three.js 793 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = { REVISION: '63dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. String.prototype.trim = String.prototype.trim || function () {
  15. return this.replace( /^\s+|\s+$/g, '' );
  16. };
  17. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  18. THREE.extend = function ( obj, source ) {
  19. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  20. if ( Object.keys ) {
  21. var keys = Object.keys( source );
  22. for (var i = 0, il = keys.length; i < il; i++) {
  23. var prop = keys[i];
  24. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  25. }
  26. } else {
  27. var safeHasOwnProperty = {}.hasOwnProperty;
  28. for ( var prop in source ) {
  29. if ( safeHasOwnProperty.call( source, prop ) ) {
  30. obj[prop] = source[prop];
  31. }
  32. }
  33. }
  34. return obj;
  35. };
  36. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  37. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  38. // requestAnimationFrame polyfill by Erik Möller
  39. // fixes from Paul Irish and Tino Zijdel
  40. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  41. ( function () {
  42. var lastTime = 0;
  43. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  44. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  45. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  46. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  47. }
  48. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  49. self.requestAnimationFrame = function ( callback ) {
  50. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  51. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  52. lastTime = currTime + timeToCall;
  53. return id;
  54. };
  55. }
  56. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  57. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  58. }
  59. }() );
  60. // GL STATE CONSTANTS
  61. THREE.CullFaceNone = 0;
  62. THREE.CullFaceBack = 1;
  63. THREE.CullFaceFront = 2;
  64. THREE.CullFaceFrontBack = 3;
  65. THREE.FrontFaceDirectionCW = 0;
  66. THREE.FrontFaceDirectionCCW = 1;
  67. // SHADOWING TYPES
  68. THREE.BasicShadowMap = 0;
  69. THREE.PCFShadowMap = 1;
  70. THREE.PCFSoftShadowMap = 2;
  71. // MATERIAL CONSTANTS
  72. // side
  73. THREE.FrontSide = 0;
  74. THREE.BackSide = 1;
  75. THREE.DoubleSide = 2;
  76. // shading
  77. THREE.NoShading = 0;
  78. THREE.FlatShading = 1;
  79. THREE.SmoothShading = 2;
  80. // colors
  81. THREE.NoColors = 0;
  82. THREE.FaceColors = 1;
  83. THREE.VertexColors = 2;
  84. // blending modes
  85. THREE.NoBlending = 0;
  86. THREE.NormalBlending = 1;
  87. THREE.AdditiveBlending = 2;
  88. THREE.SubtractiveBlending = 3;
  89. THREE.MultiplyBlending = 4;
  90. THREE.CustomBlending = 5;
  91. // custom blending equations
  92. // (numbers start from 100 not to clash with other
  93. // mappings to OpenGL constants defined in Texture.js)
  94. THREE.AddEquation = 100;
  95. THREE.SubtractEquation = 101;
  96. THREE.ReverseSubtractEquation = 102;
  97. // custom blending destination factors
  98. THREE.ZeroFactor = 200;
  99. THREE.OneFactor = 201;
  100. THREE.SrcColorFactor = 202;
  101. THREE.OneMinusSrcColorFactor = 203;
  102. THREE.SrcAlphaFactor = 204;
  103. THREE.OneMinusSrcAlphaFactor = 205;
  104. THREE.DstAlphaFactor = 206;
  105. THREE.OneMinusDstAlphaFactor = 207;
  106. // custom blending source factors
  107. //THREE.ZeroFactor = 200;
  108. //THREE.OneFactor = 201;
  109. //THREE.SrcAlphaFactor = 204;
  110. //THREE.OneMinusSrcAlphaFactor = 205;
  111. //THREE.DstAlphaFactor = 206;
  112. //THREE.OneMinusDstAlphaFactor = 207;
  113. THREE.DstColorFactor = 208;
  114. THREE.OneMinusDstColorFactor = 209;
  115. THREE.SrcAlphaSaturateFactor = 210;
  116. // TEXTURE CONSTANTS
  117. THREE.MultiplyOperation = 0;
  118. THREE.MixOperation = 1;
  119. THREE.AddOperation = 2;
  120. // Mapping modes
  121. THREE.UVMapping = function () {};
  122. THREE.CubeReflectionMapping = function () {};
  123. THREE.CubeRefractionMapping = function () {};
  124. THREE.SphericalReflectionMapping = function () {};
  125. THREE.SphericalRefractionMapping = function () {};
  126. // Wrapping modes
  127. THREE.RepeatWrapping = 1000;
  128. THREE.ClampToEdgeWrapping = 1001;
  129. THREE.MirroredRepeatWrapping = 1002;
  130. // Filters
  131. THREE.NearestFilter = 1003;
  132. THREE.NearestMipMapNearestFilter = 1004;
  133. THREE.NearestMipMapLinearFilter = 1005;
  134. THREE.LinearFilter = 1006;
  135. THREE.LinearMipMapNearestFilter = 1007;
  136. THREE.LinearMipMapLinearFilter = 1008;
  137. // Data types
  138. THREE.UnsignedByteType = 1009;
  139. THREE.ByteType = 1010;
  140. THREE.ShortType = 1011;
  141. THREE.UnsignedShortType = 1012;
  142. THREE.IntType = 1013;
  143. THREE.UnsignedIntType = 1014;
  144. THREE.FloatType = 1015;
  145. // Pixel types
  146. //THREE.UnsignedByteType = 1009;
  147. THREE.UnsignedShort4444Type = 1016;
  148. THREE.UnsignedShort5551Type = 1017;
  149. THREE.UnsignedShort565Type = 1018;
  150. // Pixel formats
  151. THREE.AlphaFormat = 1019;
  152. THREE.RGBFormat = 1020;
  153. THREE.RGBAFormat = 1021;
  154. THREE.LuminanceFormat = 1022;
  155. THREE.LuminanceAlphaFormat = 1023;
  156. // Compressed texture formats
  157. THREE.RGB_S3TC_DXT1_Format = 2001;
  158. THREE.RGBA_S3TC_DXT1_Format = 2002;
  159. THREE.RGBA_S3TC_DXT3_Format = 2003;
  160. THREE.RGBA_S3TC_DXT5_Format = 2004;
  161. /*
  162. // Potential future PVRTC compressed texture formats
  163. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  164. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  165. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  166. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  167. */
  168. /**
  169. * @author mrdoob / http://mrdoob.com/
  170. */
  171. THREE.Color = function ( value ) {
  172. if ( value !== undefined ) this.set( value );
  173. return this;
  174. };
  175. THREE.Color.prototype = {
  176. constructor: THREE.Color,
  177. r: 1, g: 1, b: 1,
  178. set: function ( value ) {
  179. if ( value instanceof THREE.Color ) {
  180. this.copy( value );
  181. } else if ( typeof value === 'number' ) {
  182. this.setHex( value );
  183. } else if ( typeof value === 'string' ) {
  184. this.setStyle( value );
  185. }
  186. return this;
  187. },
  188. setHex: function ( hex ) {
  189. hex = Math.floor( hex );
  190. this.r = ( hex >> 16 & 255 ) / 255;
  191. this.g = ( hex >> 8 & 255 ) / 255;
  192. this.b = ( hex & 255 ) / 255;
  193. return this;
  194. },
  195. setRGB: function ( r, g, b ) {
  196. this.r = r;
  197. this.g = g;
  198. this.b = b;
  199. return this;
  200. },
  201. setHSL: function ( h, s, l ) {
  202. // h,s,l ranges are in 0.0 - 1.0
  203. if ( s === 0 ) {
  204. this.r = this.g = this.b = l;
  205. } else {
  206. var hue2rgb = function ( p, q, t ) {
  207. if ( t < 0 ) t += 1;
  208. if ( t > 1 ) t -= 1;
  209. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  210. if ( t < 1 / 2 ) return q;
  211. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  212. return p;
  213. };
  214. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  215. var q = ( 2 * l ) - p;
  216. this.r = hue2rgb( q, p, h + 1 / 3 );
  217. this.g = hue2rgb( q, p, h );
  218. this.b = hue2rgb( q, p, h - 1 / 3 );
  219. }
  220. return this;
  221. },
  222. setStyle: function ( style ) {
  223. // rgb(255,0,0)
  224. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  225. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  226. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  227. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  228. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  229. return this;
  230. }
  231. // rgb(100%,0%,0%)
  232. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  233. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  234. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  235. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  236. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  237. return this;
  238. }
  239. // #ff0000
  240. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  241. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  242. this.setHex( parseInt( color[ 1 ], 16 ) );
  243. return this;
  244. }
  245. // #f00
  246. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  247. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  248. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  249. return this;
  250. }
  251. // red
  252. if ( /^(\w+)$/i.test( style ) ) {
  253. this.setHex( THREE.ColorKeywords[ style ] );
  254. return this;
  255. }
  256. },
  257. copy: function ( color ) {
  258. this.r = color.r;
  259. this.g = color.g;
  260. this.b = color.b;
  261. return this;
  262. },
  263. copyGammaToLinear: function ( color ) {
  264. this.r = color.r * color.r;
  265. this.g = color.g * color.g;
  266. this.b = color.b * color.b;
  267. return this;
  268. },
  269. copyLinearToGamma: function ( color ) {
  270. this.r = Math.sqrt( color.r );
  271. this.g = Math.sqrt( color.g );
  272. this.b = Math.sqrt( color.b );
  273. return this;
  274. },
  275. convertGammaToLinear: function () {
  276. var r = this.r, g = this.g, b = this.b;
  277. this.r = r * r;
  278. this.g = g * g;
  279. this.b = b * b;
  280. return this;
  281. },
  282. convertLinearToGamma: function () {
  283. this.r = Math.sqrt( this.r );
  284. this.g = Math.sqrt( this.g );
  285. this.b = Math.sqrt( this.b );
  286. return this;
  287. },
  288. getHex: function () {
  289. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  290. },
  291. getHexString: function () {
  292. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  293. },
  294. getHSL: function () {
  295. var hsl = { h: 0, s: 0, l: 0 };
  296. return function () {
  297. // h,s,l ranges are in 0.0 - 1.0
  298. var r = this.r, g = this.g, b = this.b;
  299. var max = Math.max( r, g, b );
  300. var min = Math.min( r, g, b );
  301. var hue, saturation;
  302. var lightness = ( min + max ) / 2.0;
  303. if ( min === max ) {
  304. hue = 0;
  305. saturation = 0;
  306. } else {
  307. var delta = max - min;
  308. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  309. switch ( max ) {
  310. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  311. case g: hue = ( b - r ) / delta + 2; break;
  312. case b: hue = ( r - g ) / delta + 4; break;
  313. }
  314. hue /= 6;
  315. }
  316. hsl.h = hue;
  317. hsl.s = saturation;
  318. hsl.l = lightness;
  319. return hsl;
  320. };
  321. }(),
  322. getStyle: function () {
  323. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  324. },
  325. offsetHSL: function ( h, s, l ) {
  326. var hsl = this.getHSL();
  327. hsl.h += h; hsl.s += s; hsl.l += l;
  328. this.setHSL( hsl.h, hsl.s, hsl.l );
  329. return this;
  330. },
  331. add: function ( color ) {
  332. this.r += color.r;
  333. this.g += color.g;
  334. this.b += color.b;
  335. return this;
  336. },
  337. addColors: function ( color1, color2 ) {
  338. this.r = color1.r + color2.r;
  339. this.g = color1.g + color2.g;
  340. this.b = color1.b + color2.b;
  341. return this;
  342. },
  343. addScalar: function ( s ) {
  344. this.r += s;
  345. this.g += s;
  346. this.b += s;
  347. return this;
  348. },
  349. multiply: function ( color ) {
  350. this.r *= color.r;
  351. this.g *= color.g;
  352. this.b *= color.b;
  353. return this;
  354. },
  355. multiplyScalar: function ( s ) {
  356. this.r *= s;
  357. this.g *= s;
  358. this.b *= s;
  359. return this;
  360. },
  361. lerp: function ( color, alpha ) {
  362. this.r += ( color.r - this.r ) * alpha;
  363. this.g += ( color.g - this.g ) * alpha;
  364. this.b += ( color.b - this.b ) * alpha;
  365. return this;
  366. },
  367. equals: function ( c ) {
  368. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  369. },
  370. fromArray: function ( array ) {
  371. this.r = array[ 0 ];
  372. this.g = array[ 1 ];
  373. this.b = array[ 2 ];
  374. return this;
  375. },
  376. toArray: function () {
  377. return [ this.r, this.g, this.b ];
  378. },
  379. clone: function () {
  380. return new THREE.Color().setRGB( this.r, this.g, this.b );
  381. }
  382. };
  383. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  384. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  385. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  386. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  387. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  388. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  389. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  390. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  391. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  392. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  393. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  394. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  395. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  396. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  397. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  398. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  399. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  400. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  401. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  402. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  403. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  404. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  405. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  406. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  407. /**
  408. * @author mikael emtinger / http://gomo.se/
  409. * @author alteredq / http://alteredqualia.com/
  410. * @author WestLangley / http://github.com/WestLangley
  411. * @author bhouston / http://exocortex.com
  412. */
  413. THREE.Quaternion = function ( x, y, z, w ) {
  414. this._x = x || 0;
  415. this._y = y || 0;
  416. this._z = z || 0;
  417. this._w = ( w !== undefined ) ? w : 1;
  418. };
  419. THREE.Quaternion.prototype = {
  420. constructor: THREE.Quaternion,
  421. _x: 0,_y: 0, _z: 0, _w: 0,
  422. _euler: undefined,
  423. _updateEuler: function ( callback ) {
  424. if ( this._euler !== undefined ) {
  425. this._euler.setFromQuaternion( this, undefined, false );
  426. }
  427. },
  428. get x () {
  429. return this._x;
  430. },
  431. set x ( value ) {
  432. this._x = value;
  433. this._updateEuler();
  434. },
  435. get y () {
  436. return this._y;
  437. },
  438. set y ( value ) {
  439. this._y = value;
  440. this._updateEuler();
  441. },
  442. get z () {
  443. return this._z;
  444. },
  445. set z ( value ) {
  446. this._z = value;
  447. this._updateEuler();
  448. },
  449. get w () {
  450. return this._w;
  451. },
  452. set w ( value ) {
  453. this._w = value;
  454. this._updateEuler();
  455. },
  456. set: function ( x, y, z, w ) {
  457. this._x = x;
  458. this._y = y;
  459. this._z = z;
  460. this._w = w;
  461. this._updateEuler();
  462. return this;
  463. },
  464. copy: function ( quaternion ) {
  465. this._x = quaternion._x;
  466. this._y = quaternion._y;
  467. this._z = quaternion._z;
  468. this._w = quaternion._w;
  469. this._updateEuler();
  470. return this;
  471. },
  472. setFromEuler: function ( euler, update ) {
  473. if ( euler instanceof THREE.Euler === false ) {
  474. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  475. }
  476. // http://www.mathworks.com/matlabcentral/fileexchange/
  477. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  478. // content/SpinCalc.m
  479. var c1 = Math.cos( euler._x / 2 );
  480. var c2 = Math.cos( euler._y / 2 );
  481. var c3 = Math.cos( euler._z / 2 );
  482. var s1 = Math.sin( euler._x / 2 );
  483. var s2 = Math.sin( euler._y / 2 );
  484. var s3 = Math.sin( euler._z / 2 );
  485. if ( euler.order === 'XYZ' ) {
  486. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  487. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  488. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  489. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  490. } else if ( euler.order === 'YXZ' ) {
  491. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  492. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  493. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  494. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  495. } else if ( euler.order === 'ZXY' ) {
  496. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  497. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  498. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  499. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  500. } else if ( euler.order === 'ZYX' ) {
  501. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  502. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  503. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  504. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  505. } else if ( euler.order === 'YZX' ) {
  506. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  507. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  508. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  509. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  510. } else if ( euler.order === 'XZY' ) {
  511. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  512. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  513. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  514. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  515. }
  516. if ( update !== false ) this._updateEuler();
  517. return this;
  518. },
  519. setFromAxisAngle: function ( axis, angle ) {
  520. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  521. // axis have to be normalized
  522. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  523. this._x = axis.x * s;
  524. this._y = axis.y * s;
  525. this._z = axis.z * s;
  526. this._w = Math.cos( halfAngle );
  527. this._updateEuler();
  528. return this;
  529. },
  530. setFromRotationMatrix: function ( m ) {
  531. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  532. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  533. var te = m.elements,
  534. m11 = te[0], m12 = te[4], m13 = te[8],
  535. m21 = te[1], m22 = te[5], m23 = te[9],
  536. m31 = te[2], m32 = te[6], m33 = te[10],
  537. trace = m11 + m22 + m33,
  538. s;
  539. if ( trace > 0 ) {
  540. s = 0.5 / Math.sqrt( trace + 1.0 );
  541. this._w = 0.25 / s;
  542. this._x = ( m32 - m23 ) * s;
  543. this._y = ( m13 - m31 ) * s;
  544. this._z = ( m21 - m12 ) * s;
  545. } else if ( m11 > m22 && m11 > m33 ) {
  546. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  547. this._w = (m32 - m23 ) / s;
  548. this._x = 0.25 * s;
  549. this._y = (m12 + m21 ) / s;
  550. this._z = (m13 + m31 ) / s;
  551. } else if ( m22 > m33 ) {
  552. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  553. this._w = (m13 - m31 ) / s;
  554. this._x = (m12 + m21 ) / s;
  555. this._y = 0.25 * s;
  556. this._z = (m23 + m32 ) / s;
  557. } else {
  558. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  559. this._w = ( m21 - m12 ) / s;
  560. this._x = ( m13 + m31 ) / s;
  561. this._y = ( m23 + m32 ) / s;
  562. this._z = 0.25 * s;
  563. }
  564. this._updateEuler();
  565. return this;
  566. },
  567. inverse: function () {
  568. this.conjugate().normalize();
  569. return this;
  570. },
  571. conjugate: function () {
  572. this._x *= -1;
  573. this._y *= -1;
  574. this._z *= -1;
  575. this._updateEuler();
  576. return this;
  577. },
  578. lengthSq: function () {
  579. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  580. },
  581. length: function () {
  582. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  583. },
  584. normalize: function () {
  585. var l = this.length();
  586. if ( l === 0 ) {
  587. this._x = 0;
  588. this._y = 0;
  589. this._z = 0;
  590. this._w = 1;
  591. } else {
  592. l = 1 / l;
  593. this._x = this._x * l;
  594. this._y = this._y * l;
  595. this._z = this._z * l;
  596. this._w = this._w * l;
  597. }
  598. return this;
  599. },
  600. multiply: function ( q, p ) {
  601. if ( p !== undefined ) {
  602. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  603. return this.multiplyQuaternions( q, p );
  604. }
  605. return this.multiplyQuaternions( this, q );
  606. },
  607. multiplyQuaternions: function ( a, b ) {
  608. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  609. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  610. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  611. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  612. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  613. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  614. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  615. this._updateEuler();
  616. return this;
  617. },
  618. multiplyVector3: function ( vector ) {
  619. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  620. return vector.applyQuaternion( this );
  621. },
  622. slerp: function ( qb, t ) {
  623. var x = this._x, y = this._y, z = this._z, w = this._w;
  624. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  625. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  626. if ( cosHalfTheta < 0 ) {
  627. this._w = -qb._w;
  628. this._x = -qb._x;
  629. this._y = -qb._y;
  630. this._z = -qb._z;
  631. cosHalfTheta = -cosHalfTheta;
  632. } else {
  633. this.copy( qb );
  634. }
  635. if ( cosHalfTheta >= 1.0 ) {
  636. this._w = w;
  637. this._x = x;
  638. this._y = y;
  639. this._z = z;
  640. return this;
  641. }
  642. var halfTheta = Math.acos( cosHalfTheta );
  643. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  644. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  645. this._w = 0.5 * ( w + this._w );
  646. this._x = 0.5 * ( x + this._x );
  647. this._y = 0.5 * ( y + this._y );
  648. this._z = 0.5 * ( z + this._z );
  649. return this;
  650. }
  651. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  652. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  653. this._w = ( w * ratioA + this._w * ratioB );
  654. this._x = ( x * ratioA + this._x * ratioB );
  655. this._y = ( y * ratioA + this._y * ratioB );
  656. this._z = ( z * ratioA + this._z * ratioB );
  657. this._updateEuler();
  658. return this;
  659. },
  660. equals: function ( quaternion ) {
  661. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  662. },
  663. fromArray: function ( array ) {
  664. this._x = array[ 0 ];
  665. this._y = array[ 1 ];
  666. this._z = array[ 2 ];
  667. this._w = array[ 3 ];
  668. this._updateEuler();
  669. return this;
  670. },
  671. toArray: function () {
  672. return [ this._x, this._y, this._z, this._w ];
  673. },
  674. clone: function () {
  675. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  676. }
  677. };
  678. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  679. return qm.copy( qa ).slerp( qb, t );
  680. }
  681. /**
  682. * @author mrdoob / http://mrdoob.com/
  683. * @author philogb / http://blog.thejit.org/
  684. * @author egraether / http://egraether.com/
  685. * @author zz85 / http://www.lab4games.net/zz85/blog
  686. */
  687. THREE.Vector2 = function ( x, y ) {
  688. this.x = x || 0;
  689. this.y = y || 0;
  690. };
  691. THREE.Vector2.prototype = {
  692. constructor: THREE.Vector2,
  693. set: function ( x, y ) {
  694. this.x = x;
  695. this.y = y;
  696. return this;
  697. },
  698. setX: function ( x ) {
  699. this.x = x;
  700. return this;
  701. },
  702. setY: function ( y ) {
  703. this.y = y;
  704. return this;
  705. },
  706. setComponent: function ( index, value ) {
  707. switch ( index ) {
  708. case 0: this.x = value; break;
  709. case 1: this.y = value; break;
  710. default: throw new Error( "index is out of range: " + index );
  711. }
  712. },
  713. getComponent: function ( index ) {
  714. switch ( index ) {
  715. case 0: return this.x;
  716. case 1: return this.y;
  717. default: throw new Error( "index is out of range: " + index );
  718. }
  719. },
  720. copy: function ( v ) {
  721. this.x = v.x;
  722. this.y = v.y;
  723. return this;
  724. },
  725. add: function ( v, w ) {
  726. if ( w !== undefined ) {
  727. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  728. return this.addVectors( v, w );
  729. }
  730. this.x += v.x;
  731. this.y += v.y;
  732. return this;
  733. },
  734. addVectors: function ( a, b ) {
  735. this.x = a.x + b.x;
  736. this.y = a.y + b.y;
  737. return this;
  738. },
  739. addScalar: function ( s ) {
  740. this.x += s;
  741. this.y += s;
  742. return this;
  743. },
  744. sub: function ( v, w ) {
  745. if ( w !== undefined ) {
  746. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  747. return this.subVectors( v, w );
  748. }
  749. this.x -= v.x;
  750. this.y -= v.y;
  751. return this;
  752. },
  753. subVectors: function ( a, b ) {
  754. this.x = a.x - b.x;
  755. this.y = a.y - b.y;
  756. return this;
  757. },
  758. multiplyScalar: function ( s ) {
  759. this.x *= s;
  760. this.y *= s;
  761. return this;
  762. },
  763. divideScalar: function ( scalar ) {
  764. if ( scalar !== 0 ) {
  765. var invScalar = 1 / scalar;
  766. this.x *= invScalar;
  767. this.y *= invScalar;
  768. } else {
  769. this.x = 0;
  770. this.y = 0;
  771. }
  772. return this;
  773. },
  774. min: function ( v ) {
  775. if ( this.x > v.x ) {
  776. this.x = v.x;
  777. }
  778. if ( this.y > v.y ) {
  779. this.y = v.y;
  780. }
  781. return this;
  782. },
  783. max: function ( v ) {
  784. if ( this.x < v.x ) {
  785. this.x = v.x;
  786. }
  787. if ( this.y < v.y ) {
  788. this.y = v.y;
  789. }
  790. return this;
  791. },
  792. clamp: function ( min, max ) {
  793. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  794. if ( this.x < min.x ) {
  795. this.x = min.x;
  796. } else if ( this.x > max.x ) {
  797. this.x = max.x;
  798. }
  799. if ( this.y < min.y ) {
  800. this.y = min.y;
  801. } else if ( this.y > max.y ) {
  802. this.y = max.y;
  803. }
  804. return this;
  805. },
  806. negate: function() {
  807. return this.multiplyScalar( - 1 );
  808. },
  809. dot: function ( v ) {
  810. return this.x * v.x + this.y * v.y;
  811. },
  812. lengthSq: function () {
  813. return this.x * this.x + this.y * this.y;
  814. },
  815. length: function () {
  816. return Math.sqrt( this.x * this.x + this.y * this.y );
  817. },
  818. normalize: function () {
  819. return this.divideScalar( this.length() );
  820. },
  821. distanceTo: function ( v ) {
  822. return Math.sqrt( this.distanceToSquared( v ) );
  823. },
  824. distanceToSquared: function ( v ) {
  825. var dx = this.x - v.x, dy = this.y - v.y;
  826. return dx * dx + dy * dy;
  827. },
  828. setLength: function ( l ) {
  829. var oldLength = this.length();
  830. if ( oldLength !== 0 && l !== oldLength ) {
  831. this.multiplyScalar( l / oldLength );
  832. }
  833. return this;
  834. },
  835. lerp: function ( v, alpha ) {
  836. this.x += ( v.x - this.x ) * alpha;
  837. this.y += ( v.y - this.y ) * alpha;
  838. return this;
  839. },
  840. equals: function( v ) {
  841. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  842. },
  843. fromArray: function ( array ) {
  844. this.x = array[ 0 ];
  845. this.y = array[ 1 ];
  846. return this;
  847. },
  848. toArray: function () {
  849. return [ this.x, this.y ];
  850. },
  851. clone: function () {
  852. return new THREE.Vector2( this.x, this.y );
  853. }
  854. };
  855. /**
  856. * @author mrdoob / http://mrdoob.com/
  857. * @author *kile / http://kile.stravaganza.org/
  858. * @author philogb / http://blog.thejit.org/
  859. * @author mikael emtinger / http://gomo.se/
  860. * @author egraether / http://egraether.com/
  861. * @author WestLangley / http://github.com/WestLangley
  862. */
  863. THREE.Vector3 = function ( x, y, z ) {
  864. this.x = x || 0;
  865. this.y = y || 0;
  866. this.z = z || 0;
  867. };
  868. THREE.Vector3.prototype = {
  869. constructor: THREE.Vector3,
  870. set: function ( x, y, z ) {
  871. this.x = x;
  872. this.y = y;
  873. this.z = z;
  874. return this;
  875. },
  876. setX: function ( x ) {
  877. this.x = x;
  878. return this;
  879. },
  880. setY: function ( y ) {
  881. this.y = y;
  882. return this;
  883. },
  884. setZ: function ( z ) {
  885. this.z = z;
  886. return this;
  887. },
  888. setComponent: function ( index, value ) {
  889. switch ( index ) {
  890. case 0: this.x = value; break;
  891. case 1: this.y = value; break;
  892. case 2: this.z = value; break;
  893. default: throw new Error( "index is out of range: " + index );
  894. }
  895. },
  896. getComponent: function ( index ) {
  897. switch ( index ) {
  898. case 0: return this.x;
  899. case 1: return this.y;
  900. case 2: return this.z;
  901. default: throw new Error( "index is out of range: " + index );
  902. }
  903. },
  904. copy: function ( v ) {
  905. this.x = v.x;
  906. this.y = v.y;
  907. this.z = v.z;
  908. return this;
  909. },
  910. add: function ( v, w ) {
  911. if ( w !== undefined ) {
  912. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  913. return this.addVectors( v, w );
  914. }
  915. this.x += v.x;
  916. this.y += v.y;
  917. this.z += v.z;
  918. return this;
  919. },
  920. addScalar: function ( s ) {
  921. this.x += s;
  922. this.y += s;
  923. this.z += s;
  924. return this;
  925. },
  926. addVectors: function ( a, b ) {
  927. this.x = a.x + b.x;
  928. this.y = a.y + b.y;
  929. this.z = a.z + b.z;
  930. return this;
  931. },
  932. sub: function ( v, w ) {
  933. if ( w !== undefined ) {
  934. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  935. return this.subVectors( v, w );
  936. }
  937. this.x -= v.x;
  938. this.y -= v.y;
  939. this.z -= v.z;
  940. return this;
  941. },
  942. subVectors: function ( a, b ) {
  943. this.x = a.x - b.x;
  944. this.y = a.y - b.y;
  945. this.z = a.z - b.z;
  946. return this;
  947. },
  948. multiply: function ( v, w ) {
  949. if ( w !== undefined ) {
  950. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  951. return this.multiplyVectors( v, w );
  952. }
  953. this.x *= v.x;
  954. this.y *= v.y;
  955. this.z *= v.z;
  956. return this;
  957. },
  958. multiplyScalar: function ( scalar ) {
  959. this.x *= scalar;
  960. this.y *= scalar;
  961. this.z *= scalar;
  962. return this;
  963. },
  964. multiplyVectors: function ( a, b ) {
  965. this.x = a.x * b.x;
  966. this.y = a.y * b.y;
  967. this.z = a.z * b.z;
  968. return this;
  969. },
  970. applyMatrix3: function ( m ) {
  971. var x = this.x;
  972. var y = this.y;
  973. var z = this.z;
  974. var e = m.elements;
  975. this.x = e[0] * x + e[3] * y + e[6] * z;
  976. this.y = e[1] * x + e[4] * y + e[7] * z;
  977. this.z = e[2] * x + e[5] * y + e[8] * z;
  978. return this;
  979. },
  980. applyMatrix4: function ( m ) {
  981. // input: THREE.Matrix4 affine matrix
  982. var x = this.x, y = this.y, z = this.z;
  983. var e = m.elements;
  984. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  985. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  986. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  987. return this;
  988. },
  989. applyProjection: function ( m ) {
  990. // input: THREE.Matrix4 projection matrix
  991. var x = this.x, y = this.y, z = this.z;
  992. var e = m.elements;
  993. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  994. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  995. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  996. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  997. return this;
  998. },
  999. applyQuaternion: function ( q ) {
  1000. var x = this.x;
  1001. var y = this.y;
  1002. var z = this.z;
  1003. var qx = q.x;
  1004. var qy = q.y;
  1005. var qz = q.z;
  1006. var qw = q.w;
  1007. // calculate quat * vector
  1008. var ix = qw * x + qy * z - qz * y;
  1009. var iy = qw * y + qz * x - qx * z;
  1010. var iz = qw * z + qx * y - qy * x;
  1011. var iw = -qx * x - qy * y - qz * z;
  1012. // calculate result * inverse quat
  1013. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1014. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1015. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1016. return this;
  1017. },
  1018. transformDirection: function ( m ) {
  1019. // input: THREE.Matrix4 affine matrix
  1020. // vector interpreted as a direction
  1021. var x = this.x, y = this.y, z = this.z;
  1022. var e = m.elements;
  1023. this.x = e[0] * x + e[4] * y + e[8] * z;
  1024. this.y = e[1] * x + e[5] * y + e[9] * z;
  1025. this.z = e[2] * x + e[6] * y + e[10] * z;
  1026. this.normalize();
  1027. return this;
  1028. },
  1029. divide: function ( v ) {
  1030. this.x /= v.x;
  1031. this.y /= v.y;
  1032. this.z /= v.z;
  1033. return this;
  1034. },
  1035. divideScalar: function ( scalar ) {
  1036. if ( scalar !== 0 ) {
  1037. var invScalar = 1 / scalar;
  1038. this.x *= invScalar;
  1039. this.y *= invScalar;
  1040. this.z *= invScalar;
  1041. } else {
  1042. this.x = 0;
  1043. this.y = 0;
  1044. this.z = 0;
  1045. }
  1046. return this;
  1047. },
  1048. min: function ( v ) {
  1049. if ( this.x > v.x ) {
  1050. this.x = v.x;
  1051. }
  1052. if ( this.y > v.y ) {
  1053. this.y = v.y;
  1054. }
  1055. if ( this.z > v.z ) {
  1056. this.z = v.z;
  1057. }
  1058. return this;
  1059. },
  1060. max: function ( v ) {
  1061. if ( this.x < v.x ) {
  1062. this.x = v.x;
  1063. }
  1064. if ( this.y < v.y ) {
  1065. this.y = v.y;
  1066. }
  1067. if ( this.z < v.z ) {
  1068. this.z = v.z;
  1069. }
  1070. return this;
  1071. },
  1072. clamp: function ( min, max ) {
  1073. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1074. if ( this.x < min.x ) {
  1075. this.x = min.x;
  1076. } else if ( this.x > max.x ) {
  1077. this.x = max.x;
  1078. }
  1079. if ( this.y < min.y ) {
  1080. this.y = min.y;
  1081. } else if ( this.y > max.y ) {
  1082. this.y = max.y;
  1083. }
  1084. if ( this.z < min.z ) {
  1085. this.z = min.z;
  1086. } else if ( this.z > max.z ) {
  1087. this.z = max.z;
  1088. }
  1089. return this;
  1090. },
  1091. negate: function () {
  1092. return this.multiplyScalar( - 1 );
  1093. },
  1094. dot: function ( v ) {
  1095. return this.x * v.x + this.y * v.y + this.z * v.z;
  1096. },
  1097. lengthSq: function () {
  1098. return this.x * this.x + this.y * this.y + this.z * this.z;
  1099. },
  1100. length: function () {
  1101. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1102. },
  1103. lengthManhattan: function () {
  1104. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1105. },
  1106. normalize: function () {
  1107. return this.divideScalar( this.length() );
  1108. },
  1109. setLength: function ( l ) {
  1110. var oldLength = this.length();
  1111. if ( oldLength !== 0 && l !== oldLength ) {
  1112. this.multiplyScalar( l / oldLength );
  1113. }
  1114. return this;
  1115. },
  1116. lerp: function ( v, alpha ) {
  1117. this.x += ( v.x - this.x ) * alpha;
  1118. this.y += ( v.y - this.y ) * alpha;
  1119. this.z += ( v.z - this.z ) * alpha;
  1120. return this;
  1121. },
  1122. cross: function ( v, w ) {
  1123. if ( w !== undefined ) {
  1124. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1125. return this.crossVectors( v, w );
  1126. }
  1127. var x = this.x, y = this.y, z = this.z;
  1128. this.x = y * v.z - z * v.y;
  1129. this.y = z * v.x - x * v.z;
  1130. this.z = x * v.y - y * v.x;
  1131. return this;
  1132. },
  1133. crossVectors: function ( a, b ) {
  1134. var ax = a.x, ay = a.y, az = a.z;
  1135. var bx = b.x, by = b.y, bz = b.z;
  1136. this.x = ay * bz - az * by;
  1137. this.y = az * bx - ax * bz;
  1138. this.z = ax * by - ay * bx;
  1139. return this;
  1140. },
  1141. angleTo: function ( v ) {
  1142. var theta = this.dot( v ) / ( this.length() * v.length() );
  1143. // clamp, to handle numerical problems
  1144. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1145. },
  1146. distanceTo: function ( v ) {
  1147. return Math.sqrt( this.distanceToSquared( v ) );
  1148. },
  1149. distanceToSquared: function ( v ) {
  1150. var dx = this.x - v.x;
  1151. var dy = this.y - v.y;
  1152. var dz = this.z - v.z;
  1153. return dx * dx + dy * dy + dz * dz;
  1154. },
  1155. setEulerFromRotationMatrix: function ( m, order ) {
  1156. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1157. },
  1158. setEulerFromQuaternion: function ( q, order ) {
  1159. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1160. },
  1161. getPositionFromMatrix: function ( m ) {
  1162. this.x = m.elements[12];
  1163. this.y = m.elements[13];
  1164. this.z = m.elements[14];
  1165. return this;
  1166. },
  1167. getScaleFromMatrix: function ( m ) {
  1168. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1169. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1170. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1171. this.x = sx;
  1172. this.y = sy;
  1173. this.z = sz;
  1174. return this;
  1175. },
  1176. getColumnFromMatrix: function ( index, matrix ) {
  1177. var offset = index * 4;
  1178. var me = matrix.elements;
  1179. this.x = me[ offset ];
  1180. this.y = me[ offset + 1 ];
  1181. this.z = me[ offset + 2 ];
  1182. return this;
  1183. },
  1184. equals: function ( v ) {
  1185. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1186. },
  1187. fromArray: function ( array ) {
  1188. this.x = array[ 0 ];
  1189. this.y = array[ 1 ];
  1190. this.z = array[ 2 ];
  1191. return this;
  1192. },
  1193. toArray: function () {
  1194. return [ this.x, this.y, this.z ];
  1195. },
  1196. clone: function () {
  1197. return new THREE.Vector3( this.x, this.y, this.z );
  1198. }
  1199. };
  1200. THREE.extend( THREE.Vector3.prototype, {
  1201. applyEuler: function () {
  1202. var quaternion = new THREE.Quaternion();
  1203. return function ( euler ) {
  1204. if ( euler instanceof THREE.Euler === false ) {
  1205. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1206. }
  1207. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1208. return this;
  1209. };
  1210. }(),
  1211. applyAxisAngle: function () {
  1212. var quaternion = new THREE.Quaternion();
  1213. return function ( axis, angle ) {
  1214. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1215. return this;
  1216. };
  1217. }(),
  1218. projectOnVector: function () {
  1219. var v1 = new THREE.Vector3();
  1220. return function ( vector ) {
  1221. v1.copy( vector ).normalize();
  1222. var d = this.dot( v1 );
  1223. return this.copy( v1 ).multiplyScalar( d );
  1224. };
  1225. }(),
  1226. projectOnPlane: function () {
  1227. var v1 = new THREE.Vector3();
  1228. return function ( planeNormal ) {
  1229. v1.copy( this ).projectOnVector( planeNormal );
  1230. return this.sub( v1 );
  1231. }
  1232. }(),
  1233. reflect: function () {
  1234. var v1 = new THREE.Vector3();
  1235. return function ( vector ) {
  1236. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1237. return this.subVectors( v1, this );
  1238. }
  1239. }()
  1240. } );
  1241. /**
  1242. * @author supereggbert / http://www.paulbrunt.co.uk/
  1243. * @author philogb / http://blog.thejit.org/
  1244. * @author mikael emtinger / http://gomo.se/
  1245. * @author egraether / http://egraether.com/
  1246. * @author WestLangley / http://github.com/WestLangley
  1247. */
  1248. THREE.Vector4 = function ( x, y, z, w ) {
  1249. this.x = x || 0;
  1250. this.y = y || 0;
  1251. this.z = z || 0;
  1252. this.w = ( w !== undefined ) ? w : 1;
  1253. };
  1254. THREE.Vector4.prototype = {
  1255. constructor: THREE.Vector4,
  1256. set: function ( x, y, z, w ) {
  1257. this.x = x;
  1258. this.y = y;
  1259. this.z = z;
  1260. this.w = w;
  1261. return this;
  1262. },
  1263. setX: function ( x ) {
  1264. this.x = x;
  1265. return this;
  1266. },
  1267. setY: function ( y ) {
  1268. this.y = y;
  1269. return this;
  1270. },
  1271. setZ: function ( z ) {
  1272. this.z = z;
  1273. return this;
  1274. },
  1275. setW: function ( w ) {
  1276. this.w = w;
  1277. return this;
  1278. },
  1279. setComponent: function ( index, value ) {
  1280. switch ( index ) {
  1281. case 0: this.x = value; break;
  1282. case 1: this.y = value; break;
  1283. case 2: this.z = value; break;
  1284. case 3: this.w = value; break;
  1285. default: throw new Error( "index is out of range: " + index );
  1286. }
  1287. },
  1288. getComponent: function ( index ) {
  1289. switch ( index ) {
  1290. case 0: return this.x;
  1291. case 1: return this.y;
  1292. case 2: return this.z;
  1293. case 3: return this.w;
  1294. default: throw new Error( "index is out of range: " + index );
  1295. }
  1296. },
  1297. copy: function ( v ) {
  1298. this.x = v.x;
  1299. this.y = v.y;
  1300. this.z = v.z;
  1301. this.w = ( v.w !== undefined ) ? v.w : 1;
  1302. return this;
  1303. },
  1304. add: function ( v, w ) {
  1305. if ( w !== undefined ) {
  1306. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1307. return this.addVectors( v, w );
  1308. }
  1309. this.x += v.x;
  1310. this.y += v.y;
  1311. this.z += v.z;
  1312. this.w += v.w;
  1313. return this;
  1314. },
  1315. addScalar: function ( s ) {
  1316. this.x += s;
  1317. this.y += s;
  1318. this.z += s;
  1319. this.w += s;
  1320. return this;
  1321. },
  1322. addVectors: function ( a, b ) {
  1323. this.x = a.x + b.x;
  1324. this.y = a.y + b.y;
  1325. this.z = a.z + b.z;
  1326. this.w = a.w + b.w;
  1327. return this;
  1328. },
  1329. sub: function ( v, w ) {
  1330. if ( w !== undefined ) {
  1331. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1332. return this.subVectors( v, w );
  1333. }
  1334. this.x -= v.x;
  1335. this.y -= v.y;
  1336. this.z -= v.z;
  1337. this.w -= v.w;
  1338. return this;
  1339. },
  1340. subVectors: function ( a, b ) {
  1341. this.x = a.x - b.x;
  1342. this.y = a.y - b.y;
  1343. this.z = a.z - b.z;
  1344. this.w = a.w - b.w;
  1345. return this;
  1346. },
  1347. multiplyScalar: function ( scalar ) {
  1348. this.x *= scalar;
  1349. this.y *= scalar;
  1350. this.z *= scalar;
  1351. this.w *= scalar;
  1352. return this;
  1353. },
  1354. applyMatrix4: function ( m ) {
  1355. var x = this.x;
  1356. var y = this.y;
  1357. var z = this.z;
  1358. var w = this.w;
  1359. var e = m.elements;
  1360. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1361. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1362. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1363. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1364. return this;
  1365. },
  1366. divideScalar: function ( scalar ) {
  1367. if ( scalar !== 0 ) {
  1368. var invScalar = 1 / scalar;
  1369. this.x *= invScalar;
  1370. this.y *= invScalar;
  1371. this.z *= invScalar;
  1372. this.w *= invScalar;
  1373. } else {
  1374. this.x = 0;
  1375. this.y = 0;
  1376. this.z = 0;
  1377. this.w = 1;
  1378. }
  1379. return this;
  1380. },
  1381. setAxisAngleFromQuaternion: function ( q ) {
  1382. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1383. // q is assumed to be normalized
  1384. this.w = 2 * Math.acos( q.w );
  1385. var s = Math.sqrt( 1 - q.w * q.w );
  1386. if ( s < 0.0001 ) {
  1387. this.x = 1;
  1388. this.y = 0;
  1389. this.z = 0;
  1390. } else {
  1391. this.x = q.x / s;
  1392. this.y = q.y / s;
  1393. this.z = q.z / s;
  1394. }
  1395. return this;
  1396. },
  1397. setAxisAngleFromRotationMatrix: function ( m ) {
  1398. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1399. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1400. var angle, x, y, z, // variables for result
  1401. epsilon = 0.01, // margin to allow for rounding errors
  1402. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1403. te = m.elements,
  1404. m11 = te[0], m12 = te[4], m13 = te[8],
  1405. m21 = te[1], m22 = te[5], m23 = te[9],
  1406. m31 = te[2], m32 = te[6], m33 = te[10];
  1407. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1408. && ( Math.abs( m13 - m31 ) < epsilon )
  1409. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1410. // singularity found
  1411. // first check for identity matrix which must have +1 for all terms
  1412. // in leading diagonal and zero in other terms
  1413. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1414. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1415. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1416. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1417. // this singularity is identity matrix so angle = 0
  1418. this.set( 1, 0, 0, 0 );
  1419. return this; // zero angle, arbitrary axis
  1420. }
  1421. // otherwise this singularity is angle = 180
  1422. angle = Math.PI;
  1423. var xx = ( m11 + 1 ) / 2;
  1424. var yy = ( m22 + 1 ) / 2;
  1425. var zz = ( m33 + 1 ) / 2;
  1426. var xy = ( m12 + m21 ) / 4;
  1427. var xz = ( m13 + m31 ) / 4;
  1428. var yz = ( m23 + m32 ) / 4;
  1429. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1430. if ( xx < epsilon ) {
  1431. x = 0;
  1432. y = 0.707106781;
  1433. z = 0.707106781;
  1434. } else {
  1435. x = Math.sqrt( xx );
  1436. y = xy / x;
  1437. z = xz / x;
  1438. }
  1439. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1440. if ( yy < epsilon ) {
  1441. x = 0.707106781;
  1442. y = 0;
  1443. z = 0.707106781;
  1444. } else {
  1445. y = Math.sqrt( yy );
  1446. x = xy / y;
  1447. z = yz / y;
  1448. }
  1449. } else { // m33 is the largest diagonal term so base result on this
  1450. if ( zz < epsilon ) {
  1451. x = 0.707106781;
  1452. y = 0.707106781;
  1453. z = 0;
  1454. } else {
  1455. z = Math.sqrt( zz );
  1456. x = xz / z;
  1457. y = yz / z;
  1458. }
  1459. }
  1460. this.set( x, y, z, angle );
  1461. return this; // return 180 deg rotation
  1462. }
  1463. // as we have reached here there are no singularities so we can handle normally
  1464. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1465. + ( m13 - m31 ) * ( m13 - m31 )
  1466. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1467. if ( Math.abs( s ) < 0.001 ) s = 1;
  1468. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1469. // caught by singularity test above, but I've left it in just in case
  1470. this.x = ( m32 - m23 ) / s;
  1471. this.y = ( m13 - m31 ) / s;
  1472. this.z = ( m21 - m12 ) / s;
  1473. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1474. return this;
  1475. },
  1476. min: function ( v ) {
  1477. if ( this.x > v.x ) {
  1478. this.x = v.x;
  1479. }
  1480. if ( this.y > v.y ) {
  1481. this.y = v.y;
  1482. }
  1483. if ( this.z > v.z ) {
  1484. this.z = v.z;
  1485. }
  1486. if ( this.w > v.w ) {
  1487. this.w = v.w;
  1488. }
  1489. return this;
  1490. },
  1491. max: function ( v ) {
  1492. if ( this.x < v.x ) {
  1493. this.x = v.x;
  1494. }
  1495. if ( this.y < v.y ) {
  1496. this.y = v.y;
  1497. }
  1498. if ( this.z < v.z ) {
  1499. this.z = v.z;
  1500. }
  1501. if ( this.w < v.w ) {
  1502. this.w = v.w;
  1503. }
  1504. return this;
  1505. },
  1506. clamp: function ( min, max ) {
  1507. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1508. if ( this.x < min.x ) {
  1509. this.x = min.x;
  1510. } else if ( this.x > max.x ) {
  1511. this.x = max.x;
  1512. }
  1513. if ( this.y < min.y ) {
  1514. this.y = min.y;
  1515. } else if ( this.y > max.y ) {
  1516. this.y = max.y;
  1517. }
  1518. if ( this.z < min.z ) {
  1519. this.z = min.z;
  1520. } else if ( this.z > max.z ) {
  1521. this.z = max.z;
  1522. }
  1523. if ( this.w < min.w ) {
  1524. this.w = min.w;
  1525. } else if ( this.w > max.w ) {
  1526. this.w = max.w;
  1527. }
  1528. return this;
  1529. },
  1530. negate: function() {
  1531. return this.multiplyScalar( -1 );
  1532. },
  1533. dot: function ( v ) {
  1534. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1535. },
  1536. lengthSq: function () {
  1537. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1538. },
  1539. length: function () {
  1540. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1541. },
  1542. lengthManhattan: function () {
  1543. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1544. },
  1545. normalize: function () {
  1546. return this.divideScalar( this.length() );
  1547. },
  1548. setLength: function ( l ) {
  1549. var oldLength = this.length();
  1550. if ( oldLength !== 0 && l !== oldLength ) {
  1551. this.multiplyScalar( l / oldLength );
  1552. }
  1553. return this;
  1554. },
  1555. lerp: function ( v, alpha ) {
  1556. this.x += ( v.x - this.x ) * alpha;
  1557. this.y += ( v.y - this.y ) * alpha;
  1558. this.z += ( v.z - this.z ) * alpha;
  1559. this.w += ( v.w - this.w ) * alpha;
  1560. return this;
  1561. },
  1562. equals: function ( v ) {
  1563. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1564. },
  1565. fromArray: function ( array ) {
  1566. this.x = array[ 0 ];
  1567. this.y = array[ 1 ];
  1568. this.z = array[ 2 ];
  1569. this.w = array[ 3 ];
  1570. return this;
  1571. },
  1572. toArray: function () {
  1573. return [ this.x, this.y, this.z, this.w ];
  1574. },
  1575. clone: function () {
  1576. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1577. }
  1578. };
  1579. /**
  1580. * @author mrdoob / http://mrdoob.com/
  1581. * @author WestLangley / http://github.com/WestLangley
  1582. * @author bhouston / http://exocortex.com
  1583. */
  1584. THREE.Euler = function ( x, y, z, order ) {
  1585. this._x = x || 0;
  1586. this._y = y || 0;
  1587. this._z = z || 0;
  1588. this._order = order || THREE.Euler.DefaultOrder;
  1589. };
  1590. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1591. THREE.Euler.DefaultOrder = 'XYZ';
  1592. THREE.Euler.prototype = {
  1593. constructor: THREE.Euler,
  1594. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1595. _quaternion: undefined,
  1596. _updateQuaternion: function () {
  1597. if ( this._quaternion !== undefined ) {
  1598. this._quaternion.setFromEuler( this, false );
  1599. }
  1600. },
  1601. get x () {
  1602. return this._x;
  1603. },
  1604. set x ( value ) {
  1605. this._x = value;
  1606. this._updateQuaternion();
  1607. },
  1608. get y () {
  1609. return this._y;
  1610. },
  1611. set y ( value ) {
  1612. this._y = value;
  1613. this._updateQuaternion();
  1614. },
  1615. get z () {
  1616. return this._z;
  1617. },
  1618. set z ( value ) {
  1619. this._z = value;
  1620. this._updateQuaternion();
  1621. },
  1622. get order () {
  1623. return this._order;
  1624. },
  1625. set order ( value ) {
  1626. this._order = value;
  1627. this._updateQuaternion();
  1628. },
  1629. set: function ( x, y, z, order ) {
  1630. this._x = x;
  1631. this._y = y;
  1632. this._z = z;
  1633. this._order = order || this._order;
  1634. this._updateQuaternion();
  1635. return this;
  1636. },
  1637. copy: function ( euler ) {
  1638. this._x = euler._x;
  1639. this._y = euler._y;
  1640. this._z = euler._z;
  1641. this._order = euler._order;
  1642. this._updateQuaternion();
  1643. return this;
  1644. },
  1645. setFromRotationMatrix: function ( m, order ) {
  1646. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1647. // clamp, to handle numerical problems
  1648. function clamp( x ) {
  1649. return Math.min( Math.max( x, -1 ), 1 );
  1650. }
  1651. var te = m.elements;
  1652. var m11 = te[0], m12 = te[4], m13 = te[8];
  1653. var m21 = te[1], m22 = te[5], m23 = te[9];
  1654. var m31 = te[2], m32 = te[6], m33 = te[10];
  1655. order = order || this._order;
  1656. if ( order === 'XYZ' ) {
  1657. this._y = Math.asin( clamp( m13 ) );
  1658. if ( Math.abs( m13 ) < 0.99999 ) {
  1659. this._x = Math.atan2( - m23, m33 );
  1660. this._z = Math.atan2( - m12, m11 );
  1661. } else {
  1662. this._x = Math.atan2( m32, m22 );
  1663. this._z = 0;
  1664. }
  1665. } else if ( order === 'YXZ' ) {
  1666. this._x = Math.asin( - clamp( m23 ) );
  1667. if ( Math.abs( m23 ) < 0.99999 ) {
  1668. this._y = Math.atan2( m13, m33 );
  1669. this._z = Math.atan2( m21, m22 );
  1670. } else {
  1671. this._y = Math.atan2( - m31, m11 );
  1672. this._z = 0;
  1673. }
  1674. } else if ( order === 'ZXY' ) {
  1675. this._x = Math.asin( clamp( m32 ) );
  1676. if ( Math.abs( m32 ) < 0.99999 ) {
  1677. this._y = Math.atan2( - m31, m33 );
  1678. this._z = Math.atan2( - m12, m22 );
  1679. } else {
  1680. this._y = 0;
  1681. this._z = Math.atan2( m21, m11 );
  1682. }
  1683. } else if ( order === 'ZYX' ) {
  1684. this._y = Math.asin( - clamp( m31 ) );
  1685. if ( Math.abs( m31 ) < 0.99999 ) {
  1686. this._x = Math.atan2( m32, m33 );
  1687. this._z = Math.atan2( m21, m11 );
  1688. } else {
  1689. this._x = 0;
  1690. this._z = Math.atan2( - m12, m22 );
  1691. }
  1692. } else if ( order === 'YZX' ) {
  1693. this._z = Math.asin( clamp( m21 ) );
  1694. if ( Math.abs( m21 ) < 0.99999 ) {
  1695. this._x = Math.atan2( - m23, m22 );
  1696. this._y = Math.atan2( - m31, m11 );
  1697. } else {
  1698. this._x = 0;
  1699. this._y = Math.atan2( m13, m33 );
  1700. }
  1701. } else if ( order === 'XZY' ) {
  1702. this._z = Math.asin( - clamp( m12 ) );
  1703. if ( Math.abs( m12 ) < 0.99999 ) {
  1704. this._x = Math.atan2( m32, m22 );
  1705. this._y = Math.atan2( m13, m11 );
  1706. } else {
  1707. this._x = Math.atan2( - m23, m33 );
  1708. this._y = 0;
  1709. }
  1710. } else {
  1711. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1712. }
  1713. this._order = order;
  1714. this._updateQuaternion();
  1715. return this;
  1716. },
  1717. setFromQuaternion: function ( q, order, update ) {
  1718. // q is assumed to be normalized
  1719. // clamp, to handle numerical problems
  1720. function clamp( x ) {
  1721. return Math.min( Math.max( x, -1 ), 1 );
  1722. }
  1723. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1724. var sqx = q.x * q.x;
  1725. var sqy = q.y * q.y;
  1726. var sqz = q.z * q.z;
  1727. var sqw = q.w * q.w;
  1728. order = order || this._order;
  1729. if ( order === 'XYZ' ) {
  1730. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1731. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1732. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1733. } else if ( order === 'YXZ' ) {
  1734. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1735. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1736. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1737. } else if ( order === 'ZXY' ) {
  1738. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1739. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1740. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1741. } else if ( order === 'ZYX' ) {
  1742. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1743. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1744. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1745. } else if ( order === 'YZX' ) {
  1746. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1747. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1748. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1749. } else if ( order === 'XZY' ) {
  1750. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1751. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1752. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1753. } else {
  1754. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1755. }
  1756. this._order = order;
  1757. if ( update !== false ) this._updateQuaternion();
  1758. return this;
  1759. },
  1760. reorder: function () {
  1761. // WARNING: this discards revolution information -bhouston
  1762. var q = new THREE.Quaternion();
  1763. return function ( newOrder ) {
  1764. q.setFromEuler( this );
  1765. this.setFromQuaternion( q, newOrder );
  1766. };
  1767. }(),
  1768. fromArray: function ( array ) {
  1769. this._x = array[ 0 ];
  1770. this._y = array[ 1 ];
  1771. this._z = array[ 2 ];
  1772. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1773. this._updateQuaternion();
  1774. return this;
  1775. },
  1776. toArray: function () {
  1777. return [ this._x, this._y, this._z, this._order ];
  1778. },
  1779. equals: function ( euler ) {
  1780. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1781. },
  1782. clone: function () {
  1783. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1784. }
  1785. };
  1786. /**
  1787. * @author bhouston / http://exocortex.com
  1788. */
  1789. THREE.Line3 = function ( start, end ) {
  1790. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1791. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1792. };
  1793. THREE.Line3.prototype = {
  1794. constructor: THREE.Line3,
  1795. set: function ( start, end ) {
  1796. this.start.copy( start );
  1797. this.end.copy( end );
  1798. return this;
  1799. },
  1800. copy: function ( line ) {
  1801. this.start.copy( line.start );
  1802. this.end.copy( line.end );
  1803. return this;
  1804. },
  1805. center: function ( optionalTarget ) {
  1806. var result = optionalTarget || new THREE.Vector3();
  1807. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1808. },
  1809. delta: function ( optionalTarget ) {
  1810. var result = optionalTarget || new THREE.Vector3();
  1811. return result.subVectors( this.end, this.start );
  1812. },
  1813. distanceSq: function () {
  1814. return this.start.distanceToSquared( this.end );
  1815. },
  1816. distance: function () {
  1817. return this.start.distanceTo( this.end );
  1818. },
  1819. at: function ( t, optionalTarget ) {
  1820. var result = optionalTarget || new THREE.Vector3();
  1821. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1822. },
  1823. closestPointToPointParameter: function() {
  1824. var startP = new THREE.Vector3();
  1825. var startEnd = new THREE.Vector3();
  1826. return function ( point, clampToLine ) {
  1827. startP.subVectors( point, this.start );
  1828. startEnd.subVectors( this.end, this.start );
  1829. var startEnd2 = startEnd.dot( startEnd );
  1830. var startEnd_startP = startEnd.dot( startP );
  1831. var t = startEnd_startP / startEnd2;
  1832. if ( clampToLine ) {
  1833. t = THREE.Math.clamp( t, 0, 1 );
  1834. }
  1835. return t;
  1836. };
  1837. }(),
  1838. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1839. var t = this.closestPointToPointParameter( point, clampToLine );
  1840. var result = optionalTarget || new THREE.Vector3();
  1841. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1842. },
  1843. applyMatrix4: function ( matrix ) {
  1844. this.start.applyMatrix4( matrix );
  1845. this.end.applyMatrix4( matrix );
  1846. return this;
  1847. },
  1848. equals: function ( line ) {
  1849. return line.start.equals( this.start ) && line.end.equals( this.end );
  1850. },
  1851. clone: function () {
  1852. return new THREE.Line3().copy( this );
  1853. }
  1854. };
  1855. /**
  1856. * @author bhouston / http://exocortex.com
  1857. */
  1858. THREE.Box2 = function ( min, max ) {
  1859. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1860. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1861. };
  1862. THREE.Box2.prototype = {
  1863. constructor: THREE.Box2,
  1864. set: function ( min, max ) {
  1865. this.min.copy( min );
  1866. this.max.copy( max );
  1867. return this;
  1868. },
  1869. setFromPoints: function ( points ) {
  1870. if ( points.length > 0 ) {
  1871. var point = points[ 0 ];
  1872. this.min.copy( point );
  1873. this.max.copy( point );
  1874. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1875. point = points[ i ];
  1876. if ( point.x < this.min.x ) {
  1877. this.min.x = point.x;
  1878. } else if ( point.x > this.max.x ) {
  1879. this.max.x = point.x;
  1880. }
  1881. if ( point.y < this.min.y ) {
  1882. this.min.y = point.y;
  1883. } else if ( point.y > this.max.y ) {
  1884. this.max.y = point.y;
  1885. }
  1886. }
  1887. } else {
  1888. this.makeEmpty();
  1889. }
  1890. return this;
  1891. },
  1892. setFromCenterAndSize: function () {
  1893. var v1 = new THREE.Vector2();
  1894. return function ( center, size ) {
  1895. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1896. this.min.copy( center ).sub( halfSize );
  1897. this.max.copy( center ).add( halfSize );
  1898. return this;
  1899. };
  1900. }(),
  1901. copy: function ( box ) {
  1902. this.min.copy( box.min );
  1903. this.max.copy( box.max );
  1904. return this;
  1905. },
  1906. makeEmpty: function () {
  1907. this.min.x = this.min.y = Infinity;
  1908. this.max.x = this.max.y = -Infinity;
  1909. return this;
  1910. },
  1911. empty: function () {
  1912. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1913. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1914. },
  1915. center: function ( optionalTarget ) {
  1916. var result = optionalTarget || new THREE.Vector2();
  1917. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1918. },
  1919. size: function ( optionalTarget ) {
  1920. var result = optionalTarget || new THREE.Vector2();
  1921. return result.subVectors( this.max, this.min );
  1922. },
  1923. expandByPoint: function ( point ) {
  1924. this.min.min( point );
  1925. this.max.max( point );
  1926. return this;
  1927. },
  1928. expandByVector: function ( vector ) {
  1929. this.min.sub( vector );
  1930. this.max.add( vector );
  1931. return this;
  1932. },
  1933. expandByScalar: function ( scalar ) {
  1934. this.min.addScalar( -scalar );
  1935. this.max.addScalar( scalar );
  1936. return this;
  1937. },
  1938. containsPoint: function ( point ) {
  1939. if ( point.x < this.min.x || point.x > this.max.x ||
  1940. point.y < this.min.y || point.y > this.max.y ) {
  1941. return false;
  1942. }
  1943. return true;
  1944. },
  1945. containsBox: function ( box ) {
  1946. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1947. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1948. return true;
  1949. }
  1950. return false;
  1951. },
  1952. getParameter: function ( point ) {
  1953. // This can potentially have a divide by zero if the box
  1954. // has a size dimension of 0.
  1955. return new THREE.Vector2(
  1956. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1957. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1958. );
  1959. },
  1960. isIntersectionBox: function ( box ) {
  1961. // using 6 splitting planes to rule out intersections.
  1962. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1963. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1964. return false;
  1965. }
  1966. return true;
  1967. },
  1968. clampPoint: function ( point, optionalTarget ) {
  1969. var result = optionalTarget || new THREE.Vector2();
  1970. return result.copy( point ).clamp( this.min, this.max );
  1971. },
  1972. distanceToPoint: function () {
  1973. var v1 = new THREE.Vector2();
  1974. return function ( point ) {
  1975. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1976. return clampedPoint.sub( point ).length();
  1977. };
  1978. }(),
  1979. intersect: function ( box ) {
  1980. this.min.max( box.min );
  1981. this.max.min( box.max );
  1982. return this;
  1983. },
  1984. union: function ( box ) {
  1985. this.min.min( box.min );
  1986. this.max.max( box.max );
  1987. return this;
  1988. },
  1989. translate: function ( offset ) {
  1990. this.min.add( offset );
  1991. this.max.add( offset );
  1992. return this;
  1993. },
  1994. equals: function ( box ) {
  1995. return box.min.equals( this.min ) && box.max.equals( this.max );
  1996. },
  1997. clone: function () {
  1998. return new THREE.Box2().copy( this );
  1999. }
  2000. };
  2001. /**
  2002. * @author bhouston / http://exocortex.com
  2003. * @author WestLangley / http://github.com/WestLangley
  2004. */
  2005. THREE.Box3 = function ( min, max ) {
  2006. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2007. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2008. };
  2009. THREE.Box3.prototype = {
  2010. constructor: THREE.Box3,
  2011. set: function ( min, max ) {
  2012. this.min.copy( min );
  2013. this.max.copy( max );
  2014. return this;
  2015. },
  2016. addPoint: function ( point ) {
  2017. if ( point.x < this.min.x ) {
  2018. this.min.x = point.x;
  2019. } else if ( point.x > this.max.x ) {
  2020. this.max.x = point.x;
  2021. }
  2022. if ( point.y < this.min.y ) {
  2023. this.min.y = point.y;
  2024. } else if ( point.y > this.max.y ) {
  2025. this.max.y = point.y;
  2026. }
  2027. if ( point.z < this.min.z ) {
  2028. this.min.z = point.z;
  2029. } else if ( point.z > this.max.z ) {
  2030. this.max.z = point.z;
  2031. }
  2032. },
  2033. setFromPoints: function ( points ) {
  2034. if ( points.length > 0 ) {
  2035. var point = points[ 0 ];
  2036. this.min.copy( point );
  2037. this.max.copy( point );
  2038. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2039. this.addPoint( points[ i ] )
  2040. }
  2041. } else {
  2042. this.makeEmpty();
  2043. }
  2044. return this;
  2045. },
  2046. setFromCenterAndSize: function() {
  2047. var v1 = new THREE.Vector3();
  2048. return function ( center, size ) {
  2049. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2050. this.min.copy( center ).sub( halfSize );
  2051. this.max.copy( center ).add( halfSize );
  2052. return this;
  2053. };
  2054. }(),
  2055. setFromObject: function() {
  2056. // Computes the world-axis-aligned bounding box of an object (including its children),
  2057. // accounting for both the object's, and childrens', world transforms
  2058. var v1 = new THREE.Vector3();
  2059. return function( object ) {
  2060. var scope = this;
  2061. object.updateMatrixWorld( true );
  2062. this.makeEmpty();
  2063. object.traverse( function ( node ) {
  2064. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2065. var vertices = node.geometry.vertices;
  2066. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2067. v1.copy( vertices[ i ] );
  2068. v1.applyMatrix4( node.matrixWorld );
  2069. scope.expandByPoint( v1 );
  2070. }
  2071. }
  2072. } );
  2073. return this;
  2074. };
  2075. }(),
  2076. copy: function ( box ) {
  2077. this.min.copy( box.min );
  2078. this.max.copy( box.max );
  2079. return this;
  2080. },
  2081. makeEmpty: function () {
  2082. this.min.x = this.min.y = this.min.z = Infinity;
  2083. this.max.x = this.max.y = this.max.z = -Infinity;
  2084. return this;
  2085. },
  2086. empty: function () {
  2087. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2088. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2089. },
  2090. center: function ( optionalTarget ) {
  2091. var result = optionalTarget || new THREE.Vector3();
  2092. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2093. },
  2094. size: function ( optionalTarget ) {
  2095. var result = optionalTarget || new THREE.Vector3();
  2096. return result.subVectors( this.max, this.min );
  2097. },
  2098. expandByPoint: function ( point ) {
  2099. this.min.min( point );
  2100. this.max.max( point );
  2101. return this;
  2102. },
  2103. expandByVector: function ( vector ) {
  2104. this.min.sub( vector );
  2105. this.max.add( vector );
  2106. return this;
  2107. },
  2108. expandByScalar: function ( scalar ) {
  2109. this.min.addScalar( -scalar );
  2110. this.max.addScalar( scalar );
  2111. return this;
  2112. },
  2113. containsPoint: function ( point ) {
  2114. if ( point.x < this.min.x || point.x > this.max.x ||
  2115. point.y < this.min.y || point.y > this.max.y ||
  2116. point.z < this.min.z || point.z > this.max.z ) {
  2117. return false;
  2118. }
  2119. return true;
  2120. },
  2121. containsBox: function ( box ) {
  2122. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2123. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2124. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2125. return true;
  2126. }
  2127. return false;
  2128. },
  2129. getParameter: function ( point ) {
  2130. // This can potentially have a divide by zero if the box
  2131. // has a size dimension of 0.
  2132. return new THREE.Vector3(
  2133. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2134. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2135. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2136. );
  2137. },
  2138. isIntersectionBox: function ( box ) {
  2139. // using 6 splitting planes to rule out intersections.
  2140. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2141. box.max.y < this.min.y || box.min.y > this.max.y ||
  2142. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2143. return false;
  2144. }
  2145. return true;
  2146. },
  2147. clampPoint: function ( point, optionalTarget ) {
  2148. var result = optionalTarget || new THREE.Vector3();
  2149. return result.copy( point ).clamp( this.min, this.max );
  2150. },
  2151. distanceToPoint: function() {
  2152. var v1 = new THREE.Vector3();
  2153. return function ( point ) {
  2154. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2155. return clampedPoint.sub( point ).length();
  2156. };
  2157. }(),
  2158. getBoundingSphere: function() {
  2159. var v1 = new THREE.Vector3();
  2160. return function ( optionalTarget ) {
  2161. var result = optionalTarget || new THREE.Sphere();
  2162. result.center = this.center();
  2163. result.radius = this.size( v1 ).length() * 0.5;
  2164. return result;
  2165. };
  2166. }(),
  2167. intersect: function ( box ) {
  2168. this.min.max( box.min );
  2169. this.max.min( box.max );
  2170. return this;
  2171. },
  2172. union: function ( box ) {
  2173. this.min.min( box.min );
  2174. this.max.max( box.max );
  2175. return this;
  2176. },
  2177. applyMatrix4: function() {
  2178. var points = [
  2179. new THREE.Vector3(),
  2180. new THREE.Vector3(),
  2181. new THREE.Vector3(),
  2182. new THREE.Vector3(),
  2183. new THREE.Vector3(),
  2184. new THREE.Vector3(),
  2185. new THREE.Vector3(),
  2186. new THREE.Vector3()
  2187. ];
  2188. return function ( matrix ) {
  2189. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2190. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2191. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2192. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2193. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2194. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2195. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2196. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2197. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2198. this.makeEmpty();
  2199. this.setFromPoints( points );
  2200. return this;
  2201. };
  2202. }(),
  2203. translate: function ( offset ) {
  2204. this.min.add( offset );
  2205. this.max.add( offset );
  2206. return this;
  2207. },
  2208. equals: function ( box ) {
  2209. return box.min.equals( this.min ) && box.max.equals( this.max );
  2210. },
  2211. clone: function () {
  2212. return new THREE.Box3().copy( this );
  2213. }
  2214. };
  2215. /**
  2216. * @author alteredq / http://alteredqualia.com/
  2217. * @author WestLangley / http://github.com/WestLangley
  2218. * @author bhouston / http://exocortex.com
  2219. */
  2220. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2221. this.elements = new Float32Array(9);
  2222. this.set(
  2223. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2224. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2225. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2226. );
  2227. };
  2228. THREE.Matrix3.prototype = {
  2229. constructor: THREE.Matrix3,
  2230. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2231. var te = this.elements;
  2232. te[0] = n11; te[3] = n12; te[6] = n13;
  2233. te[1] = n21; te[4] = n22; te[7] = n23;
  2234. te[2] = n31; te[5] = n32; te[8] = n33;
  2235. return this;
  2236. },
  2237. identity: function () {
  2238. this.set(
  2239. 1, 0, 0,
  2240. 0, 1, 0,
  2241. 0, 0, 1
  2242. );
  2243. return this;
  2244. },
  2245. copy: function ( m ) {
  2246. var me = m.elements;
  2247. this.set(
  2248. me[0], me[3], me[6],
  2249. me[1], me[4], me[7],
  2250. me[2], me[5], me[8]
  2251. );
  2252. return this;
  2253. },
  2254. multiplyVector3: function ( vector ) {
  2255. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2256. return vector.applyMatrix3( this );
  2257. },
  2258. multiplyVector3Array: function() {
  2259. var v1 = new THREE.Vector3();
  2260. return function ( a ) {
  2261. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2262. v1.x = a[ i ];
  2263. v1.y = a[ i + 1 ];
  2264. v1.z = a[ i + 2 ];
  2265. v1.applyMatrix3(this);
  2266. a[ i ] = v1.x;
  2267. a[ i + 1 ] = v1.y;
  2268. a[ i + 2 ] = v1.z;
  2269. }
  2270. return a;
  2271. };
  2272. }(),
  2273. multiplyScalar: function ( s ) {
  2274. var te = this.elements;
  2275. te[0] *= s; te[3] *= s; te[6] *= s;
  2276. te[1] *= s; te[4] *= s; te[7] *= s;
  2277. te[2] *= s; te[5] *= s; te[8] *= s;
  2278. return this;
  2279. },
  2280. determinant: function () {
  2281. var te = this.elements;
  2282. var a = te[0], b = te[1], c = te[2],
  2283. d = te[3], e = te[4], f = te[5],
  2284. g = te[6], h = te[7], i = te[8];
  2285. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2286. },
  2287. getInverse: function ( matrix, throwOnInvertible ) {
  2288. // input: THREE.Matrix4
  2289. // ( based on http://code.google.com/p/webgl-mjs/ )
  2290. var me = matrix.elements;
  2291. var te = this.elements;
  2292. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2293. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2294. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2295. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2296. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2297. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2298. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2299. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2300. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2301. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2302. // no inverse
  2303. if ( det === 0 ) {
  2304. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2305. if ( throwOnInvertible || false ) {
  2306. throw new Error( msg );
  2307. } else {
  2308. console.warn( msg );
  2309. }
  2310. this.identity();
  2311. return this;
  2312. }
  2313. this.multiplyScalar( 1.0 / det );
  2314. return this;
  2315. },
  2316. transpose: function () {
  2317. var tmp, m = this.elements;
  2318. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2319. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2320. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2321. return this;
  2322. },
  2323. getNormalMatrix: function ( m ) {
  2324. // input: THREE.Matrix4
  2325. this.getInverse( m ).transpose();
  2326. return this;
  2327. },
  2328. transposeIntoArray: function ( r ) {
  2329. var m = this.elements;
  2330. r[ 0 ] = m[ 0 ];
  2331. r[ 1 ] = m[ 3 ];
  2332. r[ 2 ] = m[ 6 ];
  2333. r[ 3 ] = m[ 1 ];
  2334. r[ 4 ] = m[ 4 ];
  2335. r[ 5 ] = m[ 7 ];
  2336. r[ 6 ] = m[ 2 ];
  2337. r[ 7 ] = m[ 5 ];
  2338. r[ 8 ] = m[ 8 ];
  2339. return this;
  2340. },
  2341. clone: function () {
  2342. var te = this.elements;
  2343. return new THREE.Matrix3(
  2344. te[0], te[3], te[6],
  2345. te[1], te[4], te[7],
  2346. te[2], te[5], te[8]
  2347. );
  2348. }
  2349. };
  2350. /**
  2351. * @author mrdoob / http://mrdoob.com/
  2352. * @author supereggbert / http://www.paulbrunt.co.uk/
  2353. * @author philogb / http://blog.thejit.org/
  2354. * @author jordi_ros / http://plattsoft.com
  2355. * @author D1plo1d / http://github.com/D1plo1d
  2356. * @author alteredq / http://alteredqualia.com/
  2357. * @author mikael emtinger / http://gomo.se/
  2358. * @author timknip / http://www.floorplanner.com/
  2359. * @author bhouston / http://exocortex.com
  2360. * @author WestLangley / http://github.com/WestLangley
  2361. */
  2362. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2363. this.elements = new Float32Array( 16 );
  2364. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2365. // we should not support semi specification of Matrix4, it is just weird.
  2366. var te = this.elements;
  2367. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2368. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2369. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2370. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2371. };
  2372. THREE.Matrix4.prototype = {
  2373. constructor: THREE.Matrix4,
  2374. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2375. var te = this.elements;
  2376. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2377. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2378. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2379. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2380. return this;
  2381. },
  2382. identity: function () {
  2383. this.set(
  2384. 1, 0, 0, 0,
  2385. 0, 1, 0, 0,
  2386. 0, 0, 1, 0,
  2387. 0, 0, 0, 1
  2388. );
  2389. return this;
  2390. },
  2391. copy: function ( m ) {
  2392. this.elements.set( m.elements );
  2393. return this;
  2394. },
  2395. extractPosition: function ( m ) {
  2396. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2397. return this.copyPosition( m );
  2398. },
  2399. copyPosition: function ( m ) {
  2400. var te = this.elements;
  2401. var me = m.elements;
  2402. te[12] = me[12];
  2403. te[13] = me[13];
  2404. te[14] = me[14];
  2405. return this;
  2406. },
  2407. extractRotation: function () {
  2408. var v1 = new THREE.Vector3();
  2409. return function ( m ) {
  2410. var te = this.elements;
  2411. var me = m.elements;
  2412. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2413. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2414. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2415. te[0] = me[0] * scaleX;
  2416. te[1] = me[1] * scaleX;
  2417. te[2] = me[2] * scaleX;
  2418. te[4] = me[4] * scaleY;
  2419. te[5] = me[5] * scaleY;
  2420. te[6] = me[6] * scaleY;
  2421. te[8] = me[8] * scaleZ;
  2422. te[9] = me[9] * scaleZ;
  2423. te[10] = me[10] * scaleZ;
  2424. return this;
  2425. };
  2426. }(),
  2427. makeRotationFromEuler: function ( euler ) {
  2428. if ( euler instanceof THREE.Euler === false ) {
  2429. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2430. }
  2431. var te = this.elements;
  2432. var x = euler.x, y = euler.y, z = euler.z;
  2433. var a = Math.cos( x ), b = Math.sin( x );
  2434. var c = Math.cos( y ), d = Math.sin( y );
  2435. var e = Math.cos( z ), f = Math.sin( z );
  2436. if ( euler.order === 'XYZ' ) {
  2437. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2438. te[0] = c * e;
  2439. te[4] = - c * f;
  2440. te[8] = d;
  2441. te[1] = af + be * d;
  2442. te[5] = ae - bf * d;
  2443. te[9] = - b * c;
  2444. te[2] = bf - ae * d;
  2445. te[6] = be + af * d;
  2446. te[10] = a * c;
  2447. } else if ( euler.order === 'YXZ' ) {
  2448. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2449. te[0] = ce + df * b;
  2450. te[4] = de * b - cf;
  2451. te[8] = a * d;
  2452. te[1] = a * f;
  2453. te[5] = a * e;
  2454. te[9] = - b;
  2455. te[2] = cf * b - de;
  2456. te[6] = df + ce * b;
  2457. te[10] = a * c;
  2458. } else if ( euler.order === 'ZXY' ) {
  2459. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2460. te[0] = ce - df * b;
  2461. te[4] = - a * f;
  2462. te[8] = de + cf * b;
  2463. te[1] = cf + de * b;
  2464. te[5] = a * e;
  2465. te[9] = df - ce * b;
  2466. te[2] = - a * d;
  2467. te[6] = b;
  2468. te[10] = a * c;
  2469. } else if ( euler.order === 'ZYX' ) {
  2470. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2471. te[0] = c * e;
  2472. te[4] = be * d - af;
  2473. te[8] = ae * d + bf;
  2474. te[1] = c * f;
  2475. te[5] = bf * d + ae;
  2476. te[9] = af * d - be;
  2477. te[2] = - d;
  2478. te[6] = b * c;
  2479. te[10] = a * c;
  2480. } else if ( euler.order === 'YZX' ) {
  2481. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2482. te[0] = c * e;
  2483. te[4] = bd - ac * f;
  2484. te[8] = bc * f + ad;
  2485. te[1] = f;
  2486. te[5] = a * e;
  2487. te[9] = - b * e;
  2488. te[2] = - d * e;
  2489. te[6] = ad * f + bc;
  2490. te[10] = ac - bd * f;
  2491. } else if ( euler.order === 'XZY' ) {
  2492. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2493. te[0] = c * e;
  2494. te[4] = - f;
  2495. te[8] = d * e;
  2496. te[1] = ac * f + bd;
  2497. te[5] = a * e;
  2498. te[9] = ad * f - bc;
  2499. te[2] = bc * f - ad;
  2500. te[6] = b * e;
  2501. te[10] = bd * f + ac;
  2502. }
  2503. // last column
  2504. te[3] = 0;
  2505. te[7] = 0;
  2506. te[11] = 0;
  2507. // bottom row
  2508. te[12] = 0;
  2509. te[13] = 0;
  2510. te[14] = 0;
  2511. te[15] = 1;
  2512. return this;
  2513. },
  2514. setRotationFromQuaternion: function ( q ) {
  2515. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2516. return this.makeRotationFromQuaternion( q );
  2517. },
  2518. makeRotationFromQuaternion: function ( q ) {
  2519. var te = this.elements;
  2520. var x = q.x, y = q.y, z = q.z, w = q.w;
  2521. var x2 = x + x, y2 = y + y, z2 = z + z;
  2522. var xx = x * x2, xy = x * y2, xz = x * z2;
  2523. var yy = y * y2, yz = y * z2, zz = z * z2;
  2524. var wx = w * x2, wy = w * y2, wz = w * z2;
  2525. te[0] = 1 - ( yy + zz );
  2526. te[4] = xy - wz;
  2527. te[8] = xz + wy;
  2528. te[1] = xy + wz;
  2529. te[5] = 1 - ( xx + zz );
  2530. te[9] = yz - wx;
  2531. te[2] = xz - wy;
  2532. te[6] = yz + wx;
  2533. te[10] = 1 - ( xx + yy );
  2534. // last column
  2535. te[3] = 0;
  2536. te[7] = 0;
  2537. te[11] = 0;
  2538. // bottom row
  2539. te[12] = 0;
  2540. te[13] = 0;
  2541. te[14] = 0;
  2542. te[15] = 1;
  2543. return this;
  2544. },
  2545. lookAt: function() {
  2546. var x = new THREE.Vector3();
  2547. var y = new THREE.Vector3();
  2548. var z = new THREE.Vector3();
  2549. return function ( eye, target, up ) {
  2550. var te = this.elements;
  2551. z.subVectors( eye, target ).normalize();
  2552. if ( z.length() === 0 ) {
  2553. z.z = 1;
  2554. }
  2555. x.crossVectors( up, z ).normalize();
  2556. if ( x.length() === 0 ) {
  2557. z.x += 0.0001;
  2558. x.crossVectors( up, z ).normalize();
  2559. }
  2560. y.crossVectors( z, x );
  2561. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2562. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2563. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2564. return this;
  2565. };
  2566. }(),
  2567. multiply: function ( m, n ) {
  2568. if ( n !== undefined ) {
  2569. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2570. return this.multiplyMatrices( m, n );
  2571. }
  2572. return this.multiplyMatrices( this, m );
  2573. },
  2574. multiplyMatrices: function ( a, b ) {
  2575. var ae = a.elements;
  2576. var be = b.elements;
  2577. var te = this.elements;
  2578. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2579. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2580. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2581. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2582. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2583. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2584. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2585. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2586. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2587. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2588. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2589. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2590. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2591. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2592. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2593. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2594. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2595. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2596. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2597. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2598. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2599. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2600. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2601. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2602. return this;
  2603. },
  2604. multiplyToArray: function ( a, b, r ) {
  2605. var te = this.elements;
  2606. this.multiplyMatrices( a, b );
  2607. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2608. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2609. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2610. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2611. return this;
  2612. },
  2613. multiplyScalar: function ( s ) {
  2614. var te = this.elements;
  2615. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2616. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2617. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2618. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2619. return this;
  2620. },
  2621. multiplyVector3: function ( vector ) {
  2622. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2623. return vector.applyProjection( this );
  2624. },
  2625. multiplyVector4: function ( vector ) {
  2626. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2627. return vector.applyMatrix4( this );
  2628. },
  2629. multiplyVector3Array: function() {
  2630. var v1 = new THREE.Vector3();
  2631. return function ( a ) {
  2632. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2633. v1.x = a[ i ];
  2634. v1.y = a[ i + 1 ];
  2635. v1.z = a[ i + 2 ];
  2636. v1.applyProjection( this );
  2637. a[ i ] = v1.x;
  2638. a[ i + 1 ] = v1.y;
  2639. a[ i + 2 ] = v1.z;
  2640. }
  2641. return a;
  2642. };
  2643. }(),
  2644. rotateAxis: function ( v ) {
  2645. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2646. v.transformDirection( this );
  2647. },
  2648. crossVector: function ( vector ) {
  2649. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2650. return vector.applyMatrix4( this );
  2651. },
  2652. determinant: function () {
  2653. var te = this.elements;
  2654. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2655. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2656. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2657. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2658. //TODO: make this more efficient
  2659. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2660. return (
  2661. n41 * (
  2662. +n14 * n23 * n32
  2663. -n13 * n24 * n32
  2664. -n14 * n22 * n33
  2665. +n12 * n24 * n33
  2666. +n13 * n22 * n34
  2667. -n12 * n23 * n34
  2668. ) +
  2669. n42 * (
  2670. +n11 * n23 * n34
  2671. -n11 * n24 * n33
  2672. +n14 * n21 * n33
  2673. -n13 * n21 * n34
  2674. +n13 * n24 * n31
  2675. -n14 * n23 * n31
  2676. ) +
  2677. n43 * (
  2678. +n11 * n24 * n32
  2679. -n11 * n22 * n34
  2680. -n14 * n21 * n32
  2681. +n12 * n21 * n34
  2682. +n14 * n22 * n31
  2683. -n12 * n24 * n31
  2684. ) +
  2685. n44 * (
  2686. -n13 * n22 * n31
  2687. -n11 * n23 * n32
  2688. +n11 * n22 * n33
  2689. +n13 * n21 * n32
  2690. -n12 * n21 * n33
  2691. +n12 * n23 * n31
  2692. )
  2693. );
  2694. },
  2695. transpose: function () {
  2696. var te = this.elements;
  2697. var tmp;
  2698. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2699. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2700. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2701. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2702. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2703. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2704. return this;
  2705. },
  2706. flattenToArray: function ( flat ) {
  2707. var te = this.elements;
  2708. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2709. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2710. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2711. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2712. return flat;
  2713. },
  2714. flattenToArrayOffset: function( flat, offset ) {
  2715. var te = this.elements;
  2716. flat[ offset ] = te[0];
  2717. flat[ offset + 1 ] = te[1];
  2718. flat[ offset + 2 ] = te[2];
  2719. flat[ offset + 3 ] = te[3];
  2720. flat[ offset + 4 ] = te[4];
  2721. flat[ offset + 5 ] = te[5];
  2722. flat[ offset + 6 ] = te[6];
  2723. flat[ offset + 7 ] = te[7];
  2724. flat[ offset + 8 ] = te[8];
  2725. flat[ offset + 9 ] = te[9];
  2726. flat[ offset + 10 ] = te[10];
  2727. flat[ offset + 11 ] = te[11];
  2728. flat[ offset + 12 ] = te[12];
  2729. flat[ offset + 13 ] = te[13];
  2730. flat[ offset + 14 ] = te[14];
  2731. flat[ offset + 15 ] = te[15];
  2732. return flat;
  2733. },
  2734. getPosition: function() {
  2735. var v1 = new THREE.Vector3();
  2736. return function () {
  2737. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2738. var te = this.elements;
  2739. return v1.set( te[12], te[13], te[14] );
  2740. };
  2741. }(),
  2742. setPosition: function ( v ) {
  2743. var te = this.elements;
  2744. te[12] = v.x;
  2745. te[13] = v.y;
  2746. te[14] = v.z;
  2747. return this;
  2748. },
  2749. getInverse: function ( m, throwOnInvertible ) {
  2750. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2751. var te = this.elements;
  2752. var me = m.elements;
  2753. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2754. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2755. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2756. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2757. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2758. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2759. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2760. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2761. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2762. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2763. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2764. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2765. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2766. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2767. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2768. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2769. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2770. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2771. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2772. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2773. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2774. if ( det == 0 ) {
  2775. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2776. if ( throwOnInvertible || false ) {
  2777. throw new Error( msg );
  2778. } else {
  2779. console.warn( msg );
  2780. }
  2781. this.identity();
  2782. return this;
  2783. }
  2784. this.multiplyScalar( 1 / det );
  2785. return this;
  2786. },
  2787. translate: function ( v ) {
  2788. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2789. },
  2790. rotateX: function ( angle ) {
  2791. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2792. },
  2793. rotateY: function ( angle ) {
  2794. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2795. },
  2796. rotateZ: function ( angle ) {
  2797. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2798. },
  2799. rotateByAxis: function ( axis, angle ) {
  2800. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2801. },
  2802. scale: function ( v ) {
  2803. var te = this.elements;
  2804. var x = v.x, y = v.y, z = v.z;
  2805. te[0] *= x; te[4] *= y; te[8] *= z;
  2806. te[1] *= x; te[5] *= y; te[9] *= z;
  2807. te[2] *= x; te[6] *= y; te[10] *= z;
  2808. te[3] *= x; te[7] *= y; te[11] *= z;
  2809. return this;
  2810. },
  2811. getMaxScaleOnAxis: function () {
  2812. var te = this.elements;
  2813. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2814. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2815. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2816. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2817. },
  2818. makeTranslation: function ( x, y, z ) {
  2819. this.set(
  2820. 1, 0, 0, x,
  2821. 0, 1, 0, y,
  2822. 0, 0, 1, z,
  2823. 0, 0, 0, 1
  2824. );
  2825. return this;
  2826. },
  2827. makeRotationX: function ( theta ) {
  2828. var c = Math.cos( theta ), s = Math.sin( theta );
  2829. this.set(
  2830. 1, 0, 0, 0,
  2831. 0, c, -s, 0,
  2832. 0, s, c, 0,
  2833. 0, 0, 0, 1
  2834. );
  2835. return this;
  2836. },
  2837. makeRotationY: function ( theta ) {
  2838. var c = Math.cos( theta ), s = Math.sin( theta );
  2839. this.set(
  2840. c, 0, s, 0,
  2841. 0, 1, 0, 0,
  2842. -s, 0, c, 0,
  2843. 0, 0, 0, 1
  2844. );
  2845. return this;
  2846. },
  2847. makeRotationZ: function ( theta ) {
  2848. var c = Math.cos( theta ), s = Math.sin( theta );
  2849. this.set(
  2850. c, -s, 0, 0,
  2851. s, c, 0, 0,
  2852. 0, 0, 1, 0,
  2853. 0, 0, 0, 1
  2854. );
  2855. return this;
  2856. },
  2857. makeRotationAxis: function ( axis, angle ) {
  2858. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2859. var c = Math.cos( angle );
  2860. var s = Math.sin( angle );
  2861. var t = 1 - c;
  2862. var x = axis.x, y = axis.y, z = axis.z;
  2863. var tx = t * x, ty = t * y;
  2864. this.set(
  2865. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2866. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2867. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2868. 0, 0, 0, 1
  2869. );
  2870. return this;
  2871. },
  2872. makeScale: function ( x, y, z ) {
  2873. this.set(
  2874. x, 0, 0, 0,
  2875. 0, y, 0, 0,
  2876. 0, 0, z, 0,
  2877. 0, 0, 0, 1
  2878. );
  2879. return this;
  2880. },
  2881. compose: function ( position, quaternion, scale ) {
  2882. this.makeRotationFromQuaternion( quaternion );
  2883. this.scale( scale );
  2884. this.setPosition( position );
  2885. return this;
  2886. },
  2887. decompose: function () {
  2888. var vector = new THREE.Vector3();
  2889. var matrix = new THREE.Matrix4();
  2890. return function ( position, quaternion, scale ) {
  2891. var te = this.elements;
  2892. var sx = vector.set( te[0], te[1], te[2] ).length();
  2893. var sy = vector.set( te[4], te[5], te[6] ).length();
  2894. var sz = vector.set( te[8], te[9], te[10] ).length();
  2895. position.x = te[12];
  2896. position.y = te[13];
  2897. position.z = te[14];
  2898. // scale the rotation part
  2899. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2900. var invSX = 1 / sx;
  2901. var invSY = 1 / sy;
  2902. var invSZ = 1 / sz;
  2903. matrix.elements[0] *= invSX;
  2904. matrix.elements[1] *= invSX;
  2905. matrix.elements[2] *= invSX;
  2906. matrix.elements[4] *= invSY;
  2907. matrix.elements[5] *= invSY;
  2908. matrix.elements[6] *= invSY;
  2909. matrix.elements[8] *= invSZ;
  2910. matrix.elements[9] *= invSZ;
  2911. matrix.elements[10] *= invSZ;
  2912. quaternion.setFromRotationMatrix( matrix );
  2913. scale.x = sx;
  2914. scale.y = sy;
  2915. scale.z = sz;
  2916. return this;
  2917. };
  2918. }(),
  2919. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2920. var te = this.elements;
  2921. var x = 2 * near / ( right - left );
  2922. var y = 2 * near / ( top - bottom );
  2923. var a = ( right + left ) / ( right - left );
  2924. var b = ( top + bottom ) / ( top - bottom );
  2925. var c = - ( far + near ) / ( far - near );
  2926. var d = - 2 * far * near / ( far - near );
  2927. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2928. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2929. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2930. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2931. return this;
  2932. },
  2933. makePerspective: function ( fov, aspect, near, far ) {
  2934. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2935. var ymin = - ymax;
  2936. var xmin = ymin * aspect;
  2937. var xmax = ymax * aspect;
  2938. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2939. },
  2940. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2941. var te = this.elements;
  2942. var w = right - left;
  2943. var h = top - bottom;
  2944. var p = far - near;
  2945. var x = ( right + left ) / w;
  2946. var y = ( top + bottom ) / h;
  2947. var z = ( far + near ) / p;
  2948. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2949. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2950. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2951. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2952. return this;
  2953. },
  2954. fromArray: function ( array ) {
  2955. this.elements.set( array );
  2956. return this;
  2957. },
  2958. toArray: function () {
  2959. var te = this.elements;
  2960. return [
  2961. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2962. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2963. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2964. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2965. ];
  2966. },
  2967. clone: function () {
  2968. var te = this.elements;
  2969. return new THREE.Matrix4(
  2970. te[0], te[4], te[8], te[12],
  2971. te[1], te[5], te[9], te[13],
  2972. te[2], te[6], te[10], te[14],
  2973. te[3], te[7], te[11], te[15]
  2974. );
  2975. }
  2976. };
  2977. /**
  2978. * @author bhouston / http://exocortex.com
  2979. */
  2980. THREE.Ray = function ( origin, direction ) {
  2981. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2982. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2983. };
  2984. THREE.Ray.prototype = {
  2985. constructor: THREE.Ray,
  2986. set: function ( origin, direction ) {
  2987. this.origin.copy( origin );
  2988. this.direction.copy( direction );
  2989. return this;
  2990. },
  2991. copy: function ( ray ) {
  2992. this.origin.copy( ray.origin );
  2993. this.direction.copy( ray.direction );
  2994. return this;
  2995. },
  2996. at: function ( t, optionalTarget ) {
  2997. var result = optionalTarget || new THREE.Vector3();
  2998. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2999. },
  3000. recast: function () {
  3001. var v1 = new THREE.Vector3();
  3002. return function ( t ) {
  3003. this.origin.copy( this.at( t, v1 ) );
  3004. return this;
  3005. };
  3006. }(),
  3007. closestPointToPoint: function ( point, optionalTarget ) {
  3008. var result = optionalTarget || new THREE.Vector3();
  3009. result.subVectors( point, this.origin );
  3010. var directionDistance = result.dot( this.direction );
  3011. if ( directionDistance < 0 ) {
  3012. return result.copy( this.origin );
  3013. }
  3014. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3015. },
  3016. distanceToPoint: function () {
  3017. var v1 = new THREE.Vector3();
  3018. return function ( point ) {
  3019. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3020. // point behind the ray
  3021. if ( directionDistance < 0 ) {
  3022. return this.origin.distanceTo( point );
  3023. }
  3024. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3025. return v1.distanceTo( point );
  3026. };
  3027. }(),
  3028. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3029. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3030. // It returns the min distance between the ray and the segment
  3031. // defined by v0 and v1
  3032. // It can also set two optional targets :
  3033. // - The closest point on the ray
  3034. // - The closest point on the segment
  3035. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3036. var segDir = v1.clone().sub( v0 ).normalize();
  3037. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3038. var diff = this.origin.clone().sub( segCenter );
  3039. var a01 = - this.direction.dot( segDir );
  3040. var b0 = diff.dot( this.direction );
  3041. var b1 = - diff.dot( segDir );
  3042. var c = diff.lengthSq();
  3043. var det = Math.abs( 1 - a01 * a01 );
  3044. var s0, s1, sqrDist, extDet;
  3045. if ( det >= 0 ) {
  3046. // The ray and segment are not parallel.
  3047. s0 = a01 * b1 - b0;
  3048. s1 = a01 * b0 - b1;
  3049. extDet = segExtent * det;
  3050. if ( s0 >= 0 ) {
  3051. if ( s1 >= - extDet ) {
  3052. if ( s1 <= extDet ) {
  3053. // region 0
  3054. // Minimum at interior points of ray and segment.
  3055. var invDet = 1 / det;
  3056. s0 *= invDet;
  3057. s1 *= invDet;
  3058. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3059. } else {
  3060. // region 1
  3061. s1 = segExtent;
  3062. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3063. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3064. }
  3065. } else {
  3066. // region 5
  3067. s1 = - segExtent;
  3068. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3069. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3070. }
  3071. } else {
  3072. if ( s1 <= - extDet) {
  3073. // region 4
  3074. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3075. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3076. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3077. } else if ( s1 <= extDet ) {
  3078. // region 3
  3079. s0 = 0;
  3080. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3081. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3082. } else {
  3083. // region 2
  3084. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3085. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3086. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3087. }
  3088. }
  3089. } else {
  3090. // Ray and segment are parallel.
  3091. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3092. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3093. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3094. }
  3095. if ( optionalPointOnRay ) {
  3096. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3097. }
  3098. if ( optionalPointOnSegment ) {
  3099. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3100. }
  3101. return sqrDist;
  3102. },
  3103. isIntersectionSphere: function ( sphere ) {
  3104. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3105. },
  3106. isIntersectionPlane: function ( plane ) {
  3107. // check if the ray lies on the plane first
  3108. var distToPoint = plane.distanceToPoint( this.origin );
  3109. if ( distToPoint === 0 ) {
  3110. return true;
  3111. }
  3112. var denominator = plane.normal.dot( this.direction );
  3113. if ( denominator * distToPoint < 0 ) {
  3114. return true
  3115. }
  3116. // ray origin is behind the plane (and is pointing behind it)
  3117. return false;
  3118. },
  3119. distanceToPlane: function ( plane ) {
  3120. var denominator = plane.normal.dot( this.direction );
  3121. if ( denominator == 0 ) {
  3122. // line is coplanar, return origin
  3123. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3124. return 0;
  3125. }
  3126. // Null is preferable to undefined since undefined means.... it is undefined
  3127. return null;
  3128. }
  3129. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3130. // Return if the ray never intersects the plane
  3131. return t >= 0 ? t : null;
  3132. },
  3133. intersectPlane: function ( plane, optionalTarget ) {
  3134. var t = this.distanceToPlane( plane );
  3135. if ( t === null ) {
  3136. return null;
  3137. }
  3138. return this.at( t, optionalTarget );
  3139. },
  3140. isIntersectionBox: function () {
  3141. var v = new THREE.Vector3();
  3142. return function ( box ) {
  3143. return this.intersectBox( box, v ) !== null;
  3144. }
  3145. }(),
  3146. intersectBox: function ( box , optionalTarget ) {
  3147. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3148. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3149. var invdirx = 1/this.direction.x,
  3150. invdiry = 1/this.direction.y,
  3151. invdirz = 1/this.direction.z;
  3152. var origin = this.origin;
  3153. if (invdirx >= 0) {
  3154. tmin = (box.min.x - origin.x) * invdirx;
  3155. tmax = (box.max.x - origin.x) * invdirx;
  3156. } else {
  3157. tmin = (box.max.x - origin.x) * invdirx;
  3158. tmax = (box.min.x - origin.x) * invdirx;
  3159. }
  3160. if (invdiry >= 0) {
  3161. tymin = (box.min.y - origin.y) * invdiry;
  3162. tymax = (box.max.y - origin.y) * invdiry;
  3163. } else {
  3164. tymin = (box.max.y - origin.y) * invdiry;
  3165. tymax = (box.min.y - origin.y) * invdiry;
  3166. }
  3167. if ((tmin > tymax) || (tymin > tmax)) return null;
  3168. // These lines also handle the case where tmin or tmax is NaN
  3169. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3170. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3171. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3172. if (invdirz >= 0) {
  3173. tzmin = (box.min.z - origin.z) * invdirz;
  3174. tzmax = (box.max.z - origin.z) * invdirz;
  3175. } else {
  3176. tzmin = (box.max.z - origin.z) * invdirz;
  3177. tzmax = (box.min.z - origin.z) * invdirz;
  3178. }
  3179. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3180. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3181. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3182. //return point closest to the ray (positive side)
  3183. if ( tmax < 0 ) return null;
  3184. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3185. },
  3186. intersectTriangle: function() {
  3187. // Compute the offset origin, edges, and normal.
  3188. var diff = new THREE.Vector3();
  3189. var edge1 = new THREE.Vector3();
  3190. var edge2 = new THREE.Vector3();
  3191. var normal = new THREE.Vector3();
  3192. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3193. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3194. edge1.subVectors( b, a );
  3195. edge2.subVectors( c, a );
  3196. normal.crossVectors( edge1, edge2 );
  3197. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3198. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3199. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3200. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3201. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3202. var DdN = this.direction.dot( normal );
  3203. var sign;
  3204. if ( DdN > 0 ) {
  3205. if ( backfaceCulling ) return null;
  3206. sign = 1;
  3207. } else if ( DdN < 0 ) {
  3208. sign = - 1;
  3209. DdN = - DdN;
  3210. } else {
  3211. return null;
  3212. }
  3213. diff.subVectors( this.origin, a );
  3214. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3215. // b1 < 0, no intersection
  3216. if ( DdQxE2 < 0 ) {
  3217. return null;
  3218. }
  3219. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3220. // b2 < 0, no intersection
  3221. if ( DdE1xQ < 0 ) {
  3222. return null;
  3223. }
  3224. // b1+b2 > 1, no intersection
  3225. if ( DdQxE2 + DdE1xQ > DdN ) {
  3226. return null;
  3227. }
  3228. // Line intersects triangle, check if ray does.
  3229. var QdN = - sign * diff.dot( normal );
  3230. // t < 0, no intersection
  3231. if ( QdN < 0 ) {
  3232. return null;
  3233. }
  3234. // Ray intersects triangle.
  3235. return this.at( QdN / DdN, optionalTarget );
  3236. }
  3237. }(),
  3238. applyMatrix4: function ( matrix4 ) {
  3239. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3240. this.origin.applyMatrix4( matrix4 );
  3241. this.direction.sub( this.origin );
  3242. this.direction.normalize();
  3243. return this;
  3244. },
  3245. equals: function ( ray ) {
  3246. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3247. },
  3248. clone: function () {
  3249. return new THREE.Ray().copy( this );
  3250. }
  3251. };
  3252. /**
  3253. * @author bhouston / http://exocortex.com
  3254. * @author mrdoob / http://mrdoob.com/
  3255. */
  3256. THREE.Sphere = function ( center, radius ) {
  3257. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3258. this.radius = ( radius !== undefined ) ? radius : 0;
  3259. };
  3260. THREE.Sphere.prototype = {
  3261. constructor: THREE.Sphere,
  3262. set: function ( center, radius ) {
  3263. this.center.copy( center );
  3264. this.radius = radius;
  3265. return this;
  3266. },
  3267. setFromPoints: function () {
  3268. var box = new THREE.Box3();
  3269. return function ( points, optionalCenter ) {
  3270. var center = this.center;
  3271. if ( optionalCenter !== undefined ) {
  3272. center.copy( optionalCenter );
  3273. } else {
  3274. box.setFromPoints( points ).center( center );
  3275. }
  3276. var maxRadiusSq = 0;
  3277. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3278. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3279. }
  3280. this.radius = Math.sqrt( maxRadiusSq );
  3281. return this;
  3282. };
  3283. }(),
  3284. copy: function ( sphere ) {
  3285. this.center.copy( sphere.center );
  3286. this.radius = sphere.radius;
  3287. return this;
  3288. },
  3289. empty: function () {
  3290. return ( this.radius <= 0 );
  3291. },
  3292. containsPoint: function ( point ) {
  3293. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3294. },
  3295. distanceToPoint: function ( point ) {
  3296. return ( point.distanceTo( this.center ) - this.radius );
  3297. },
  3298. intersectsSphere: function ( sphere ) {
  3299. var radiusSum = this.radius + sphere.radius;
  3300. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3301. },
  3302. clampPoint: function ( point, optionalTarget ) {
  3303. var deltaLengthSq = this.center.distanceToSquared( point );
  3304. var result = optionalTarget || new THREE.Vector3();
  3305. result.copy( point );
  3306. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3307. result.sub( this.center ).normalize();
  3308. result.multiplyScalar( this.radius ).add( this.center );
  3309. }
  3310. return result;
  3311. },
  3312. getBoundingBox: function ( optionalTarget ) {
  3313. var box = optionalTarget || new THREE.Box3();
  3314. box.set( this.center, this.center );
  3315. box.expandByScalar( this.radius );
  3316. return box;
  3317. },
  3318. applyMatrix4: function ( matrix ) {
  3319. this.center.applyMatrix4( matrix );
  3320. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3321. return this;
  3322. },
  3323. translate: function ( offset ) {
  3324. this.center.add( offset );
  3325. return this;
  3326. },
  3327. equals: function ( sphere ) {
  3328. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3329. },
  3330. clone: function () {
  3331. return new THREE.Sphere().copy( this );
  3332. }
  3333. };
  3334. /**
  3335. * @author mrdoob / http://mrdoob.com/
  3336. * @author alteredq / http://alteredqualia.com/
  3337. * @author bhouston / http://exocortex.com
  3338. */
  3339. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3340. this.planes = [
  3341. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3342. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3343. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3344. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3345. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3346. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3347. ];
  3348. };
  3349. THREE.Frustum.prototype = {
  3350. constructor: THREE.Frustum,
  3351. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3352. var planes = this.planes;
  3353. planes[0].copy( p0 );
  3354. planes[1].copy( p1 );
  3355. planes[2].copy( p2 );
  3356. planes[3].copy( p3 );
  3357. planes[4].copy( p4 );
  3358. planes[5].copy( p5 );
  3359. return this;
  3360. },
  3361. copy: function ( frustum ) {
  3362. var planes = this.planes;
  3363. for( var i = 0; i < 6; i ++ ) {
  3364. planes[i].copy( frustum.planes[i] );
  3365. }
  3366. return this;
  3367. },
  3368. setFromMatrix: function ( m ) {
  3369. var planes = this.planes;
  3370. var me = m.elements;
  3371. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3372. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3373. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3374. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3375. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3376. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3377. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3378. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3379. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3380. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3381. return this;
  3382. },
  3383. intersectsObject: function () {
  3384. var sphere = new THREE.Sphere();
  3385. return function ( object ) {
  3386. var geometry = object.geometry;
  3387. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3388. sphere.copy( geometry.boundingSphere );
  3389. sphere.applyMatrix4( object.matrixWorld );
  3390. return this.intersectsSphere( sphere );
  3391. };
  3392. }(),
  3393. intersectsSphere: function ( sphere ) {
  3394. var planes = this.planes;
  3395. var center = sphere.center;
  3396. var negRadius = -sphere.radius;
  3397. for ( var i = 0; i < 6; i ++ ) {
  3398. var distance = planes[ i ].distanceToPoint( center );
  3399. if ( distance < negRadius ) {
  3400. return false;
  3401. }
  3402. }
  3403. return true;
  3404. },
  3405. intersectsBox : function() {
  3406. var p1 = new THREE.Vector3(),
  3407. p2 = new THREE.Vector3();
  3408. return function( box ) {
  3409. var planes = this.planes;
  3410. for ( var i = 0; i < 6 ; i ++ ) {
  3411. var plane = planes[i];
  3412. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3413. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3414. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3415. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3416. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3417. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3418. var d1 = plane.distanceToPoint( p1 );
  3419. var d2 = plane.distanceToPoint( p2 );
  3420. // if both outside plane, no intersection
  3421. if ( d1 < 0 && d2 < 0 ) {
  3422. return false;
  3423. }
  3424. }
  3425. return true;
  3426. };
  3427. }(),
  3428. containsPoint: function ( point ) {
  3429. var planes = this.planes;
  3430. for ( var i = 0; i < 6; i ++ ) {
  3431. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3432. return false;
  3433. }
  3434. }
  3435. return true;
  3436. },
  3437. clone: function () {
  3438. return new THREE.Frustum().copy( this );
  3439. }
  3440. };
  3441. /**
  3442. * @author bhouston / http://exocortex.com
  3443. */
  3444. THREE.Plane = function ( normal, constant ) {
  3445. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3446. this.constant = ( constant !== undefined ) ? constant : 0;
  3447. };
  3448. THREE.Plane.prototype = {
  3449. constructor: THREE.Plane,
  3450. set: function ( normal, constant ) {
  3451. this.normal.copy( normal );
  3452. this.constant = constant;
  3453. return this;
  3454. },
  3455. setComponents: function ( x, y, z, w ) {
  3456. this.normal.set( x, y, z );
  3457. this.constant = w;
  3458. return this;
  3459. },
  3460. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3461. this.normal.copy( normal );
  3462. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3463. return this;
  3464. },
  3465. setFromCoplanarPoints: function() {
  3466. var v1 = new THREE.Vector3();
  3467. var v2 = new THREE.Vector3();
  3468. return function ( a, b, c ) {
  3469. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3470. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3471. this.setFromNormalAndCoplanarPoint( normal, a );
  3472. return this;
  3473. };
  3474. }(),
  3475. copy: function ( plane ) {
  3476. this.normal.copy( plane.normal );
  3477. this.constant = plane.constant;
  3478. return this;
  3479. },
  3480. normalize: function () {
  3481. // Note: will lead to a divide by zero if the plane is invalid.
  3482. var inverseNormalLength = 1.0 / this.normal.length();
  3483. this.normal.multiplyScalar( inverseNormalLength );
  3484. this.constant *= inverseNormalLength;
  3485. return this;
  3486. },
  3487. negate: function () {
  3488. this.constant *= -1;
  3489. this.normal.negate();
  3490. return this;
  3491. },
  3492. distanceToPoint: function ( point ) {
  3493. return this.normal.dot( point ) + this.constant;
  3494. },
  3495. distanceToSphere: function ( sphere ) {
  3496. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3497. },
  3498. projectPoint: function ( point, optionalTarget ) {
  3499. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3500. },
  3501. orthoPoint: function ( point, optionalTarget ) {
  3502. var perpendicularMagnitude = this.distanceToPoint( point );
  3503. var result = optionalTarget || new THREE.Vector3();
  3504. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3505. },
  3506. isIntersectionLine: function ( line ) {
  3507. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3508. var startSign = this.distanceToPoint( line.start );
  3509. var endSign = this.distanceToPoint( line.end );
  3510. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3511. },
  3512. intersectLine: function() {
  3513. var v1 = new THREE.Vector3();
  3514. return function ( line, optionalTarget ) {
  3515. var result = optionalTarget || new THREE.Vector3();
  3516. var direction = line.delta( v1 );
  3517. var denominator = this.normal.dot( direction );
  3518. if ( denominator == 0 ) {
  3519. // line is coplanar, return origin
  3520. if( this.distanceToPoint( line.start ) == 0 ) {
  3521. return result.copy( line.start );
  3522. }
  3523. // Unsure if this is the correct method to handle this case.
  3524. return undefined;
  3525. }
  3526. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3527. if( t < 0 || t > 1 ) {
  3528. return undefined;
  3529. }
  3530. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3531. };
  3532. }(),
  3533. coplanarPoint: function ( optionalTarget ) {
  3534. var result = optionalTarget || new THREE.Vector3();
  3535. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3536. },
  3537. applyMatrix4: function() {
  3538. var v1 = new THREE.Vector3();
  3539. var v2 = new THREE.Vector3();
  3540. return function ( matrix, optionalNormalMatrix ) {
  3541. // compute new normal based on theory here:
  3542. // http://www.songho.ca/opengl/gl_normaltransform.html
  3543. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3544. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3545. var newCoplanarPoint = this.coplanarPoint( v2 );
  3546. newCoplanarPoint.applyMatrix4( matrix );
  3547. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3548. return this;
  3549. };
  3550. }(),
  3551. translate: function ( offset ) {
  3552. this.constant = this.constant - offset.dot( this.normal );
  3553. return this;
  3554. },
  3555. equals: function ( plane ) {
  3556. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3557. },
  3558. clone: function () {
  3559. return new THREE.Plane().copy( this );
  3560. }
  3561. };
  3562. /**
  3563. * @author alteredq / http://alteredqualia.com/
  3564. * @author mrdoob / http://mrdoob.com/
  3565. */
  3566. THREE.Math = {
  3567. PI2: Math.PI * 2,
  3568. generateUUID: function () {
  3569. // http://www.broofa.com/Tools/Math.uuid.htm
  3570. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3571. var uuid = new Array(36);
  3572. var rnd = 0, r;
  3573. return function () {
  3574. for ( var i = 0; i < 36; i ++ ) {
  3575. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3576. uuid[ i ] = '-';
  3577. } else if ( i == 14 ) {
  3578. uuid[ i ] = '4';
  3579. } else {
  3580. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3581. r = rnd & 0xf;
  3582. rnd = rnd >> 4;
  3583. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3584. }
  3585. }
  3586. return uuid.join('');
  3587. };
  3588. }(),
  3589. // Clamp value to range <a, b>
  3590. clamp: function ( x, a, b ) {
  3591. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3592. },
  3593. // Clamp value to range <a, inf)
  3594. clampBottom: function ( x, a ) {
  3595. return x < a ? a : x;
  3596. },
  3597. // Linear mapping from range <a1, a2> to range <b1, b2>
  3598. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3599. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3600. },
  3601. // http://en.wikipedia.org/wiki/Smoothstep
  3602. smoothstep: function ( x, min, max ) {
  3603. if ( x <= min ) return 0;
  3604. if ( x >= max ) return 1;
  3605. x = ( x - min )/( max - min );
  3606. return x*x*(3 - 2*x);
  3607. },
  3608. smootherstep: function ( x, min, max ) {
  3609. if ( x <= min ) return 0;
  3610. if ( x >= max ) return 1;
  3611. x = ( x - min )/( max - min );
  3612. return x*x*x*(x*(x*6 - 15) + 10);
  3613. },
  3614. // Random float from <0, 1> with 16 bits of randomness
  3615. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3616. random16: function () {
  3617. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3618. },
  3619. // Random integer from <low, high> interval
  3620. randInt: function ( low, high ) {
  3621. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3622. },
  3623. // Random float from <low, high> interval
  3624. randFloat: function ( low, high ) {
  3625. return low + Math.random() * ( high - low );
  3626. },
  3627. // Random float from <-range/2, range/2> interval
  3628. randFloatSpread: function ( range ) {
  3629. return range * ( 0.5 - Math.random() );
  3630. },
  3631. sign: function ( x ) {
  3632. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3633. },
  3634. degToRad: function() {
  3635. var degreeToRadiansFactor = Math.PI / 180;
  3636. return function ( degrees ) {
  3637. return degrees * degreeToRadiansFactor;
  3638. };
  3639. }(),
  3640. radToDeg: function() {
  3641. var radianToDegreesFactor = 180 / Math.PI;
  3642. return function ( radians ) {
  3643. return radians * radianToDegreesFactor;
  3644. };
  3645. }()
  3646. };
  3647. /**
  3648. * Spline from Tween.js, slightly optimized (and trashed)
  3649. * http://sole.github.com/tween.js/examples/05_spline.html
  3650. *
  3651. * @author mrdoob / http://mrdoob.com/
  3652. * @author alteredq / http://alteredqualia.com/
  3653. */
  3654. THREE.Spline = function ( points ) {
  3655. this.points = points;
  3656. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3657. point, intPoint, weight, w2, w3,
  3658. pa, pb, pc, pd;
  3659. this.initFromArray = function( a ) {
  3660. this.points = [];
  3661. for ( var i = 0; i < a.length; i++ ) {
  3662. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3663. }
  3664. };
  3665. this.getPoint = function ( k ) {
  3666. point = ( this.points.length - 1 ) * k;
  3667. intPoint = Math.floor( point );
  3668. weight = point - intPoint;
  3669. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3670. c[ 1 ] = intPoint;
  3671. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3672. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3673. pa = this.points[ c[ 0 ] ];
  3674. pb = this.points[ c[ 1 ] ];
  3675. pc = this.points[ c[ 2 ] ];
  3676. pd = this.points[ c[ 3 ] ];
  3677. w2 = weight * weight;
  3678. w3 = weight * w2;
  3679. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3680. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3681. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3682. return v3;
  3683. };
  3684. this.getControlPointsArray = function () {
  3685. var i, p, l = this.points.length,
  3686. coords = [];
  3687. for ( i = 0; i < l; i ++ ) {
  3688. p = this.points[ i ];
  3689. coords[ i ] = [ p.x, p.y, p.z ];
  3690. }
  3691. return coords;
  3692. };
  3693. // approximate length by summing linear segments
  3694. this.getLength = function ( nSubDivisions ) {
  3695. var i, index, nSamples, position,
  3696. point = 0, intPoint = 0, oldIntPoint = 0,
  3697. oldPosition = new THREE.Vector3(),
  3698. tmpVec = new THREE.Vector3(),
  3699. chunkLengths = [],
  3700. totalLength = 0;
  3701. // first point has 0 length
  3702. chunkLengths[ 0 ] = 0;
  3703. if ( !nSubDivisions ) nSubDivisions = 100;
  3704. nSamples = this.points.length * nSubDivisions;
  3705. oldPosition.copy( this.points[ 0 ] );
  3706. for ( i = 1; i < nSamples; i ++ ) {
  3707. index = i / nSamples;
  3708. position = this.getPoint( index );
  3709. tmpVec.copy( position );
  3710. totalLength += tmpVec.distanceTo( oldPosition );
  3711. oldPosition.copy( position );
  3712. point = ( this.points.length - 1 ) * index;
  3713. intPoint = Math.floor( point );
  3714. if ( intPoint != oldIntPoint ) {
  3715. chunkLengths[ intPoint ] = totalLength;
  3716. oldIntPoint = intPoint;
  3717. }
  3718. }
  3719. // last point ends with total length
  3720. chunkLengths[ chunkLengths.length ] = totalLength;
  3721. return { chunks: chunkLengths, total: totalLength };
  3722. };
  3723. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3724. var i, j,
  3725. index, indexCurrent, indexNext,
  3726. linearDistance, realDistance,
  3727. sampling, position,
  3728. newpoints = [],
  3729. tmpVec = new THREE.Vector3(),
  3730. sl = this.getLength();
  3731. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3732. for ( i = 1; i < this.points.length; i++ ) {
  3733. //tmpVec.copy( this.points[ i - 1 ] );
  3734. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3735. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3736. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3737. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3738. indexNext = i / ( this.points.length - 1 );
  3739. for ( j = 1; j < sampling - 1; j++ ) {
  3740. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3741. position = this.getPoint( index );
  3742. newpoints.push( tmpVec.copy( position ).clone() );
  3743. }
  3744. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3745. }
  3746. this.points = newpoints;
  3747. };
  3748. // Catmull-Rom
  3749. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3750. var v0 = ( p2 - p0 ) * 0.5,
  3751. v1 = ( p3 - p1 ) * 0.5;
  3752. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3753. };
  3754. };
  3755. /**
  3756. * @author bhouston / http://exocortex.com
  3757. * @author mrdoob / http://mrdoob.com/
  3758. */
  3759. THREE.Triangle = function ( a, b, c ) {
  3760. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3761. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3762. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3763. };
  3764. THREE.Triangle.normal = function() {
  3765. var v0 = new THREE.Vector3();
  3766. return function ( a, b, c, optionalTarget ) {
  3767. var result = optionalTarget || new THREE.Vector3();
  3768. result.subVectors( c, b );
  3769. v0.subVectors( a, b );
  3770. result.cross( v0 );
  3771. var resultLengthSq = result.lengthSq();
  3772. if( resultLengthSq > 0 ) {
  3773. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3774. }
  3775. return result.set( 0, 0, 0 );
  3776. };
  3777. }();
  3778. // static/instance method to calculate barycoordinates
  3779. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3780. THREE.Triangle.barycoordFromPoint = function() {
  3781. var v0 = new THREE.Vector3();
  3782. var v1 = new THREE.Vector3();
  3783. var v2 = new THREE.Vector3();
  3784. return function ( point, a, b, c, optionalTarget ) {
  3785. v0.subVectors( c, a );
  3786. v1.subVectors( b, a );
  3787. v2.subVectors( point, a );
  3788. var dot00 = v0.dot( v0 );
  3789. var dot01 = v0.dot( v1 );
  3790. var dot02 = v0.dot( v2 );
  3791. var dot11 = v1.dot( v1 );
  3792. var dot12 = v1.dot( v2 );
  3793. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3794. var result = optionalTarget || new THREE.Vector3();
  3795. // colinear or singular triangle
  3796. if( denom == 0 ) {
  3797. // arbitrary location outside of triangle?
  3798. // not sure if this is the best idea, maybe should be returning undefined
  3799. return result.set( -2, -1, -1 );
  3800. }
  3801. var invDenom = 1 / denom;
  3802. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3803. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3804. // barycoordinates must always sum to 1
  3805. return result.set( 1 - u - v, v, u );
  3806. };
  3807. }();
  3808. THREE.Triangle.containsPoint = function() {
  3809. var v1 = new THREE.Vector3();
  3810. return function ( point, a, b, c ) {
  3811. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3812. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3813. };
  3814. }();
  3815. THREE.Triangle.prototype = {
  3816. constructor: THREE.Triangle,
  3817. set: function ( a, b, c ) {
  3818. this.a.copy( a );
  3819. this.b.copy( b );
  3820. this.c.copy( c );
  3821. return this;
  3822. },
  3823. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3824. this.a.copy( points[i0] );
  3825. this.b.copy( points[i1] );
  3826. this.c.copy( points[i2] );
  3827. return this;
  3828. },
  3829. copy: function ( triangle ) {
  3830. this.a.copy( triangle.a );
  3831. this.b.copy( triangle.b );
  3832. this.c.copy( triangle.c );
  3833. return this;
  3834. },
  3835. area: function() {
  3836. var v0 = new THREE.Vector3();
  3837. var v1 = new THREE.Vector3();
  3838. return function () {
  3839. v0.subVectors( this.c, this.b );
  3840. v1.subVectors( this.a, this.b );
  3841. return v0.cross( v1 ).length() * 0.5;
  3842. };
  3843. }(),
  3844. midpoint: function ( optionalTarget ) {
  3845. var result = optionalTarget || new THREE.Vector3();
  3846. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3847. },
  3848. normal: function ( optionalTarget ) {
  3849. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3850. },
  3851. plane: function ( optionalTarget ) {
  3852. var result = optionalTarget || new THREE.Plane();
  3853. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3854. },
  3855. barycoordFromPoint: function ( point, optionalTarget ) {
  3856. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3857. },
  3858. containsPoint: function ( point ) {
  3859. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3860. },
  3861. equals: function ( triangle ) {
  3862. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3863. },
  3864. clone: function () {
  3865. return new THREE.Triangle().copy( this );
  3866. }
  3867. };
  3868. /**
  3869. * @author mrdoob / http://mrdoob.com/
  3870. */
  3871. THREE.Vertex = function ( v ) {
  3872. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3873. return v;
  3874. };
  3875. /**
  3876. * @author mrdoob / http://mrdoob.com/
  3877. */
  3878. THREE.UV = function ( u, v ) {
  3879. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3880. return new THREE.Vector2( u, v );
  3881. };
  3882. /**
  3883. * @author alteredq / http://alteredqualia.com/
  3884. */
  3885. THREE.Clock = function ( autoStart ) {
  3886. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3887. this.startTime = 0;
  3888. this.oldTime = 0;
  3889. this.elapsedTime = 0;
  3890. this.running = false;
  3891. };
  3892. THREE.Clock.prototype = {
  3893. constructor: THREE.Clock,
  3894. start: function () {
  3895. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3896. ? self.performance.now()
  3897. : Date.now();
  3898. this.oldTime = this.startTime;
  3899. this.running = true;
  3900. },
  3901. stop: function () {
  3902. this.getElapsedTime();
  3903. this.running = false;
  3904. },
  3905. getElapsedTime: function () {
  3906. this.getDelta();
  3907. return this.elapsedTime;
  3908. },
  3909. getDelta: function () {
  3910. var diff = 0;
  3911. if ( this.autoStart && ! this.running ) {
  3912. this.start();
  3913. }
  3914. if ( this.running ) {
  3915. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3916. ? self.performance.now()
  3917. : Date.now();
  3918. diff = 0.001 * ( newTime - this.oldTime );
  3919. this.oldTime = newTime;
  3920. this.elapsedTime += diff;
  3921. }
  3922. return diff;
  3923. }
  3924. };
  3925. /**
  3926. * https://github.com/mrdoob/eventdispatcher.js/
  3927. */
  3928. THREE.EventDispatcher = function () {}
  3929. THREE.EventDispatcher.prototype = {
  3930. constructor: THREE.EventDispatcher,
  3931. apply: function ( object ) {
  3932. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  3933. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  3934. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  3935. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  3936. },
  3937. addEventListener: function ( type, listener ) {
  3938. if ( this._listeners === undefined ) this._listeners = {};
  3939. var listeners = this._listeners;
  3940. if ( listeners[ type ] === undefined ) {
  3941. listeners[ type ] = [];
  3942. }
  3943. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3944. listeners[ type ].push( listener );
  3945. }
  3946. },
  3947. hasEventListener: function ( type, listener ) {
  3948. if ( this._listeners === undefined ) return false;
  3949. var listeners = this._listeners;
  3950. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3951. return true;
  3952. }
  3953. return false;
  3954. },
  3955. removeEventListener: function ( type, listener ) {
  3956. if ( this._listeners === undefined ) return;
  3957. var listeners = this._listeners;
  3958. var index = listeners[ type ].indexOf( listener );
  3959. if ( index !== - 1 ) {
  3960. listeners[ type ].splice( index, 1 );
  3961. }
  3962. },
  3963. dispatchEvent: function () {
  3964. var array = [];
  3965. return function ( event ) {
  3966. if ( this._listeners === undefined ) return;
  3967. var listeners = this._listeners;
  3968. var listenerArray = listeners[ event.type ];
  3969. if ( listenerArray !== undefined ) {
  3970. event.target = this;
  3971. var length = listenerArray.length;
  3972. for ( var i = 0; i < length; i ++ ) {
  3973. array[ i ] = listenerArray[ i ];
  3974. }
  3975. for ( var i = 0; i < length; i ++ ) {
  3976. array[ i ].call( this, event );
  3977. }
  3978. }
  3979. };
  3980. }()
  3981. };
  3982. /**
  3983. * @author mrdoob / http://mrdoob.com/
  3984. * @author bhouston / http://exocortex.com/
  3985. * @author stephomi / http://stephaneginier.com/
  3986. */
  3987. ( function ( THREE ) {
  3988. THREE.Raycaster = function ( origin, direction, near, far ) {
  3989. this.ray = new THREE.Ray( origin, direction );
  3990. // direction is assumed to be normalized (for accurate distance calculations)
  3991. this.near = near || 0;
  3992. this.far = far || Infinity;
  3993. };
  3994. var sphere = new THREE.Sphere();
  3995. var localRay = new THREE.Ray();
  3996. var facePlane = new THREE.Plane();
  3997. var intersectPoint = new THREE.Vector3();
  3998. var matrixPosition = new THREE.Vector3();
  3999. var inverseMatrix = new THREE.Matrix4();
  4000. var descSort = function ( a, b ) {
  4001. return a.distance - b.distance;
  4002. };
  4003. var vA = new THREE.Vector3();
  4004. var vB = new THREE.Vector3();
  4005. var vC = new THREE.Vector3();
  4006. var intersectObject = function ( object, raycaster, intersects ) {
  4007. if ( object instanceof THREE.Sprite ) {
  4008. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  4009. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4010. if ( distance > object.scale.x ) {
  4011. return intersects;
  4012. }
  4013. intersects.push( {
  4014. distance: distance,
  4015. point: object.position,
  4016. face: null,
  4017. object: object
  4018. } );
  4019. } else if ( object instanceof THREE.LOD ) {
  4020. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  4021. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4022. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4023. } else if ( object instanceof THREE.Mesh ) {
  4024. var geometry = object.geometry;
  4025. // Checking boundingSphere distance to ray
  4026. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4027. sphere.copy( geometry.boundingSphere );
  4028. sphere.applyMatrix4( object.matrixWorld );
  4029. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4030. return intersects;
  4031. }
  4032. // Check boundingBox before continuing
  4033. inverseMatrix.getInverse( object.matrixWorld );
  4034. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4035. if ( geometry.boundingBox !== null ) {
  4036. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4037. return intersects;
  4038. }
  4039. }
  4040. if ( geometry instanceof THREE.BufferGeometry ) {
  4041. var material = object.material;
  4042. if ( material === undefined ) return intersects;
  4043. if ( geometry.dynamic === false ) return intersects;
  4044. var a, b, c;
  4045. var precision = raycaster.precision;
  4046. if ( geometry.attributes.index !== undefined ) {
  4047. var offsets = geometry.offsets;
  4048. var indices = geometry.attributes.index.array;
  4049. var positions = geometry.attributes.position.array;
  4050. var offLength = geometry.offsets.length;
  4051. var fl = geometry.attributes.index.array.length / 3;
  4052. for ( var oi = 0; oi < offLength; ++oi ) {
  4053. var start = offsets[ oi ].start;
  4054. var count = offsets[ oi ].count;
  4055. var index = offsets[ oi ].index;
  4056. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4057. a = index + indices[ i ];
  4058. b = index + indices[ i + 1 ];
  4059. c = index + indices[ i + 2 ];
  4060. vA.set(
  4061. positions[ a * 3 ],
  4062. positions[ a * 3 + 1 ],
  4063. positions[ a * 3 + 2 ]
  4064. );
  4065. vB.set(
  4066. positions[ b * 3 ],
  4067. positions[ b * 3 + 1 ],
  4068. positions[ b * 3 + 2 ]
  4069. );
  4070. vC.set(
  4071. positions[ c * 3 ],
  4072. positions[ c * 3 + 1 ],
  4073. positions[ c * 3 + 2 ]
  4074. );
  4075. if ( material.side === THREE.BackSide ) {
  4076. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4077. } else {
  4078. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4079. }
  4080. if ( intersectionPoint === null ) continue;
  4081. intersectionPoint.applyMatrix4( object.matrixWorld );
  4082. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4083. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4084. intersects.push( {
  4085. distance: distance,
  4086. point: intersectionPoint,
  4087. face: null,
  4088. faceIndex: null,
  4089. object: object
  4090. } );
  4091. }
  4092. }
  4093. } else {
  4094. var offsets = geometry.offsets;
  4095. var positions = geometry.attributes.position.array;
  4096. var offLength = geometry.offsets.length;
  4097. var fl = geometry.attributes.position.array.length;
  4098. for ( var i = 0; i < fl; i += 3 ) {
  4099. a = i;
  4100. b = i + 1;
  4101. c = i + 2;
  4102. vA.set(
  4103. positions[ a * 3 ],
  4104. positions[ a * 3 + 1 ],
  4105. positions[ a * 3 + 2 ]
  4106. );
  4107. vB.set(
  4108. positions[ b * 3 ],
  4109. positions[ b * 3 + 1 ],
  4110. positions[ b * 3 + 2 ]
  4111. );
  4112. vC.set(
  4113. positions[ c * 3 ],
  4114. positions[ c * 3 + 1 ],
  4115. positions[ c * 3 + 2 ]
  4116. );
  4117. if ( material.side === THREE.BackSide ) {
  4118. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4119. } else {
  4120. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4121. }
  4122. if ( intersectionPoint === null ) continue;
  4123. intersectionPoint.applyMatrix4( object.matrixWorld );
  4124. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4125. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4126. intersects.push( {
  4127. distance: distance,
  4128. point: intersectionPoint,
  4129. face: null,
  4130. faceIndex: null,
  4131. object: object
  4132. } );
  4133. }
  4134. }
  4135. } else if ( geometry instanceof THREE.Geometry ) {
  4136. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4137. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4138. var a, b, c, d;
  4139. var precision = raycaster.precision;
  4140. var vertices = geometry.vertices;
  4141. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4142. var face = geometry.faces[ f ];
  4143. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4144. if ( material === undefined ) continue;
  4145. a = vertices[ face.a ];
  4146. b = vertices[ face.b ];
  4147. c = vertices[ face.c ];
  4148. if ( material.side === THREE.BackSide ) {
  4149. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4150. } else {
  4151. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4152. }
  4153. if ( intersectionPoint === null ) continue;
  4154. intersectionPoint.applyMatrix4( object.matrixWorld );
  4155. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4156. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4157. intersects.push( {
  4158. distance: distance,
  4159. point: intersectionPoint,
  4160. face: face,
  4161. faceIndex: f,
  4162. object: object
  4163. } );
  4164. }
  4165. }
  4166. } else if ( object instanceof THREE.Line ) {
  4167. var precision = raycaster.linePrecision;
  4168. var precisionSq = precision * precision;
  4169. var geometry = object.geometry;
  4170. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4171. // Checking boundingSphere distance to ray
  4172. sphere.copy( geometry.boundingSphere );
  4173. sphere.applyMatrix4( object.matrixWorld );
  4174. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4175. return intersects;
  4176. }
  4177. inverseMatrix.getInverse( object.matrixWorld );
  4178. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4179. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4180. } else */ if ( geometry instanceof THREE.Geometry ) {
  4181. var vertices = geometry.vertices;
  4182. var nbVertices = vertices.length;
  4183. var interSegment = new THREE.Vector3();
  4184. var interRay = new THREE.Vector3();
  4185. var step = object.type === THREE.LineStrip ? 1 : 2;
  4186. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4187. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4188. if ( distSq > precisionSq ) continue;
  4189. var distance = localRay.origin.distanceTo( interRay );
  4190. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4191. intersects.push( {
  4192. distance: distance,
  4193. // What do we want? intersection point on the ray or on the segment??
  4194. // point: raycaster.ray.at( distance ),
  4195. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4196. face: null,
  4197. faceIndex: null,
  4198. object: object
  4199. } );
  4200. }
  4201. }
  4202. }
  4203. };
  4204. var intersectDescendants = function ( object, raycaster, intersects ) {
  4205. var descendants = object.getDescendants();
  4206. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4207. intersectObject( descendants[ i ], raycaster, intersects );
  4208. }
  4209. };
  4210. //
  4211. THREE.Raycaster.prototype.precision = 0.0001;
  4212. THREE.Raycaster.prototype.linePrecision = 1;
  4213. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4214. this.ray.set( origin, direction );
  4215. // direction is assumed to be normalized (for accurate distance calculations)
  4216. };
  4217. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4218. var intersects = [];
  4219. if ( recursive === true ) {
  4220. intersectDescendants( object, this, intersects );
  4221. }
  4222. intersectObject( object, this, intersects );
  4223. intersects.sort( descSort );
  4224. return intersects;
  4225. };
  4226. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4227. var intersects = [];
  4228. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4229. intersectObject( objects[ i ], this, intersects );
  4230. if ( recursive === true ) {
  4231. intersectDescendants( objects[ i ], this, intersects );
  4232. }
  4233. }
  4234. intersects.sort( descSort );
  4235. return intersects;
  4236. };
  4237. }( THREE ) );
  4238. /**
  4239. * @author mrdoob / http://mrdoob.com/
  4240. * @author mikael emtinger / http://gomo.se/
  4241. * @author alteredq / http://alteredqualia.com/
  4242. * @author WestLangley / http://github.com/WestLangley
  4243. */
  4244. THREE.Object3D = function () {
  4245. this.id = THREE.Object3DIdCount ++;
  4246. this.uuid = THREE.Math.generateUUID();
  4247. this.name = '';
  4248. this.parent = undefined;
  4249. this.children = [];
  4250. this.up = new THREE.Vector3( 0, 1, 0 );
  4251. this.position = new THREE.Vector3();
  4252. this._rotation = new THREE.Euler();
  4253. this._quaternion = new THREE.Quaternion();
  4254. this.scale = new THREE.Vector3( 1, 1, 1 );
  4255. // keep rotation and quaternion in sync
  4256. this._rotation._quaternion = this.quaternion;
  4257. this._quaternion._euler = this.rotation;
  4258. this.renderDepth = null;
  4259. this.rotationAutoUpdate = true;
  4260. this.matrix = new THREE.Matrix4();
  4261. this.matrixWorld = new THREE.Matrix4();
  4262. this.matrixAutoUpdate = true;
  4263. this.matrixWorldNeedsUpdate = true;
  4264. this.visible = true;
  4265. this.castShadow = false;
  4266. this.receiveShadow = false;
  4267. this.frustumCulled = true;
  4268. this.userData = {};
  4269. };
  4270. THREE.Object3D.prototype = {
  4271. constructor: THREE.Object3D,
  4272. get rotation () {
  4273. return this._rotation;
  4274. },
  4275. set rotation ( value ) {
  4276. this._rotation = value;
  4277. this._rotation._quaternion = this._quaternion;
  4278. this._quaternion._euler = this._rotation;
  4279. this._rotation._updateQuaternion();
  4280. },
  4281. get quaternion () {
  4282. return this._quaternion;
  4283. },
  4284. set quaternion ( value ) {
  4285. this._quaternion = value;
  4286. this._quaternion._euler = this._rotation;
  4287. this._rotation._quaternion = this._quaternion;
  4288. this._quaternion._updateEuler();
  4289. },
  4290. get eulerOrder () {
  4291. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4292. return this.rotation.order;
  4293. },
  4294. set eulerOrder ( value ) {
  4295. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4296. this.rotation.order = value;
  4297. },
  4298. get useQuaternion () {
  4299. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4300. },
  4301. set useQuaternion ( value ) {
  4302. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4303. },
  4304. applyMatrix: function () {
  4305. var m1 = new THREE.Matrix4();
  4306. return function ( matrix ) {
  4307. this.matrix.multiplyMatrices( matrix, this.matrix );
  4308. this.position.getPositionFromMatrix( this.matrix );
  4309. this.scale.getScaleFromMatrix( this.matrix );
  4310. m1.extractRotation( this.matrix );
  4311. this.quaternion.setFromRotationMatrix( m1 );
  4312. }
  4313. }(),
  4314. setRotationFromAxisAngle: function ( axis, angle ) {
  4315. // assumes axis is normalized
  4316. this.quaternion.setFromAxisAngle( axis, angle );
  4317. },
  4318. setRotationFromEuler: function ( euler ) {
  4319. this.quaternion.setFromEuler( euler, true );
  4320. },
  4321. setRotationFromMatrix: function ( m ) {
  4322. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4323. this.quaternion.setFromRotationMatrix( m );
  4324. },
  4325. setRotationFromQuaternion: function ( q ) {
  4326. // assumes q is normalized
  4327. this.quaternion.copy( q );
  4328. },
  4329. rotateOnAxis: function() {
  4330. // rotate object on axis in object space
  4331. // axis is assumed to be normalized
  4332. var q1 = new THREE.Quaternion();
  4333. return function ( axis, angle ) {
  4334. q1.setFromAxisAngle( axis, angle );
  4335. this.quaternion.multiply( q1 );
  4336. return this;
  4337. }
  4338. }(),
  4339. rotateX: function () {
  4340. var v1 = new THREE.Vector3( 1, 0, 0 );
  4341. return function ( angle ) {
  4342. return this.rotateOnAxis( v1, angle );
  4343. };
  4344. }(),
  4345. rotateY: function () {
  4346. var v1 = new THREE.Vector3( 0, 1, 0 );
  4347. return function ( angle ) {
  4348. return this.rotateOnAxis( v1, angle );
  4349. };
  4350. }(),
  4351. rotateZ: function () {
  4352. var v1 = new THREE.Vector3( 0, 0, 1 );
  4353. return function ( angle ) {
  4354. return this.rotateOnAxis( v1, angle );
  4355. };
  4356. }(),
  4357. translateOnAxis: function () {
  4358. // translate object by distance along axis in object space
  4359. // axis is assumed to be normalized
  4360. var v1 = new THREE.Vector3();
  4361. return function ( axis, distance ) {
  4362. v1.copy( axis );
  4363. v1.applyQuaternion( this.quaternion );
  4364. this.position.add( v1.multiplyScalar( distance ) );
  4365. return this;
  4366. }
  4367. }(),
  4368. translate: function ( distance, axis ) {
  4369. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4370. return this.translateOnAxis( axis, distance );
  4371. },
  4372. translateX: function () {
  4373. var v1 = new THREE.Vector3( 1, 0, 0 );
  4374. return function ( distance ) {
  4375. return this.translateOnAxis( v1, distance );
  4376. };
  4377. }(),
  4378. translateY: function () {
  4379. var v1 = new THREE.Vector3( 0, 1, 0 );
  4380. return function ( distance ) {
  4381. return this.translateOnAxis( v1, distance );
  4382. };
  4383. }(),
  4384. translateZ: function () {
  4385. var v1 = new THREE.Vector3( 0, 0, 1 );
  4386. return function ( distance ) {
  4387. return this.translateOnAxis( v1, distance );
  4388. };
  4389. }(),
  4390. localToWorld: function ( vector ) {
  4391. return vector.applyMatrix4( this.matrixWorld );
  4392. },
  4393. worldToLocal: function () {
  4394. var m1 = new THREE.Matrix4();
  4395. return function ( vector ) {
  4396. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4397. };
  4398. }(),
  4399. lookAt: function () {
  4400. // This routine does not support objects with rotated and/or translated parent(s)
  4401. var m1 = new THREE.Matrix4();
  4402. return function ( vector ) {
  4403. m1.lookAt( vector, this.position, this.up );
  4404. this.quaternion.setFromRotationMatrix( m1 );
  4405. };
  4406. }(),
  4407. add: function ( object ) {
  4408. if ( object === this ) {
  4409. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4410. return;
  4411. }
  4412. if ( object instanceof THREE.Object3D ) {
  4413. if ( object.parent !== undefined ) {
  4414. object.parent.remove( object );
  4415. }
  4416. object.parent = this;
  4417. object.dispatchEvent( { type: 'added' } );
  4418. this.children.push( object );
  4419. // add to scene
  4420. var scene = this;
  4421. while ( scene.parent !== undefined ) {
  4422. scene = scene.parent;
  4423. }
  4424. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4425. scene.__addObject( object );
  4426. }
  4427. }
  4428. },
  4429. remove: function ( object ) {
  4430. var index = this.children.indexOf( object );
  4431. if ( index !== - 1 ) {
  4432. object.parent = undefined;
  4433. object.dispatchEvent( { type: 'removed' } );
  4434. this.children.splice( index, 1 );
  4435. // remove from scene
  4436. var scene = this;
  4437. while ( scene.parent !== undefined ) {
  4438. scene = scene.parent;
  4439. }
  4440. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4441. scene.__removeObject( object );
  4442. }
  4443. }
  4444. },
  4445. traverse: function ( callback ) {
  4446. callback( this );
  4447. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4448. this.children[ i ].traverse( callback );
  4449. }
  4450. },
  4451. getObjectById: function ( id, recursive ) {
  4452. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4453. var child = this.children[ i ];
  4454. if ( child.id === id ) {
  4455. return child;
  4456. }
  4457. if ( recursive === true ) {
  4458. child = child.getObjectById( id, recursive );
  4459. if ( child !== undefined ) {
  4460. return child;
  4461. }
  4462. }
  4463. }
  4464. return undefined;
  4465. },
  4466. getObjectByName: function ( name, recursive ) {
  4467. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4468. var child = this.children[ i ];
  4469. if ( child.name === name ) {
  4470. return child;
  4471. }
  4472. if ( recursive === true ) {
  4473. child = child.getObjectByName( name, recursive );
  4474. if ( child !== undefined ) {
  4475. return child;
  4476. }
  4477. }
  4478. }
  4479. return undefined;
  4480. },
  4481. getChildByName: function ( name, recursive ) {
  4482. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4483. return this.getObjectByName( name, recursive );
  4484. },
  4485. getDescendants: function ( array ) {
  4486. if ( array === undefined ) array = [];
  4487. Array.prototype.push.apply( array, this.children );
  4488. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4489. this.children[ i ].getDescendants( array );
  4490. }
  4491. return array;
  4492. },
  4493. updateMatrix: function () {
  4494. this.matrix.compose( this.position, this.quaternion, this.scale );
  4495. this.matrixWorldNeedsUpdate = true;
  4496. },
  4497. updateMatrixWorld: function ( force ) {
  4498. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4499. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4500. if ( this.parent === undefined ) {
  4501. this.matrixWorld.copy( this.matrix );
  4502. } else {
  4503. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4504. }
  4505. this.matrixWorldNeedsUpdate = false;
  4506. force = true;
  4507. }
  4508. // update children
  4509. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4510. this.children[ i ].updateMatrixWorld( force );
  4511. }
  4512. },
  4513. clone: function ( object, recursive ) {
  4514. if ( object === undefined ) object = new THREE.Object3D();
  4515. if ( recursive === undefined ) recursive = true;
  4516. object.name = this.name;
  4517. object.up.copy( this.up );
  4518. object.position.copy( this.position );
  4519. object.quaternion.copy( this.quaternion );
  4520. object.scale.copy( this.scale );
  4521. object.renderDepth = this.renderDepth;
  4522. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4523. object.matrix.copy( this.matrix );
  4524. object.matrixWorld.copy( this.matrixWorld );
  4525. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4526. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4527. object.visible = this.visible;
  4528. object.castShadow = this.castShadow;
  4529. object.receiveShadow = this.receiveShadow;
  4530. object.frustumCulled = this.frustumCulled;
  4531. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4532. if ( recursive === true ) {
  4533. for ( var i = 0; i < this.children.length; i ++ ) {
  4534. var child = this.children[ i ];
  4535. object.add( child.clone() );
  4536. }
  4537. }
  4538. return object;
  4539. }
  4540. };
  4541. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4542. THREE.Object3DIdCount = 0;
  4543. /**
  4544. * @author mrdoob / http://mrdoob.com/
  4545. * @author supereggbert / http://www.paulbrunt.co.uk/
  4546. * @author julianwa / https://github.com/julianwa
  4547. */
  4548. THREE.Projector = function () {
  4549. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4550. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4551. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4552. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4553. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4554. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4555. _vector3 = new THREE.Vector3(),
  4556. _vector4 = new THREE.Vector4(),
  4557. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4558. _boundingBox = new THREE.Box3(),
  4559. _points3 = new Array( 3 ),
  4560. _points4 = new Array( 4 ),
  4561. _viewMatrix = new THREE.Matrix4(),
  4562. _viewProjectionMatrix = new THREE.Matrix4(),
  4563. _modelMatrix,
  4564. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4565. _normalMatrix = new THREE.Matrix3(),
  4566. _normalViewMatrix = new THREE.Matrix3(),
  4567. _centroid = new THREE.Vector3(),
  4568. _frustum = new THREE.Frustum(),
  4569. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4570. _clippedVertex2PositionScreen = new THREE.Vector4();
  4571. this.projectVector = function ( vector, camera ) {
  4572. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4573. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4574. return vector.applyProjection( _viewProjectionMatrix );
  4575. };
  4576. this.unprojectVector = function ( vector, camera ) {
  4577. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4578. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4579. return vector.applyProjection( _viewProjectionMatrix );
  4580. };
  4581. this.pickingRay = function ( vector, camera ) {
  4582. // set two vectors with opposing z values
  4583. vector.z = -1.0;
  4584. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4585. this.unprojectVector( vector, camera );
  4586. this.unprojectVector( end, camera );
  4587. // find direction from vector to end
  4588. end.sub( vector ).normalize();
  4589. return new THREE.Raycaster( vector, end );
  4590. };
  4591. var getObject = function ( object ) {
  4592. _object = getNextObjectInPool();
  4593. _object.id = object.id;
  4594. _object.object = object;
  4595. if ( object.renderDepth !== null ) {
  4596. _object.z = object.renderDepth;
  4597. } else {
  4598. _vector3.getPositionFromMatrix( object.matrixWorld );
  4599. _vector3.applyProjection( _viewProjectionMatrix );
  4600. _object.z = _vector3.z;
  4601. }
  4602. return _object;
  4603. };
  4604. var projectObject = function ( object ) {
  4605. if ( object.visible === false ) return;
  4606. if ( object instanceof THREE.Light ) {
  4607. _renderData.lights.push( object );
  4608. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4609. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4610. _renderData.objects.push( getObject( object ) );
  4611. }
  4612. } else if ( object instanceof THREE.Sprite ) {
  4613. _renderData.sprites.push( getObject( object ) );
  4614. }
  4615. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4616. projectObject( object.children[ i ] );
  4617. }
  4618. };
  4619. var projectGraph = function ( root, sortObjects ) {
  4620. _objectCount = 0;
  4621. _renderData.objects.length = 0;
  4622. _renderData.sprites.length = 0;
  4623. _renderData.lights.length = 0;
  4624. projectObject( root );
  4625. if ( sortObjects === true ) {
  4626. _renderData.objects.sort( painterSort );
  4627. }
  4628. };
  4629. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4630. var visible = false,
  4631. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4632. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4633. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4634. _face3Count = 0;
  4635. _lineCount = 0;
  4636. _spriteCount = 0;
  4637. _renderData.elements.length = 0;
  4638. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4639. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4640. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4641. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4642. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4643. _frustum.setFromMatrix( _viewProjectionMatrix );
  4644. projectGraph( scene, sortObjects );
  4645. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4646. object = _renderData.objects[ o ].object;
  4647. _modelMatrix = object.matrixWorld;
  4648. _vertexCount = 0;
  4649. if ( object instanceof THREE.Mesh ) {
  4650. geometry = object.geometry;
  4651. vertices = geometry.vertices;
  4652. faces = geometry.faces;
  4653. faceVertexUvs = geometry.faceVertexUvs;
  4654. _normalMatrix.getNormalMatrix( _modelMatrix );
  4655. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4656. objectMaterials = isFaceMaterial === true ? object.material : null;
  4657. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4658. _vertex = getNextVertexInPool();
  4659. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4660. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4661. var invW = 1 / _vertex.positionScreen.w;
  4662. _vertex.positionScreen.x *= invW;
  4663. _vertex.positionScreen.y *= invW;
  4664. _vertex.positionScreen.z *= invW;
  4665. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4666. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4667. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4668. }
  4669. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4670. face = faces[ f ];
  4671. var material = isFaceMaterial === true
  4672. ? objectMaterials.materials[ face.materialIndex ]
  4673. : object.material;
  4674. if ( material === undefined ) continue;
  4675. var side = material.side;
  4676. v1 = _vertexPool[ face.a ];
  4677. v2 = _vertexPool[ face.b ];
  4678. v3 = _vertexPool[ face.c ];
  4679. _points3[ 0 ] = v1.positionScreen;
  4680. _points3[ 1 ] = v2.positionScreen;
  4681. _points3[ 2 ] = v3.positionScreen;
  4682. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4683. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4684. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4685. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4686. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4687. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4688. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4689. _face = getNextFace3InPool();
  4690. _face.id = object.id;
  4691. _face.v1.copy( v1 );
  4692. _face.v2.copy( v2 );
  4693. _face.v3.copy( v3 );
  4694. } else {
  4695. continue;
  4696. }
  4697. } else {
  4698. continue;
  4699. }
  4700. _face.normalModel.copy( face.normal );
  4701. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4702. _face.normalModel.negate();
  4703. }
  4704. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4705. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4706. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4707. faceVertexNormals = face.vertexNormals;
  4708. for ( n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4709. var normalModel = _face.vertexNormalsModel[ n ];
  4710. normalModel.copy( faceVertexNormals[ n ] );
  4711. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4712. normalModel.negate();
  4713. }
  4714. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4715. var normalModelView = _face.vertexNormalsModelView[ n ];
  4716. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4717. }
  4718. _face.vertexNormalsLength = faceVertexNormals.length;
  4719. for ( c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4720. uvs = faceVertexUvs[ c ][ f ];
  4721. if ( uvs === undefined ) continue;
  4722. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4723. _face.uvs[ c ][ u ] = uvs[ u ];
  4724. }
  4725. }
  4726. _face.color = face.color;
  4727. _face.material = material;
  4728. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4729. _face.z = _centroid.z;
  4730. _renderData.elements.push( _face );
  4731. }
  4732. } else if ( object instanceof THREE.Line ) {
  4733. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4734. vertices = object.geometry.vertices;
  4735. v1 = getNextVertexInPool();
  4736. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4737. // Handle LineStrip and LinePieces
  4738. var step = object.type === THREE.LinePieces ? 2 : 1;
  4739. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4740. v1 = getNextVertexInPool();
  4741. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4742. if ( ( v + 1 ) % step > 0 ) continue;
  4743. v2 = _vertexPool[ _vertexCount - 2 ];
  4744. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4745. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4746. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4747. // Perform the perspective divide
  4748. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4749. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4750. _line = getNextLineInPool();
  4751. _line.id = object.id;
  4752. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4753. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4754. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4755. _line.material = object.material;
  4756. if ( object.material.vertexColors === THREE.VertexColors ) {
  4757. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4758. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4759. }
  4760. _renderData.elements.push( _line );
  4761. }
  4762. }
  4763. }
  4764. }
  4765. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4766. object = _renderData.sprites[ o ].object;
  4767. _modelMatrix = object.matrixWorld;
  4768. if ( object instanceof THREE.Sprite ) {
  4769. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4770. _vector4.applyMatrix4( _viewProjectionMatrix );
  4771. var invW = 1 / _vector4.w;
  4772. _vector4.z *= invW;
  4773. if ( _vector4.z > -1 && _vector4.z < 1 ) {
  4774. _sprite = getNextSpriteInPool();
  4775. _sprite.id = object.id;
  4776. _sprite.x = _vector4.x * invW;
  4777. _sprite.y = _vector4.y * invW;
  4778. _sprite.z = _vector4.z;
  4779. _sprite.object = object;
  4780. _sprite.rotation = object.rotation;
  4781. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4782. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4783. _sprite.material = object.material;
  4784. _renderData.elements.push( _sprite );
  4785. }
  4786. }
  4787. }
  4788. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4789. return _renderData;
  4790. };
  4791. // Pools
  4792. function getNextObjectInPool() {
  4793. if ( _objectCount === _objectPoolLength ) {
  4794. var object = new THREE.RenderableObject();
  4795. _objectPool.push( object );
  4796. _objectPoolLength ++;
  4797. _objectCount ++;
  4798. return object;
  4799. }
  4800. return _objectPool[ _objectCount ++ ];
  4801. }
  4802. function getNextVertexInPool() {
  4803. if ( _vertexCount === _vertexPoolLength ) {
  4804. var vertex = new THREE.RenderableVertex();
  4805. _vertexPool.push( vertex );
  4806. _vertexPoolLength ++;
  4807. _vertexCount ++;
  4808. return vertex;
  4809. }
  4810. return _vertexPool[ _vertexCount ++ ];
  4811. }
  4812. function getNextFace3InPool() {
  4813. if ( _face3Count === _face3PoolLength ) {
  4814. var face = new THREE.RenderableFace3();
  4815. _face3Pool.push( face );
  4816. _face3PoolLength ++;
  4817. _face3Count ++;
  4818. return face;
  4819. }
  4820. return _face3Pool[ _face3Count ++ ];
  4821. }
  4822. function getNextLineInPool() {
  4823. if ( _lineCount === _linePoolLength ) {
  4824. var line = new THREE.RenderableLine();
  4825. _linePool.push( line );
  4826. _linePoolLength ++;
  4827. _lineCount ++
  4828. return line;
  4829. }
  4830. return _linePool[ _lineCount ++ ];
  4831. }
  4832. function getNextSpriteInPool() {
  4833. if ( _spriteCount === _spritePoolLength ) {
  4834. var sprite = new THREE.RenderableSprite();
  4835. _spritePool.push( sprite );
  4836. _spritePoolLength ++;
  4837. _spriteCount ++
  4838. return sprite;
  4839. }
  4840. return _spritePool[ _spriteCount ++ ];
  4841. }
  4842. //
  4843. function painterSort( a, b ) {
  4844. if ( a.z !== b.z ) {
  4845. return b.z - a.z;
  4846. } else if ( a.id !== b.id ) {
  4847. return a.id - b.id;
  4848. } else {
  4849. return 0;
  4850. }
  4851. }
  4852. function clipLine( s1, s2 ) {
  4853. var alpha1 = 0, alpha2 = 1,
  4854. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4855. // Z = -1 and Z = +1, respectively.
  4856. bc1near = s1.z + s1.w,
  4857. bc2near = s2.z + s2.w,
  4858. bc1far = - s1.z + s1.w,
  4859. bc2far = - s2.z + s2.w;
  4860. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4861. // Both vertices lie entirely within all clip planes.
  4862. return true;
  4863. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4864. // Both vertices lie entirely outside one of the clip planes.
  4865. return false;
  4866. } else {
  4867. // The line segment spans at least one clip plane.
  4868. if ( bc1near < 0 ) {
  4869. // v1 lies outside the near plane, v2 inside
  4870. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4871. } else if ( bc2near < 0 ) {
  4872. // v2 lies outside the near plane, v1 inside
  4873. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4874. }
  4875. if ( bc1far < 0 ) {
  4876. // v1 lies outside the far plane, v2 inside
  4877. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4878. } else if ( bc2far < 0 ) {
  4879. // v2 lies outside the far plane, v2 inside
  4880. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4881. }
  4882. if ( alpha2 < alpha1 ) {
  4883. // The line segment spans two boundaries, but is outside both of them.
  4884. // (This can't happen when we're only clipping against just near/far but good
  4885. // to leave the check here for future usage if other clip planes are added.)
  4886. return false;
  4887. } else {
  4888. // Update the s1 and s2 vertices to match the clipped line segment.
  4889. s1.lerp( s2, alpha1 );
  4890. s2.lerp( s1, 1 - alpha2 );
  4891. return true;
  4892. }
  4893. }
  4894. }
  4895. };
  4896. /**
  4897. * @author mrdoob / http://mrdoob.com/
  4898. * @author alteredq / http://alteredqualia.com/
  4899. */
  4900. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4901. this.a = a;
  4902. this.b = b;
  4903. this.c = c;
  4904. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4905. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4906. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4907. this.vertexColors = color instanceof Array ? color : [];
  4908. this.vertexTangents = [];
  4909. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4910. this.centroid = new THREE.Vector3();
  4911. };
  4912. THREE.Face3.prototype = {
  4913. constructor: THREE.Face3,
  4914. clone: function () {
  4915. var face = new THREE.Face3( this.a, this.b, this.c );
  4916. face.normal.copy( this.normal );
  4917. face.color.copy( this.color );
  4918. face.centroid.copy( this.centroid );
  4919. face.materialIndex = this.materialIndex;
  4920. var i, il;
  4921. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4922. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4923. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4924. return face;
  4925. }
  4926. };
  4927. /**
  4928. * @author mrdoob / http://mrdoob.com/
  4929. */
  4930. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4931. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  4932. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  4933. };
  4934. /**
  4935. * @author mrdoob / http://mrdoob.com/
  4936. * @author kile / http://kile.stravaganza.org/
  4937. * @author alteredq / http://alteredqualia.com/
  4938. * @author mikael emtinger / http://gomo.se/
  4939. * @author zz85 / http://www.lab4games.net/zz85/blog
  4940. * @author bhouston / http://exocortex.com
  4941. */
  4942. THREE.Geometry = function () {
  4943. this.id = THREE.GeometryIdCount ++;
  4944. this.uuid = THREE.Math.generateUUID();
  4945. this.name = '';
  4946. this.vertices = [];
  4947. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  4948. this.faces = [];
  4949. this.faceVertexUvs = [[]];
  4950. this.morphTargets = [];
  4951. this.morphColors = [];
  4952. this.morphNormals = [];
  4953. this.skinWeights = [];
  4954. this.skinIndices = [];
  4955. this.lineDistances = [];
  4956. this.boundingBox = null;
  4957. this.boundingSphere = null;
  4958. this.hasTangents = false;
  4959. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4960. // update flags
  4961. this.verticesNeedUpdate = false;
  4962. this.elementsNeedUpdate = false;
  4963. this.uvsNeedUpdate = false;
  4964. this.normalsNeedUpdate = false;
  4965. this.tangentsNeedUpdate = false;
  4966. this.colorsNeedUpdate = false;
  4967. this.lineDistancesNeedUpdate = false;
  4968. this.buffersNeedUpdate = false;
  4969. };
  4970. THREE.Geometry.prototype = {
  4971. constructor: THREE.Geometry,
  4972. applyMatrix: function ( matrix ) {
  4973. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4974. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4975. var vertex = this.vertices[ i ];
  4976. vertex.applyMatrix4( matrix );
  4977. }
  4978. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4979. var face = this.faces[ i ];
  4980. face.normal.applyMatrix3( normalMatrix ).normalize();
  4981. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4982. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4983. }
  4984. face.centroid.applyMatrix4( matrix );
  4985. }
  4986. if ( this.boundingBox instanceof THREE.Box3 ) {
  4987. this.computeBoundingBox();
  4988. }
  4989. if ( this.boundingSphere instanceof THREE.Sphere ) {
  4990. this.computeBoundingSphere();
  4991. }
  4992. },
  4993. computeCentroids: function () {
  4994. var f, fl, face;
  4995. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4996. face = this.faces[ f ];
  4997. face.centroid.set( 0, 0, 0 );
  4998. face.centroid.add( this.vertices[ face.a ] );
  4999. face.centroid.add( this.vertices[ face.b ] );
  5000. face.centroid.add( this.vertices[ face.c ] );
  5001. face.centroid.divideScalar( 3 );
  5002. }
  5003. },
  5004. computeFaceNormals: function () {
  5005. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5006. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5007. var face = this.faces[ f ];
  5008. var vA = this.vertices[ face.a ];
  5009. var vB = this.vertices[ face.b ];
  5010. var vC = this.vertices[ face.c ];
  5011. cb.subVectors( vC, vB );
  5012. ab.subVectors( vA, vB );
  5013. cb.cross( ab );
  5014. cb.normalize();
  5015. face.normal.copy( cb );
  5016. }
  5017. },
  5018. computeVertexNormals: function ( areaWeighted ) {
  5019. var v, vl, f, fl, face, vertices;
  5020. // create internal buffers for reuse when calling this method repeatedly
  5021. // (otherwise memory allocation / deallocation every frame is big resource hog)
  5022. if ( this.__tmpVertices === undefined ) {
  5023. this.__tmpVertices = new Array( this.vertices.length );
  5024. vertices = this.__tmpVertices;
  5025. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5026. vertices[ v ] = new THREE.Vector3();
  5027. }
  5028. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5029. face = this.faces[ f ];
  5030. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  5031. }
  5032. } else {
  5033. vertices = this.__tmpVertices;
  5034. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5035. vertices[ v ].set( 0, 0, 0 );
  5036. }
  5037. }
  5038. if ( areaWeighted ) {
  5039. // vertex normals weighted by triangle areas
  5040. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5041. var vA, vB, vC, vD;
  5042. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5043. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5044. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5045. face = this.faces[ f ];
  5046. vA = this.vertices[ face.a ];
  5047. vB = this.vertices[ face.b ];
  5048. vC = this.vertices[ face.c ];
  5049. cb.subVectors( vC, vB );
  5050. ab.subVectors( vA, vB );
  5051. cb.cross( ab );
  5052. vertices[ face.a ].add( cb );
  5053. vertices[ face.b ].add( cb );
  5054. vertices[ face.c ].add( cb );
  5055. }
  5056. } else {
  5057. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5058. face = this.faces[ f ];
  5059. vertices[ face.a ].add( face.normal );
  5060. vertices[ face.b ].add( face.normal );
  5061. vertices[ face.c ].add( face.normal );
  5062. }
  5063. }
  5064. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5065. vertices[ v ].normalize();
  5066. }
  5067. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5068. face = this.faces[ f ];
  5069. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5070. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5071. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5072. }
  5073. },
  5074. computeMorphNormals: function () {
  5075. var i, il, f, fl, face;
  5076. // save original normals
  5077. // - create temp variables on first access
  5078. // otherwise just copy (for faster repeated calls)
  5079. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5080. face = this.faces[ f ];
  5081. if ( ! face.__originalFaceNormal ) {
  5082. face.__originalFaceNormal = face.normal.clone();
  5083. } else {
  5084. face.__originalFaceNormal.copy( face.normal );
  5085. }
  5086. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5087. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5088. if ( ! face.__originalVertexNormals[ i ] ) {
  5089. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5090. } else {
  5091. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5092. }
  5093. }
  5094. }
  5095. // use temp geometry to compute face and vertex normals for each morph
  5096. var tmpGeo = new THREE.Geometry();
  5097. tmpGeo.faces = this.faces;
  5098. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5099. // create on first access
  5100. if ( ! this.morphNormals[ i ] ) {
  5101. this.morphNormals[ i ] = {};
  5102. this.morphNormals[ i ].faceNormals = [];
  5103. this.morphNormals[ i ].vertexNormals = [];
  5104. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5105. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5106. var faceNormal, vertexNormals;
  5107. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5108. face = this.faces[ f ];
  5109. faceNormal = new THREE.Vector3();
  5110. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5111. dstNormalsFace.push( faceNormal );
  5112. dstNormalsVertex.push( vertexNormals );
  5113. }
  5114. }
  5115. var morphNormals = this.morphNormals[ i ];
  5116. // set vertices to morph target
  5117. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5118. // compute morph normals
  5119. tmpGeo.computeFaceNormals();
  5120. tmpGeo.computeVertexNormals();
  5121. // store morph normals
  5122. var faceNormal, vertexNormals;
  5123. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5124. face = this.faces[ f ];
  5125. faceNormal = morphNormals.faceNormals[ f ];
  5126. vertexNormals = morphNormals.vertexNormals[ f ];
  5127. faceNormal.copy( face.normal );
  5128. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5129. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5130. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5131. }
  5132. }
  5133. // restore original normals
  5134. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5135. face = this.faces[ f ];
  5136. face.normal = face.__originalFaceNormal;
  5137. face.vertexNormals = face.__originalVertexNormals;
  5138. }
  5139. },
  5140. computeTangents: function () {
  5141. // based on http://www.terathon.com/code/tangent.html
  5142. // tangents go to vertices
  5143. var f, fl, v, vl, i, il, vertexIndex,
  5144. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5145. x1, x2, y1, y2, z1, z2,
  5146. s1, s2, t1, t2, r, t, test,
  5147. tan1 = [], tan2 = [],
  5148. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5149. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5150. n = new THREE.Vector3(), w;
  5151. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5152. tan1[ v ] = new THREE.Vector3();
  5153. tan2[ v ] = new THREE.Vector3();
  5154. }
  5155. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5156. vA = context.vertices[ a ];
  5157. vB = context.vertices[ b ];
  5158. vC = context.vertices[ c ];
  5159. uvA = uv[ ua ];
  5160. uvB = uv[ ub ];
  5161. uvC = uv[ uc ];
  5162. x1 = vB.x - vA.x;
  5163. x2 = vC.x - vA.x;
  5164. y1 = vB.y - vA.y;
  5165. y2 = vC.y - vA.y;
  5166. z1 = vB.z - vA.z;
  5167. z2 = vC.z - vA.z;
  5168. s1 = uvB.x - uvA.x;
  5169. s2 = uvC.x - uvA.x;
  5170. t1 = uvB.y - uvA.y;
  5171. t2 = uvC.y - uvA.y;
  5172. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5173. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5174. ( t2 * y1 - t1 * y2 ) * r,
  5175. ( t2 * z1 - t1 * z2 ) * r );
  5176. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5177. ( s1 * y2 - s2 * y1 ) * r,
  5178. ( s1 * z2 - s2 * z1 ) * r );
  5179. tan1[ a ].add( sdir );
  5180. tan1[ b ].add( sdir );
  5181. tan1[ c ].add( sdir );
  5182. tan2[ a ].add( tdir );
  5183. tan2[ b ].add( tdir );
  5184. tan2[ c ].add( tdir );
  5185. }
  5186. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5187. face = this.faces[ f ];
  5188. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5189. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5190. }
  5191. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5192. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5193. face = this.faces[ f ];
  5194. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5195. n.copy( face.vertexNormals[ i ] );
  5196. vertexIndex = face[ faceIndex[ i ] ];
  5197. t = tan1[ vertexIndex ];
  5198. // Gram-Schmidt orthogonalize
  5199. tmp.copy( t );
  5200. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5201. // Calculate handedness
  5202. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5203. test = tmp2.dot( tan2[ vertexIndex ] );
  5204. w = (test < 0.0) ? -1.0 : 1.0;
  5205. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5206. }
  5207. }
  5208. this.hasTangents = true;
  5209. },
  5210. computeLineDistances: function ( ) {
  5211. var d = 0;
  5212. var vertices = this.vertices;
  5213. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5214. if ( i > 0 ) {
  5215. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5216. }
  5217. this.lineDistances[ i ] = d;
  5218. }
  5219. },
  5220. computeBoundingBox: function () {
  5221. if ( this.boundingBox === null ) {
  5222. this.boundingBox = new THREE.Box3();
  5223. }
  5224. this.boundingBox.setFromPoints( this.vertices );
  5225. },
  5226. computeBoundingSphere: function () {
  5227. if ( this.boundingSphere === null ) {
  5228. this.boundingSphere = new THREE.Sphere();
  5229. }
  5230. this.boundingSphere.setFromPoints( this.vertices );
  5231. },
  5232. /*
  5233. * Checks for duplicate vertices with hashmap.
  5234. * Duplicated vertices are removed
  5235. * and faces' vertices are updated.
  5236. */
  5237. mergeVertices: function () {
  5238. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5239. var unique = [], changes = [];
  5240. var v, key;
  5241. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5242. var precision = Math.pow( 10, precisionPoints );
  5243. var i,il, face;
  5244. var indices, k, j, jl, u;
  5245. // reset cache of vertices as it now will be changing.
  5246. this.__tmpVertices = undefined;
  5247. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5248. v = this.vertices[ i ];
  5249. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5250. if ( verticesMap[ key ] === undefined ) {
  5251. verticesMap[ key ] = i;
  5252. unique.push( this.vertices[ i ] );
  5253. changes[ i ] = unique.length - 1;
  5254. } else {
  5255. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5256. changes[ i ] = changes[ verticesMap[ key ] ];
  5257. }
  5258. };
  5259. // if faces are completely degenerate after merging vertices, we
  5260. // have to remove them from the geometry.
  5261. var faceIndicesToRemove = [];
  5262. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5263. face = this.faces[ i ];
  5264. face.a = changes[ face.a ];
  5265. face.b = changes[ face.b ];
  5266. face.c = changes[ face.c ];
  5267. indices = [ face.a, face.b, face.c ];
  5268. var dupIndex = -1;
  5269. // if any duplicate vertices are found in a Face3
  5270. // we have to remove the face as nothing can be saved
  5271. for ( var n = 0; n < 3; n ++ ) {
  5272. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5273. dupIndex = n;
  5274. faceIndicesToRemove.push( i );
  5275. break;
  5276. }
  5277. }
  5278. }
  5279. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5280. var idx = faceIndicesToRemove[ i ];
  5281. this.faces.splice( idx, 1 );
  5282. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5283. this.faceVertexUvs[ j ].splice( idx, 1 );
  5284. }
  5285. }
  5286. // Use unique set of vertices
  5287. var diff = this.vertices.length - unique.length;
  5288. this.vertices = unique;
  5289. return diff;
  5290. },
  5291. clone: function () {
  5292. var geometry = new THREE.Geometry();
  5293. var vertices = this.vertices;
  5294. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5295. geometry.vertices.push( vertices[ i ].clone() );
  5296. }
  5297. var faces = this.faces;
  5298. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5299. geometry.faces.push( faces[ i ].clone() );
  5300. }
  5301. var uvs = this.faceVertexUvs[ 0 ];
  5302. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5303. var uv = uvs[ i ], uvCopy = [];
  5304. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5305. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5306. }
  5307. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5308. }
  5309. return geometry;
  5310. },
  5311. dispose: function () {
  5312. this.dispatchEvent( { type: 'dispose' } );
  5313. }
  5314. };
  5315. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5316. THREE.GeometryIdCount = 0;
  5317. /**
  5318. * @author alteredq / http://alteredqualia.com/
  5319. */
  5320. THREE.BufferGeometry = function () {
  5321. this.id = THREE.GeometryIdCount ++;
  5322. this.uuid = THREE.Math.generateUUID();
  5323. this.name = '';
  5324. // attributes
  5325. this.attributes = {};
  5326. // attributes typed arrays are kept only if dynamic flag is set
  5327. this.dynamic = true;
  5328. // offsets for chunks when using indexed elements
  5329. this.offsets = [];
  5330. // boundings
  5331. this.boundingBox = null;
  5332. this.boundingSphere = null;
  5333. this.hasTangents = false;
  5334. // for compatibility
  5335. this.morphTargets = [];
  5336. };
  5337. THREE.BufferGeometry.prototype = {
  5338. constructor: THREE.BufferGeometry,
  5339. addAttribute: function( name, type, numItems, itemSize ) {
  5340. this.attributes[ name ] = {
  5341. itemSize: itemSize,
  5342. array: new type( numItems * itemSize )
  5343. };
  5344. },
  5345. applyMatrix: function ( matrix ) {
  5346. var positionArray;
  5347. var normalArray;
  5348. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5349. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5350. if ( positionArray !== undefined ) {
  5351. matrix.multiplyVector3Array( positionArray );
  5352. this.verticesNeedUpdate = true;
  5353. }
  5354. if ( normalArray !== undefined ) {
  5355. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5356. normalMatrix.multiplyVector3Array( normalArray );
  5357. this.normalizeNormals();
  5358. this.normalsNeedUpdate = true;
  5359. }
  5360. },
  5361. computeBoundingBox: function () {
  5362. if ( this.boundingBox === null ) {
  5363. this.boundingBox = new THREE.Box3();
  5364. }
  5365. var positions = this.attributes[ "position" ].array;
  5366. if ( positions ) {
  5367. var bb = this.boundingBox;
  5368. var x, y, z;
  5369. if( positions.length >= 3 ) {
  5370. bb.min.x = bb.max.x = positions[ 0 ];
  5371. bb.min.y = bb.max.y = positions[ 1 ];
  5372. bb.min.z = bb.max.z = positions[ 2 ];
  5373. }
  5374. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5375. x = positions[ i ];
  5376. y = positions[ i + 1 ];
  5377. z = positions[ i + 2 ];
  5378. // bounding box
  5379. if ( x < bb.min.x ) {
  5380. bb.min.x = x;
  5381. } else if ( x > bb.max.x ) {
  5382. bb.max.x = x;
  5383. }
  5384. if ( y < bb.min.y ) {
  5385. bb.min.y = y;
  5386. } else if ( y > bb.max.y ) {
  5387. bb.max.y = y;
  5388. }
  5389. if ( z < bb.min.z ) {
  5390. bb.min.z = z;
  5391. } else if ( z > bb.max.z ) {
  5392. bb.max.z = z;
  5393. }
  5394. }
  5395. }
  5396. if ( positions === undefined || positions.length === 0 ) {
  5397. this.boundingBox.min.set( 0, 0, 0 );
  5398. this.boundingBox.max.set( 0, 0, 0 );
  5399. }
  5400. },
  5401. computeBoundingSphere: function () {
  5402. var box = new THREE.Box3();
  5403. var vector = new THREE.Vector3();
  5404. return function () {
  5405. if ( this.boundingSphere === null ) {
  5406. this.boundingSphere = new THREE.Sphere();
  5407. }
  5408. var positions = this.attributes[ "position" ].array;
  5409. if ( positions ) {
  5410. var center = this.boundingSphere.center;
  5411. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5412. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5413. box.addPoint( vector );
  5414. }
  5415. box.center( center );
  5416. var maxRadiusSq = 0;
  5417. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5418. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5419. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5420. }
  5421. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5422. }
  5423. }
  5424. }(),
  5425. computeVertexNormals: function () {
  5426. if ( this.attributes[ "position" ] ) {
  5427. var i, il;
  5428. var j, jl;
  5429. var nVertexElements = this.attributes[ "position" ].array.length;
  5430. if ( this.attributes[ "normal" ] === undefined ) {
  5431. this.attributes[ "normal" ] = {
  5432. itemSize: 3,
  5433. array: new Float32Array( nVertexElements )
  5434. };
  5435. } else {
  5436. // reset existing normals to zero
  5437. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5438. this.attributes[ "normal" ].array[ i ] = 0;
  5439. }
  5440. }
  5441. var positions = this.attributes[ "position" ].array;
  5442. var normals = this.attributes[ "normal" ].array;
  5443. var vA, vB, vC, x, y, z,
  5444. pA = new THREE.Vector3(),
  5445. pB = new THREE.Vector3(),
  5446. pC = new THREE.Vector3(),
  5447. cb = new THREE.Vector3(),
  5448. ab = new THREE.Vector3();
  5449. // indexed elements
  5450. if ( this.attributes[ "index" ] ) {
  5451. var indices = this.attributes[ "index" ].array;
  5452. var offsets = this.offsets;
  5453. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5454. var start = offsets[ j ].start;
  5455. var count = offsets[ j ].count;
  5456. var index = offsets[ j ].index;
  5457. for ( i = start, il = start + count; i < il; i += 3 ) {
  5458. vA = index + indices[ i ];
  5459. vB = index + indices[ i + 1 ];
  5460. vC = index + indices[ i + 2 ];
  5461. x = positions[ vA * 3 ];
  5462. y = positions[ vA * 3 + 1 ];
  5463. z = positions[ vA * 3 + 2 ];
  5464. pA.set( x, y, z );
  5465. x = positions[ vB * 3 ];
  5466. y = positions[ vB * 3 + 1 ];
  5467. z = positions[ vB * 3 + 2 ];
  5468. pB.set( x, y, z );
  5469. x = positions[ vC * 3 ];
  5470. y = positions[ vC * 3 + 1 ];
  5471. z = positions[ vC * 3 + 2 ];
  5472. pC.set( x, y, z );
  5473. cb.subVectors( pC, pB );
  5474. ab.subVectors( pA, pB );
  5475. cb.cross( ab );
  5476. normals[ vA * 3 ] += cb.x;
  5477. normals[ vA * 3 + 1 ] += cb.y;
  5478. normals[ vA * 3 + 2 ] += cb.z;
  5479. normals[ vB * 3 ] += cb.x;
  5480. normals[ vB * 3 + 1 ] += cb.y;
  5481. normals[ vB * 3 + 2 ] += cb.z;
  5482. normals[ vC * 3 ] += cb.x;
  5483. normals[ vC * 3 + 1 ] += cb.y;
  5484. normals[ vC * 3 + 2 ] += cb.z;
  5485. }
  5486. }
  5487. // non-indexed elements (unconnected triangle soup)
  5488. } else {
  5489. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5490. x = positions[ i ];
  5491. y = positions[ i + 1 ];
  5492. z = positions[ i + 2 ];
  5493. pA.set( x, y, z );
  5494. x = positions[ i + 3 ];
  5495. y = positions[ i + 4 ];
  5496. z = positions[ i + 5 ];
  5497. pB.set( x, y, z );
  5498. x = positions[ i + 6 ];
  5499. y = positions[ i + 7 ];
  5500. z = positions[ i + 8 ];
  5501. pC.set( x, y, z );
  5502. cb.subVectors( pC, pB );
  5503. ab.subVectors( pA, pB );
  5504. cb.cross( ab );
  5505. normals[ i ] = cb.x;
  5506. normals[ i + 1 ] = cb.y;
  5507. normals[ i + 2 ] = cb.z;
  5508. normals[ i + 3 ] = cb.x;
  5509. normals[ i + 4 ] = cb.y;
  5510. normals[ i + 5 ] = cb.z;
  5511. normals[ i + 6 ] = cb.x;
  5512. normals[ i + 7 ] = cb.y;
  5513. normals[ i + 8 ] = cb.z;
  5514. }
  5515. }
  5516. this.normalizeNormals();
  5517. this.normalsNeedUpdate = true;
  5518. }
  5519. },
  5520. normalizeNormals: function () {
  5521. var normals = this.attributes[ "normal" ].array;
  5522. var x, y, z, n;
  5523. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5524. x = normals[ i ];
  5525. y = normals[ i + 1 ];
  5526. z = normals[ i + 2 ];
  5527. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5528. normals[ i ] *= n;
  5529. normals[ i + 1 ] *= n;
  5530. normals[ i + 2 ] *= n;
  5531. }
  5532. },
  5533. computeTangents: function () {
  5534. // based on http://www.terathon.com/code/tangent.html
  5535. // (per vertex tangents)
  5536. if ( this.attributes[ "index" ] === undefined ||
  5537. this.attributes[ "position" ] === undefined ||
  5538. this.attributes[ "normal" ] === undefined ||
  5539. this.attributes[ "uv" ] === undefined ) {
  5540. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5541. return;
  5542. }
  5543. var indices = this.attributes[ "index" ].array;
  5544. var positions = this.attributes[ "position" ].array;
  5545. var normals = this.attributes[ "normal" ].array;
  5546. var uvs = this.attributes[ "uv" ].array;
  5547. var nVertices = positions.length / 3;
  5548. if ( this.attributes[ "tangent" ] === undefined ) {
  5549. var nTangentElements = 4 * nVertices;
  5550. this.attributes[ "tangent" ] = {
  5551. itemSize: 4,
  5552. array: new Float32Array( nTangentElements )
  5553. };
  5554. }
  5555. var tangents = this.attributes[ "tangent" ].array;
  5556. var tan1 = [], tan2 = [];
  5557. for ( var k = 0; k < nVertices; k ++ ) {
  5558. tan1[ k ] = new THREE.Vector3();
  5559. tan2[ k ] = new THREE.Vector3();
  5560. }
  5561. var xA, yA, zA,
  5562. xB, yB, zB,
  5563. xC, yC, zC,
  5564. uA, vA,
  5565. uB, vB,
  5566. uC, vC,
  5567. x1, x2, y1, y2, z1, z2,
  5568. s1, s2, t1, t2, r;
  5569. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5570. function handleTriangle( a, b, c ) {
  5571. xA = positions[ a * 3 ];
  5572. yA = positions[ a * 3 + 1 ];
  5573. zA = positions[ a * 3 + 2 ];
  5574. xB = positions[ b * 3 ];
  5575. yB = positions[ b * 3 + 1 ];
  5576. zB = positions[ b * 3 + 2 ];
  5577. xC = positions[ c * 3 ];
  5578. yC = positions[ c * 3 + 1 ];
  5579. zC = positions[ c * 3 + 2 ];
  5580. uA = uvs[ a * 2 ];
  5581. vA = uvs[ a * 2 + 1 ];
  5582. uB = uvs[ b * 2 ];
  5583. vB = uvs[ b * 2 + 1 ];
  5584. uC = uvs[ c * 2 ];
  5585. vC = uvs[ c * 2 + 1 ];
  5586. x1 = xB - xA;
  5587. x2 = xC - xA;
  5588. y1 = yB - yA;
  5589. y2 = yC - yA;
  5590. z1 = zB - zA;
  5591. z2 = zC - zA;
  5592. s1 = uB - uA;
  5593. s2 = uC - uA;
  5594. t1 = vB - vA;
  5595. t2 = vC - vA;
  5596. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5597. sdir.set(
  5598. ( t2 * x1 - t1 * x2 ) * r,
  5599. ( t2 * y1 - t1 * y2 ) * r,
  5600. ( t2 * z1 - t1 * z2 ) * r
  5601. );
  5602. tdir.set(
  5603. ( s1 * x2 - s2 * x1 ) * r,
  5604. ( s1 * y2 - s2 * y1 ) * r,
  5605. ( s1 * z2 - s2 * z1 ) * r
  5606. );
  5607. tan1[ a ].add( sdir );
  5608. tan1[ b ].add( sdir );
  5609. tan1[ c ].add( sdir );
  5610. tan2[ a ].add( tdir );
  5611. tan2[ b ].add( tdir );
  5612. tan2[ c ].add( tdir );
  5613. }
  5614. var i, il;
  5615. var j, jl;
  5616. var iA, iB, iC;
  5617. var offsets = this.offsets;
  5618. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5619. var start = offsets[ j ].start;
  5620. var count = offsets[ j ].count;
  5621. var index = offsets[ j ].index;
  5622. for ( i = start, il = start + count; i < il; i += 3 ) {
  5623. iA = index + indices[ i ];
  5624. iB = index + indices[ i + 1 ];
  5625. iC = index + indices[ i + 2 ];
  5626. handleTriangle( iA, iB, iC );
  5627. }
  5628. }
  5629. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5630. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5631. var w, t, test;
  5632. function handleVertex( v ) {
  5633. n.x = normals[ v * 3 ];
  5634. n.y = normals[ v * 3 + 1 ];
  5635. n.z = normals[ v * 3 + 2 ];
  5636. n2.copy( n );
  5637. t = tan1[ v ];
  5638. // Gram-Schmidt orthogonalize
  5639. tmp.copy( t );
  5640. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5641. // Calculate handedness
  5642. tmp2.crossVectors( n2, t );
  5643. test = tmp2.dot( tan2[ v ] );
  5644. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5645. tangents[ v * 4 ] = tmp.x;
  5646. tangents[ v * 4 + 1 ] = tmp.y;
  5647. tangents[ v * 4 + 2 ] = tmp.z;
  5648. tangents[ v * 4 + 3 ] = w;
  5649. }
  5650. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5651. var start = offsets[ j ].start;
  5652. var count = offsets[ j ].count;
  5653. var index = offsets[ j ].index;
  5654. for ( i = start, il = start + count; i < il; i += 3 ) {
  5655. iA = index + indices[ i ];
  5656. iB = index + indices[ i + 1 ];
  5657. iC = index + indices[ i + 2 ];
  5658. handleVertex( iA );
  5659. handleVertex( iB );
  5660. handleVertex( iC );
  5661. }
  5662. }
  5663. this.hasTangents = true;
  5664. this.tangentsNeedUpdate = true;
  5665. },
  5666. clone: function () {
  5667. var geometry = new THREE.BufferGeometry();
  5668. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5669. for ( var attr in this.attributes ) {
  5670. var sourceAttr = this.attributes[ attr ];
  5671. var sourceArray = sourceAttr.array;
  5672. var attribute = {
  5673. itemSize: sourceAttr.itemSize,
  5674. numItems: sourceAttr.numItems,
  5675. array: null
  5676. };
  5677. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5678. var type = types[ i ];
  5679. if ( sourceArray instanceof type ) {
  5680. attribute.array = new type( sourceArray );
  5681. break;
  5682. }
  5683. }
  5684. geometry.attributes[ attr ] = attribute;
  5685. }
  5686. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5687. var offset = this.offsets[ i ];
  5688. geometry.offsets.push( {
  5689. start: offset.start,
  5690. index: offset.index,
  5691. count: offset.count
  5692. } );
  5693. }
  5694. return geometry;
  5695. },
  5696. dispose: function () {
  5697. this.dispatchEvent( { type: 'dispose' } );
  5698. }
  5699. };
  5700. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5701. /**
  5702. * @author mrdoob / http://mrdoob.com/
  5703. * @author mikael emtinger / http://gomo.se/
  5704. * @author WestLangley / http://github.com/WestLangley
  5705. */
  5706. THREE.Camera = function () {
  5707. THREE.Object3D.call( this );
  5708. this.matrixWorldInverse = new THREE.Matrix4();
  5709. this.projectionMatrix = new THREE.Matrix4();
  5710. this.projectionMatrixInverse = new THREE.Matrix4();
  5711. };
  5712. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5713. THREE.Camera.prototype.lookAt = function () {
  5714. // This routine does not support cameras with rotated and/or translated parent(s)
  5715. var m1 = new THREE.Matrix4();
  5716. return function ( vector ) {
  5717. m1.lookAt( this.position, vector, this.up );
  5718. this.quaternion.setFromRotationMatrix( m1 );
  5719. };
  5720. }();
  5721. THREE.Camera.prototype.clone = function (camera) {
  5722. if ( camera === undefined ) camera = new THREE.Camera();
  5723. THREE.Object3D.prototype.clone.call( this, camera );
  5724. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  5725. camera.projectionMatrix.copy( this.projectionMatrix );
  5726. camera.projectionMatrixInverse.copy( this.projectionMatrixInverse );
  5727. return camera;
  5728. };
  5729. /**
  5730. * @author alteredq / http://alteredqualia.com/
  5731. */
  5732. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5733. THREE.Camera.call( this );
  5734. this.left = left;
  5735. this.right = right;
  5736. this.top = top;
  5737. this.bottom = bottom;
  5738. this.near = ( near !== undefined ) ? near : 0.1;
  5739. this.far = ( far !== undefined ) ? far : 2000;
  5740. this.updateProjectionMatrix();
  5741. };
  5742. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5743. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5744. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5745. };
  5746. THREE.OrthographicCamera.prototype.clone = function () {
  5747. var camera = new THREE.OrthographicCamera();
  5748. THREE.Camera.prototype.clone.call( this, camera );
  5749. camera.left = this.left;
  5750. camera.right = this.right;
  5751. camera.top = this.top;
  5752. camera.bottom = this.bottom;
  5753. camera.near = this.near;
  5754. camera.far = this.far;
  5755. return camera;
  5756. };
  5757. /**
  5758. * @author mrdoob / http://mrdoob.com/
  5759. * @author greggman / http://games.greggman.com/
  5760. * @author zz85 / http://www.lab4games.net/zz85/blog
  5761. */
  5762. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5763. THREE.Camera.call( this );
  5764. this.fov = fov !== undefined ? fov : 50;
  5765. this.aspect = aspect !== undefined ? aspect : 1;
  5766. this.near = near !== undefined ? near : 0.1;
  5767. this.far = far !== undefined ? far : 2000;
  5768. this.updateProjectionMatrix();
  5769. };
  5770. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5771. /**
  5772. * Uses Focal Length (in mm) to estimate and set FOV
  5773. * 35mm (fullframe) camera is used if frame size is not specified;
  5774. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5775. */
  5776. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5777. if ( frameHeight === undefined ) frameHeight = 24;
  5778. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5779. this.updateProjectionMatrix();
  5780. }
  5781. /**
  5782. * Sets an offset in a larger frustum. This is useful for multi-window or
  5783. * multi-monitor/multi-machine setups.
  5784. *
  5785. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5786. * the monitors are in grid like this
  5787. *
  5788. * +---+---+---+
  5789. * | A | B | C |
  5790. * +---+---+---+
  5791. * | D | E | F |
  5792. * +---+---+---+
  5793. *
  5794. * then for each monitor you would call it like this
  5795. *
  5796. * var w = 1920;
  5797. * var h = 1080;
  5798. * var fullWidth = w * 3;
  5799. * var fullHeight = h * 2;
  5800. *
  5801. * --A--
  5802. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5803. * --B--
  5804. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5805. * --C--
  5806. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5807. * --D--
  5808. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5809. * --E--
  5810. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5811. * --F--
  5812. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5813. *
  5814. * Note there is no reason monitors have to be the same size or in a grid.
  5815. */
  5816. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5817. this.fullWidth = fullWidth;
  5818. this.fullHeight = fullHeight;
  5819. this.x = x;
  5820. this.y = y;
  5821. this.width = width;
  5822. this.height = height;
  5823. this.updateProjectionMatrix();
  5824. };
  5825. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5826. if ( this.fullWidth ) {
  5827. var aspect = this.fullWidth / this.fullHeight;
  5828. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5829. var bottom = -top;
  5830. var left = aspect * bottom;
  5831. var right = aspect * top;
  5832. var width = Math.abs( right - left );
  5833. var height = Math.abs( top - bottom );
  5834. this.projectionMatrix.makeFrustum(
  5835. left + this.x * width / this.fullWidth,
  5836. left + ( this.x + this.width ) * width / this.fullWidth,
  5837. top - ( this.y + this.height ) * height / this.fullHeight,
  5838. top - this.y * height / this.fullHeight,
  5839. this.near,
  5840. this.far
  5841. );
  5842. } else {
  5843. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5844. }
  5845. };
  5846. THREE.PerspectiveCamera.prototype.clone = function () {
  5847. var camera = new THREE.PerspectiveCamera();
  5848. THREE.Camera.prototype.clone.call( this, camera );
  5849. camera.fov = this.fov;
  5850. camera.aspect = this.aspect;
  5851. camera.near = this.near;
  5852. camera.far = this.far;
  5853. return camera;
  5854. };
  5855. /**
  5856. * @author mrdoob / http://mrdoob.com/
  5857. * @author alteredq / http://alteredqualia.com/
  5858. */
  5859. THREE.Light = function ( hex ) {
  5860. THREE.Object3D.call( this );
  5861. this.color = new THREE.Color( hex );
  5862. };
  5863. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5864. THREE.Light.prototype.clone = function ( light ) {
  5865. if ( light === undefined ) light = new THREE.Light();
  5866. THREE.Object3D.prototype.clone.call( this, light );
  5867. light.color.copy( this.color );
  5868. return light;
  5869. };
  5870. /**
  5871. * @author mrdoob / http://mrdoob.com/
  5872. */
  5873. THREE.AmbientLight = function ( hex ) {
  5874. THREE.Light.call( this, hex );
  5875. };
  5876. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5877. THREE.AmbientLight.prototype.clone = function () {
  5878. var light = new THREE.AmbientLight();
  5879. THREE.Light.prototype.clone.call( this, light );
  5880. return light;
  5881. };
  5882. /**
  5883. * @author MPanknin / http://www.redplant.de/
  5884. * @author alteredq / http://alteredqualia.com/
  5885. */
  5886. THREE.AreaLight = function ( hex, intensity ) {
  5887. THREE.Light.call( this, hex );
  5888. this.normal = new THREE.Vector3( 0, -1, 0 );
  5889. this.right = new THREE.Vector3( 1, 0, 0 );
  5890. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5891. this.width = 1.0;
  5892. this.height = 1.0;
  5893. this.constantAttenuation = 1.5;
  5894. this.linearAttenuation = 0.5;
  5895. this.quadraticAttenuation = 0.1;
  5896. };
  5897. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5898. /**
  5899. * @author mrdoob / http://mrdoob.com/
  5900. * @author alteredq / http://alteredqualia.com/
  5901. */
  5902. THREE.DirectionalLight = function ( hex, intensity ) {
  5903. THREE.Light.call( this, hex );
  5904. this.position.set( 0, 1, 0 );
  5905. this.target = new THREE.Object3D();
  5906. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5907. this.castShadow = false;
  5908. this.onlyShadow = false;
  5909. //
  5910. this.shadowCameraNear = 50;
  5911. this.shadowCameraFar = 5000;
  5912. this.shadowCameraLeft = -500;
  5913. this.shadowCameraRight = 500;
  5914. this.shadowCameraTop = 500;
  5915. this.shadowCameraBottom = -500;
  5916. this.shadowCameraVisible = false;
  5917. this.shadowBias = 0;
  5918. this.shadowDarkness = 0.5;
  5919. this.shadowMapWidth = 512;
  5920. this.shadowMapHeight = 512;
  5921. //
  5922. this.shadowCascade = false;
  5923. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5924. this.shadowCascadeCount = 2;
  5925. this.shadowCascadeBias = [ 0, 0, 0 ];
  5926. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5927. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5928. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5929. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5930. this.shadowCascadeArray = [];
  5931. //
  5932. this.shadowMap = null;
  5933. this.shadowMapSize = null;
  5934. this.shadowCamera = null;
  5935. this.shadowMatrix = null;
  5936. };
  5937. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5938. THREE.DirectionalLight.prototype.clone = function () {
  5939. var light = new THREE.DirectionalLight();
  5940. THREE.Light.prototype.clone.call( this, light );
  5941. light.target = this.target.clone();
  5942. light.intensity = this.intensity;
  5943. light.castShadow = this.castShadow;
  5944. light.onlyShadow = this.onlyShadow;
  5945. return light;
  5946. };
  5947. /**
  5948. * @author alteredq / http://alteredqualia.com/
  5949. */
  5950. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5951. THREE.Light.call( this, skyColorHex );
  5952. this.position.set( 0, 100, 0 );
  5953. this.groundColor = new THREE.Color( groundColorHex );
  5954. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5955. };
  5956. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5957. THREE.HemisphereLight.prototype.clone = function () {
  5958. var light = new THREE.HemisphereLight();
  5959. THREE.Light.prototype.clone.call( this, light );
  5960. light.groundColor.copy( this.groundColor );
  5961. light.intensity = this.intensity;
  5962. return light;
  5963. };
  5964. /**
  5965. * @author mrdoob / http://mrdoob.com/
  5966. */
  5967. THREE.PointLight = function ( hex, intensity, distance ) {
  5968. THREE.Light.call( this, hex );
  5969. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5970. this.distance = ( distance !== undefined ) ? distance : 0;
  5971. };
  5972. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5973. THREE.PointLight.prototype.clone = function () {
  5974. var light = new THREE.PointLight();
  5975. THREE.Light.prototype.clone.call( this, light );
  5976. light.intensity = this.intensity;
  5977. light.distance = this.distance;
  5978. return light;
  5979. };
  5980. /**
  5981. * @author alteredq / http://alteredqualia.com/
  5982. */
  5983. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5984. THREE.Light.call( this, hex );
  5985. this.position.set( 0, 1, 0 );
  5986. this.target = new THREE.Object3D();
  5987. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5988. this.distance = ( distance !== undefined ) ? distance : 0;
  5989. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5990. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5991. this.castShadow = false;
  5992. this.onlyShadow = false;
  5993. //
  5994. this.shadowCameraNear = 50;
  5995. this.shadowCameraFar = 5000;
  5996. this.shadowCameraFov = 50;
  5997. this.shadowCameraVisible = false;
  5998. this.shadowBias = 0;
  5999. this.shadowDarkness = 0.5;
  6000. this.shadowMapWidth = 512;
  6001. this.shadowMapHeight = 512;
  6002. //
  6003. this.shadowMap = null;
  6004. this.shadowMapSize = null;
  6005. this.shadowCamera = null;
  6006. this.shadowMatrix = null;
  6007. };
  6008. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6009. THREE.SpotLight.prototype.clone = function () {
  6010. var light = new THREE.SpotLight();
  6011. THREE.Light.prototype.clone.call( this, light );
  6012. light.target = this.target.clone();
  6013. light.intensity = this.intensity;
  6014. light.distance = this.distance;
  6015. light.angle = this.angle;
  6016. light.exponent = this.exponent;
  6017. light.castShadow = this.castShadow;
  6018. light.onlyShadow = this.onlyShadow;
  6019. return light;
  6020. };
  6021. /**
  6022. * @author alteredq / http://alteredqualia.com/
  6023. */
  6024. THREE.Loader = function ( showStatus ) {
  6025. this.showStatus = showStatus;
  6026. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6027. this.onLoadStart = function () {};
  6028. this.onLoadProgress = function () {};
  6029. this.onLoadComplete = function () {};
  6030. };
  6031. THREE.Loader.prototype = {
  6032. constructor: THREE.Loader,
  6033. crossOrigin: 'anonymous',
  6034. addStatusElement: function () {
  6035. var e = document.createElement( "div" );
  6036. e.style.position = "absolute";
  6037. e.style.right = "0px";
  6038. e.style.top = "0px";
  6039. e.style.fontSize = "0.8em";
  6040. e.style.textAlign = "left";
  6041. e.style.background = "rgba(0,0,0,0.25)";
  6042. e.style.color = "#fff";
  6043. e.style.width = "120px";
  6044. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6045. e.style.zIndex = 1000;
  6046. e.innerHTML = "Loading ...";
  6047. return e;
  6048. },
  6049. updateProgress: function ( progress ) {
  6050. var message = "Loaded ";
  6051. if ( progress.total ) {
  6052. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6053. } else {
  6054. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6055. }
  6056. this.statusDomElement.innerHTML = message;
  6057. },
  6058. extractUrlBase: function ( url ) {
  6059. var parts = url.split( '/' );
  6060. parts.pop();
  6061. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  6062. },
  6063. initMaterials: function ( materials, texturePath ) {
  6064. var array = [];
  6065. for ( var i = 0; i < materials.length; ++ i ) {
  6066. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6067. }
  6068. return array;
  6069. },
  6070. needsTangents: function ( materials ) {
  6071. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6072. var m = materials[ i ];
  6073. if ( m instanceof THREE.ShaderMaterial ) return true;
  6074. }
  6075. return false;
  6076. },
  6077. createMaterial: function ( m, texturePath ) {
  6078. var _this = this;
  6079. function is_pow2( n ) {
  6080. var l = Math.log( n ) / Math.LN2;
  6081. return Math.floor( l ) == l;
  6082. }
  6083. function nearest_pow2( n ) {
  6084. var l = Math.log( n ) / Math.LN2;
  6085. return Math.pow( 2, Math.round( l ) );
  6086. }
  6087. function load_image( where, url ) {
  6088. var image = new Image();
  6089. image.onload = function () {
  6090. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6091. var width = nearest_pow2( this.width );
  6092. var height = nearest_pow2( this.height );
  6093. where.image.width = width;
  6094. where.image.height = height;
  6095. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6096. } else {
  6097. where.image = this;
  6098. }
  6099. where.needsUpdate = true;
  6100. };
  6101. image.crossOrigin = _this.crossOrigin;
  6102. image.src = url;
  6103. }
  6104. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6105. var isCompressed = /\.dds$/i.test( sourceFile );
  6106. var fullPath = texturePath + "/" + sourceFile;
  6107. if ( isCompressed ) {
  6108. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6109. where[ name ] = texture;
  6110. } else {
  6111. var texture = document.createElement( 'canvas' );
  6112. where[ name ] = new THREE.Texture( texture );
  6113. }
  6114. where[ name ].sourceFile = sourceFile;
  6115. if( repeat ) {
  6116. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6117. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6118. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6119. }
  6120. if ( offset ) {
  6121. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6122. }
  6123. if ( wrap ) {
  6124. var wrapMap = {
  6125. "repeat": THREE.RepeatWrapping,
  6126. "mirror": THREE.MirroredRepeatWrapping
  6127. }
  6128. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6129. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6130. }
  6131. if ( anisotropy ) {
  6132. where[ name ].anisotropy = anisotropy;
  6133. }
  6134. if ( ! isCompressed ) {
  6135. load_image( where[ name ], fullPath );
  6136. }
  6137. }
  6138. function rgb2hex( rgb ) {
  6139. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6140. }
  6141. // defaults
  6142. var mtype = "MeshLambertMaterial";
  6143. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6144. // parameters from model file
  6145. if ( m.shading ) {
  6146. var shading = m.shading.toLowerCase();
  6147. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6148. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6149. }
  6150. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6151. mpars.blending = THREE[ m.blending ];
  6152. }
  6153. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6154. mpars.transparent = m.transparent;
  6155. }
  6156. if ( m.depthTest !== undefined ) {
  6157. mpars.depthTest = m.depthTest;
  6158. }
  6159. if ( m.depthWrite !== undefined ) {
  6160. mpars.depthWrite = m.depthWrite;
  6161. }
  6162. if ( m.visible !== undefined ) {
  6163. mpars.visible = m.visible;
  6164. }
  6165. if ( m.flipSided !== undefined ) {
  6166. mpars.side = THREE.BackSide;
  6167. }
  6168. if ( m.doubleSided !== undefined ) {
  6169. mpars.side = THREE.DoubleSide;
  6170. }
  6171. if ( m.wireframe !== undefined ) {
  6172. mpars.wireframe = m.wireframe;
  6173. }
  6174. if ( m.vertexColors !== undefined ) {
  6175. if ( m.vertexColors === "face" ) {
  6176. mpars.vertexColors = THREE.FaceColors;
  6177. } else if ( m.vertexColors ) {
  6178. mpars.vertexColors = THREE.VertexColors;
  6179. }
  6180. }
  6181. // colors
  6182. if ( m.colorDiffuse ) {
  6183. mpars.color = rgb2hex( m.colorDiffuse );
  6184. } else if ( m.DbgColor ) {
  6185. mpars.color = m.DbgColor;
  6186. }
  6187. if ( m.colorSpecular ) {
  6188. mpars.specular = rgb2hex( m.colorSpecular );
  6189. }
  6190. if ( m.colorAmbient ) {
  6191. mpars.ambient = rgb2hex( m.colorAmbient );
  6192. }
  6193. // modifiers
  6194. if ( m.transparency ) {
  6195. mpars.opacity = m.transparency;
  6196. }
  6197. if ( m.specularCoef ) {
  6198. mpars.shininess = m.specularCoef;
  6199. }
  6200. // textures
  6201. if ( m.mapDiffuse && texturePath ) {
  6202. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6203. }
  6204. if ( m.mapLight && texturePath ) {
  6205. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6206. }
  6207. if ( m.mapBump && texturePath ) {
  6208. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6209. }
  6210. if ( m.mapNormal && texturePath ) {
  6211. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6212. }
  6213. if ( m.mapSpecular && texturePath ) {
  6214. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6215. }
  6216. //
  6217. if ( m.mapBumpScale ) {
  6218. mpars.bumpScale = m.mapBumpScale;
  6219. }
  6220. // special case for normal mapped material
  6221. if ( m.mapNormal ) {
  6222. var shader = THREE.ShaderLib[ "normalmap" ];
  6223. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6224. uniforms[ "tNormal" ].value = mpars.normalMap;
  6225. if ( m.mapNormalFactor ) {
  6226. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6227. }
  6228. if ( mpars.map ) {
  6229. uniforms[ "tDiffuse" ].value = mpars.map;
  6230. uniforms[ "enableDiffuse" ].value = true;
  6231. }
  6232. if ( mpars.specularMap ) {
  6233. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6234. uniforms[ "enableSpecular" ].value = true;
  6235. }
  6236. if ( mpars.lightMap ) {
  6237. uniforms[ "tAO" ].value = mpars.lightMap;
  6238. uniforms[ "enableAO" ].value = true;
  6239. }
  6240. // for the moment don't handle displacement texture
  6241. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6242. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6243. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6244. uniforms[ "uShininess" ].value = mpars.shininess;
  6245. if ( mpars.opacity !== undefined ) {
  6246. uniforms[ "uOpacity" ].value = mpars.opacity;
  6247. }
  6248. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6249. var material = new THREE.ShaderMaterial( parameters );
  6250. if ( mpars.transparent ) {
  6251. material.transparent = true;
  6252. }
  6253. } else {
  6254. var material = new THREE[ mtype ]( mpars );
  6255. }
  6256. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6257. return material;
  6258. }
  6259. };
  6260. /**
  6261. * @author mrdoob / http://mrdoob.com/
  6262. */
  6263. THREE.XHRLoader = function ( manager ) {
  6264. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6265. };
  6266. THREE.XHRLoader.prototype = {
  6267. constructor: THREE.XHRLoader,
  6268. load: function ( url, onLoad, onProgress, onError ) {
  6269. var scope = this;
  6270. var request = new XMLHttpRequest();
  6271. if ( onLoad !== undefined ) {
  6272. request.addEventListener( 'load', function ( event ) {
  6273. onLoad( event.target.responseText );
  6274. scope.manager.itemEnd( url );
  6275. }, false );
  6276. }
  6277. if ( onProgress !== undefined ) {
  6278. request.addEventListener( 'progress', function ( event ) {
  6279. onProgress( event );
  6280. }, false );
  6281. }
  6282. if ( onError !== undefined ) {
  6283. request.addEventListener( 'error', function ( event ) {
  6284. onError( event );
  6285. }, false );
  6286. }
  6287. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6288. request.open( 'GET', url, true );
  6289. request.send( null );
  6290. scope.manager.itemStart( url );
  6291. },
  6292. setCrossOrigin: function ( value ) {
  6293. this.crossOrigin = value;
  6294. }
  6295. };
  6296. /**
  6297. * @author mrdoob / http://mrdoob.com/
  6298. */
  6299. THREE.ImageLoader = function ( manager ) {
  6300. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6301. };
  6302. THREE.ImageLoader.prototype = {
  6303. constructor: THREE.ImageLoader,
  6304. load: function ( url, onLoad, onProgress, onError ) {
  6305. var scope = this;
  6306. var image = document.createElement( 'img' );
  6307. if ( onLoad !== undefined ) {
  6308. image.addEventListener( 'load', function ( event ) {
  6309. scope.manager.itemEnd( url );
  6310. onLoad( this );
  6311. }, false );
  6312. }
  6313. if ( onProgress !== undefined ) {
  6314. image.addEventListener( 'progress', function ( event ) {
  6315. onProgress( event );
  6316. }, false );
  6317. }
  6318. if ( onError !== undefined ) {
  6319. image.addEventListener( 'error', function ( event ) {
  6320. onError( event );
  6321. }, false );
  6322. }
  6323. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6324. image.src = url;
  6325. scope.manager.itemStart( url );
  6326. return image;
  6327. },
  6328. setCrossOrigin: function ( value ) {
  6329. this.crossOrigin = value;
  6330. }
  6331. }
  6332. /**
  6333. * @author mrdoob / http://mrdoob.com/
  6334. * @author alteredq / http://alteredqualia.com/
  6335. */
  6336. THREE.JSONLoader = function ( showStatus ) {
  6337. THREE.Loader.call( this, showStatus );
  6338. this.withCredentials = false;
  6339. };
  6340. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6341. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6342. var scope = this;
  6343. // todo: unify load API to for easier SceneLoader use
  6344. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6345. this.onLoadStart();
  6346. this.loadAjaxJSON( this, url, callback, texturePath );
  6347. };
  6348. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6349. var xhr = new XMLHttpRequest();
  6350. var length = 0;
  6351. xhr.onreadystatechange = function () {
  6352. if ( xhr.readyState === xhr.DONE ) {
  6353. if ( xhr.status === 200 || xhr.status === 0 ) {
  6354. if ( xhr.responseText ) {
  6355. var json = JSON.parse( xhr.responseText );
  6356. var result = context.parse( json, texturePath );
  6357. callback( result.geometry, result.materials );
  6358. } else {
  6359. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6360. }
  6361. // in context of more complex asset initialization
  6362. // do not block on single failed file
  6363. // maybe should go even one more level up
  6364. context.onLoadComplete();
  6365. } else {
  6366. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6367. }
  6368. } else if ( xhr.readyState === xhr.LOADING ) {
  6369. if ( callbackProgress ) {
  6370. if ( length === 0 ) {
  6371. length = xhr.getResponseHeader( "Content-Length" );
  6372. }
  6373. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6374. }
  6375. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6376. if ( callbackProgress !== undefined ) {
  6377. length = xhr.getResponseHeader( "Content-Length" );
  6378. }
  6379. }
  6380. };
  6381. xhr.open( "GET", url, true );
  6382. xhr.withCredentials = this.withCredentials;
  6383. xhr.send( null );
  6384. };
  6385. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6386. var scope = this,
  6387. geometry = new THREE.Geometry(),
  6388. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6389. parseModel( scale );
  6390. parseSkin();
  6391. parseMorphing( scale );
  6392. geometry.computeCentroids();
  6393. geometry.computeFaceNormals();
  6394. geometry.computeBoundingSphere();
  6395. function parseModel( scale ) {
  6396. function isBitSet( value, position ) {
  6397. return value & ( 1 << position );
  6398. }
  6399. var i, j, fi,
  6400. offset, zLength,
  6401. colorIndex, normalIndex, uvIndex, materialIndex,
  6402. type,
  6403. isQuad,
  6404. hasMaterial,
  6405. hasFaceVertexUv,
  6406. hasFaceNormal, hasFaceVertexNormal,
  6407. hasFaceColor, hasFaceVertexColor,
  6408. vertex, face, faceA, faceB, color, hex, normal,
  6409. uvLayer, uv, u, v,
  6410. faces = json.faces,
  6411. vertices = json.vertices,
  6412. normals = json.normals,
  6413. colors = json.colors,
  6414. nUvLayers = 0;
  6415. if ( json.uvs !== undefined ) {
  6416. // disregard empty arrays
  6417. for ( i = 0; i < json.uvs.length; i++ ) {
  6418. if ( json.uvs[ i ].length ) nUvLayers ++;
  6419. }
  6420. for ( i = 0; i < nUvLayers; i++ ) {
  6421. geometry.faceVertexUvs[ i ] = [];
  6422. }
  6423. }
  6424. offset = 0;
  6425. zLength = vertices.length;
  6426. while ( offset < zLength ) {
  6427. vertex = new THREE.Vector3();
  6428. vertex.x = vertices[ offset ++ ] * scale;
  6429. vertex.y = vertices[ offset ++ ] * scale;
  6430. vertex.z = vertices[ offset ++ ] * scale;
  6431. geometry.vertices.push( vertex );
  6432. }
  6433. offset = 0;
  6434. zLength = faces.length;
  6435. while ( offset < zLength ) {
  6436. type = faces[ offset ++ ];
  6437. isQuad = isBitSet( type, 0 );
  6438. hasMaterial = isBitSet( type, 1 );
  6439. hasFaceVertexUv = isBitSet( type, 3 );
  6440. hasFaceNormal = isBitSet( type, 4 );
  6441. hasFaceVertexNormal = isBitSet( type, 5 );
  6442. hasFaceColor = isBitSet( type, 6 );
  6443. hasFaceVertexColor = isBitSet( type, 7 );
  6444. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6445. if ( isQuad ) {
  6446. faceA = new THREE.Face3();
  6447. faceA.a = faces[ offset ];
  6448. faceA.b = faces[ offset + 1 ];
  6449. faceA.c = faces[ offset + 3 ];
  6450. faceB = new THREE.Face3();
  6451. faceB.a = faces[ offset + 1 ];
  6452. faceB.b = faces[ offset + 2 ];
  6453. faceB.c = faces[ offset + 3 ];
  6454. offset += 4;
  6455. if ( hasMaterial ) {
  6456. materialIndex = faces[ offset ++ ];
  6457. faceA.materialIndex = materialIndex;
  6458. faceB.materialIndex = materialIndex;
  6459. }
  6460. // to get face <=> uv index correspondence
  6461. fi = geometry.faces.length;
  6462. if ( hasFaceVertexUv ) {
  6463. for ( i = 0; i < nUvLayers; i++ ) {
  6464. uvLayer = json.uvs[ i ];
  6465. geometry.faceVertexUvs[ i ][ fi ] = [];
  6466. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6467. for ( j = 0; j < 4; j ++ ) {
  6468. uvIndex = faces[ offset ++ ];
  6469. u = uvLayer[ uvIndex * 2 ];
  6470. v = uvLayer[ uvIndex * 2 + 1 ];
  6471. uv = new THREE.Vector2( u, v );
  6472. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6473. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6474. }
  6475. }
  6476. }
  6477. if ( hasFaceNormal ) {
  6478. normalIndex = faces[ offset ++ ] * 3;
  6479. faceA.normal.set(
  6480. normals[ normalIndex ++ ],
  6481. normals[ normalIndex ++ ],
  6482. normals[ normalIndex ]
  6483. );
  6484. faceB.normal.copy( faceA.normal );
  6485. }
  6486. if ( hasFaceVertexNormal ) {
  6487. for ( i = 0; i < 4; i++ ) {
  6488. normalIndex = faces[ offset ++ ] * 3;
  6489. normal = new THREE.Vector3(
  6490. normals[ normalIndex ++ ],
  6491. normals[ normalIndex ++ ],
  6492. normals[ normalIndex ]
  6493. );
  6494. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  6495. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  6496. }
  6497. }
  6498. if ( hasFaceColor ) {
  6499. colorIndex = faces[ offset ++ ];
  6500. hex = colors[ colorIndex ];
  6501. faceA.color.setHex( hex );
  6502. faceB.color.setHex( hex );
  6503. }
  6504. if ( hasFaceVertexColor ) {
  6505. for ( i = 0; i < 4; i++ ) {
  6506. colorIndex = faces[ offset ++ ];
  6507. hex = colors[ colorIndex ];
  6508. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  6509. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  6510. }
  6511. }
  6512. geometry.faces.push( faceA );
  6513. geometry.faces.push( faceB );
  6514. } else {
  6515. face = new THREE.Face3();
  6516. face.a = faces[ offset ++ ];
  6517. face.b = faces[ offset ++ ];
  6518. face.c = faces[ offset ++ ];
  6519. if ( hasMaterial ) {
  6520. materialIndex = faces[ offset ++ ];
  6521. face.materialIndex = materialIndex;
  6522. }
  6523. // to get face <=> uv index correspondence
  6524. fi = geometry.faces.length;
  6525. if ( hasFaceVertexUv ) {
  6526. for ( i = 0; i < nUvLayers; i++ ) {
  6527. uvLayer = json.uvs[ i ];
  6528. geometry.faceVertexUvs[ i ][ fi ] = [];
  6529. for ( j = 0; j < 3; j ++ ) {
  6530. uvIndex = faces[ offset ++ ];
  6531. u = uvLayer[ uvIndex * 2 ];
  6532. v = uvLayer[ uvIndex * 2 + 1 ];
  6533. uv = new THREE.Vector2( u, v );
  6534. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6535. }
  6536. }
  6537. }
  6538. if ( hasFaceNormal ) {
  6539. normalIndex = faces[ offset ++ ] * 3;
  6540. face.normal.set(
  6541. normals[ normalIndex ++ ],
  6542. normals[ normalIndex ++ ],
  6543. normals[ normalIndex ]
  6544. );
  6545. }
  6546. if ( hasFaceVertexNormal ) {
  6547. for ( i = 0; i < 3; i++ ) {
  6548. normalIndex = faces[ offset ++ ] * 3;
  6549. normal = new THREE.Vector3(
  6550. normals[ normalIndex ++ ],
  6551. normals[ normalIndex ++ ],
  6552. normals[ normalIndex ]
  6553. );
  6554. face.vertexNormals.push( normal );
  6555. }
  6556. }
  6557. if ( hasFaceColor ) {
  6558. colorIndex = faces[ offset ++ ];
  6559. face.color.setHex( colors[ colorIndex ] );
  6560. }
  6561. if ( hasFaceVertexColor ) {
  6562. for ( i = 0; i < 3; i++ ) {
  6563. colorIndex = faces[ offset ++ ];
  6564. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  6565. }
  6566. }
  6567. geometry.faces.push( face );
  6568. }
  6569. }
  6570. };
  6571. function parseSkin() {
  6572. var i, l, x, y, z, w, a, b, c, d;
  6573. if ( json.skinWeights ) {
  6574. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6575. x = json.skinWeights[ i ];
  6576. y = json.skinWeights[ i + 1 ];
  6577. z = 0;
  6578. w = 0;
  6579. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6580. }
  6581. }
  6582. if ( json.skinIndices ) {
  6583. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6584. a = json.skinIndices[ i ];
  6585. b = json.skinIndices[ i + 1 ];
  6586. c = 0;
  6587. d = 0;
  6588. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6589. }
  6590. }
  6591. geometry.bones = json.bones;
  6592. // could change this to json.animations[0] or remove completely
  6593. geometry.animation = json.animation;
  6594. geometry.animations = json.animations;
  6595. };
  6596. function parseMorphing( scale ) {
  6597. if ( json.morphTargets !== undefined ) {
  6598. var i, l, v, vl, dstVertices, srcVertices;
  6599. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6600. geometry.morphTargets[ i ] = {};
  6601. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6602. geometry.morphTargets[ i ].vertices = [];
  6603. dstVertices = geometry.morphTargets[ i ].vertices;
  6604. srcVertices = json.morphTargets [ i ].vertices;
  6605. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6606. var vertex = new THREE.Vector3();
  6607. vertex.x = srcVertices[ v ] * scale;
  6608. vertex.y = srcVertices[ v + 1 ] * scale;
  6609. vertex.z = srcVertices[ v + 2 ] * scale;
  6610. dstVertices.push( vertex );
  6611. }
  6612. }
  6613. }
  6614. if ( json.morphColors !== undefined ) {
  6615. var i, l, c, cl, dstColors, srcColors, color;
  6616. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6617. geometry.morphColors[ i ] = {};
  6618. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6619. geometry.morphColors[ i ].colors = [];
  6620. dstColors = geometry.morphColors[ i ].colors;
  6621. srcColors = json.morphColors [ i ].colors;
  6622. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6623. color = new THREE.Color( 0xffaa00 );
  6624. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6625. dstColors.push( color );
  6626. }
  6627. }
  6628. }
  6629. };
  6630. if ( json.materials === undefined ) {
  6631. return { geometry: geometry };
  6632. } else {
  6633. var materials = this.initMaterials( json.materials, texturePath );
  6634. if ( this.needsTangents( materials ) ) {
  6635. geometry.computeTangents();
  6636. }
  6637. return { geometry: geometry, materials: materials };
  6638. }
  6639. };
  6640. /**
  6641. * @author mrdoob / http://mrdoob.com/
  6642. */
  6643. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6644. var scope = this;
  6645. var loaded = 0, total = 0;
  6646. this.onLoad = onLoad;
  6647. this.onProgress = onProgress;
  6648. this.onError = onError;
  6649. this.itemStart = function ( url ) {
  6650. total ++;
  6651. };
  6652. this.itemEnd = function ( url ) {
  6653. loaded ++;
  6654. if ( scope.onProgress !== undefined ) {
  6655. scope.onProgress( url, loaded, total );
  6656. }
  6657. if ( loaded === total && scope.onLoad !== undefined ) {
  6658. scope.onLoad();
  6659. }
  6660. };
  6661. };
  6662. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6663. /**
  6664. * @author mrdoob / http://mrdoob.com/
  6665. */
  6666. THREE.BufferGeometryLoader = function ( manager ) {
  6667. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6668. };
  6669. THREE.BufferGeometryLoader.prototype = {
  6670. constructor: THREE.BufferGeometryLoader,
  6671. load: function ( url, onLoad, onProgress, onError ) {
  6672. var scope = this;
  6673. var loader = new THREE.XHRLoader();
  6674. loader.setCrossOrigin( this.crossOrigin );
  6675. loader.load( url, function ( text ) {
  6676. onLoad( scope.parse( JSON.parse( text ) ) );
  6677. } );
  6678. },
  6679. setCrossOrigin: function ( value ) {
  6680. this.crossOrigin = value;
  6681. },
  6682. parse: function ( json ) {
  6683. var geometry = new THREE.BufferGeometry();
  6684. var attributes = json.attributes;
  6685. var offsets = json.offsets;
  6686. var boundingSphere = json.boundingSphere;
  6687. for ( var key in attributes ) {
  6688. var attribute = attributes[ key ];
  6689. geometry.attributes[ key ] = {
  6690. itemSize: attribute.itemSize,
  6691. array: new self[ attribute.type ]( attribute.array )
  6692. }
  6693. }
  6694. if ( offsets !== undefined ) {
  6695. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  6696. }
  6697. if ( boundingSphere !== undefined ) {
  6698. geometry.boundingSphere = new THREE.Sphere(
  6699. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  6700. boundingSphere.radius
  6701. );
  6702. }
  6703. return geometry;
  6704. }
  6705. };
  6706. /**
  6707. * @author mrdoob / http://mrdoob.com/
  6708. */
  6709. THREE.GeometryLoader = function ( manager ) {
  6710. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6711. };
  6712. THREE.GeometryLoader.prototype = {
  6713. constructor: THREE.GeometryLoader,
  6714. load: function ( url, onLoad, onProgress, onError ) {
  6715. var scope = this;
  6716. var loader = new THREE.XHRLoader();
  6717. loader.setCrossOrigin( this.crossOrigin );
  6718. loader.load( url, function ( text ) {
  6719. onLoad( scope.parse( JSON.parse( text ) ) );
  6720. } );
  6721. },
  6722. setCrossOrigin: function ( value ) {
  6723. this.crossOrigin = value;
  6724. },
  6725. parse: function ( json ) {
  6726. }
  6727. };
  6728. /**
  6729. * @author mrdoob / http://mrdoob.com/
  6730. */
  6731. THREE.MaterialLoader = function ( manager ) {
  6732. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6733. };
  6734. THREE.MaterialLoader.prototype = {
  6735. constructor: THREE.MaterialLoader,
  6736. load: function ( url, onLoad, onProgress, onError ) {
  6737. var scope = this;
  6738. var loader = new THREE.XHRLoader();
  6739. loader.setCrossOrigin( this.crossOrigin );
  6740. loader.load( url, function ( text ) {
  6741. onLoad( scope.parse( JSON.parse( text ) ) );
  6742. } );
  6743. },
  6744. setCrossOrigin: function ( value ) {
  6745. this.crossOrigin = value;
  6746. },
  6747. parse: function ( json ) {
  6748. var material = new THREE[ json.type ];
  6749. if ( json.color !== undefined ) material.color.setHex( json.color );
  6750. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  6751. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  6752. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  6753. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  6754. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  6755. if ( json.blending !== undefined ) material.blending = json.blending;
  6756. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  6757. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  6758. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  6759. if ( json.materials !== undefined ) {
  6760. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  6761. material.materials.push( this.parse( json.materials[ i ] ) );
  6762. }
  6763. }
  6764. return material;
  6765. }
  6766. };
  6767. /**
  6768. * @author mrdoob / http://mrdoob.com/
  6769. */
  6770. THREE.ObjectLoader = function ( manager ) {
  6771. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6772. };
  6773. THREE.ObjectLoader.prototype = {
  6774. constructor: THREE.ObjectLoader,
  6775. load: function ( url, onLoad, onProgress, onError ) {
  6776. var scope = this;
  6777. var loader = new THREE.XHRLoader( scope.manager );
  6778. loader.setCrossOrigin( this.crossOrigin );
  6779. loader.load( url, function ( text ) {
  6780. onLoad( scope.parse( JSON.parse( text ) ) );
  6781. } );
  6782. },
  6783. setCrossOrigin: function ( value ) {
  6784. this.crossOrigin = value;
  6785. },
  6786. parse: function ( json ) {
  6787. var geometries = this.parseGeometries( json.geometries );
  6788. var materials = this.parseMaterials( json.materials );
  6789. var object = this.parseObject( json.object, geometries, materials );
  6790. return object;
  6791. },
  6792. parseGeometries: function ( json ) {
  6793. var geometries = {};
  6794. if ( json !== undefined ) {
  6795. var geometryLoader = new THREE.JSONLoader();
  6796. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  6797. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6798. var geometry;
  6799. var data = json[ i ];
  6800. switch ( data.type ) {
  6801. case 'PlaneGeometry':
  6802. geometry = new THREE.PlaneGeometry(
  6803. data.width,
  6804. data.height,
  6805. data.widthSegments,
  6806. data.heightSegments
  6807. );
  6808. break;
  6809. case 'CircleGeometry':
  6810. geometry = new THREE.CircleGeometry(
  6811. data.radius,
  6812. data.segments
  6813. );
  6814. break;
  6815. case 'CubeGeometry':
  6816. geometry = new THREE.CubeGeometry(
  6817. data.width,
  6818. data.height,
  6819. data.depth,
  6820. data.widthSegments,
  6821. data.heightSegments,
  6822. data.depthSegments
  6823. );
  6824. break;
  6825. case 'CylinderGeometry':
  6826. geometry = new THREE.CylinderGeometry(
  6827. data.radiusTop,
  6828. data.radiusBottom,
  6829. data.height,
  6830. data.radialSegments,
  6831. data.heightSegments,
  6832. data.openEnded
  6833. );
  6834. break;
  6835. case 'SphereGeometry':
  6836. geometry = new THREE.SphereGeometry(
  6837. data.radius,
  6838. data.widthSegments,
  6839. data.heightSegments,
  6840. data.phiStart,
  6841. data.phiLength,
  6842. data.thetaStart,
  6843. data.thetaLength
  6844. );
  6845. break;
  6846. case 'IcosahedronGeometry':
  6847. geometry = new THREE.IcosahedronGeometry(
  6848. data.radius,
  6849. data.detail
  6850. );
  6851. break;
  6852. case 'TorusGeometry':
  6853. geometry = new THREE.TorusGeometry(
  6854. data.radius,
  6855. data.tube,
  6856. data.radialSegments,
  6857. data.tubularSegments,
  6858. data.arc
  6859. );
  6860. break;
  6861. case 'TorusKnotGeometry':
  6862. geometry = new THREE.TorusKnotGeometry(
  6863. data.radius,
  6864. data.tube,
  6865. data.radialSegments,
  6866. data.tubularSegments,
  6867. data.p,
  6868. data.q,
  6869. data.heightScale
  6870. );
  6871. break;
  6872. case 'BufferGeometry':
  6873. geometry = bufferGeometryLoader.parse( data.data );
  6874. break;
  6875. case 'Geometry':
  6876. geometry = geometryLoader.parse( data.data ).geometry;
  6877. break;
  6878. }
  6879. geometry.uuid = data.uuid;
  6880. if ( data.name !== undefined ) geometry.name = data.name;
  6881. geometries[ data.uuid ] = geometry;
  6882. }
  6883. }
  6884. return geometries;
  6885. },
  6886. parseMaterials: function ( json ) {
  6887. var materials = {};
  6888. if ( json !== undefined ) {
  6889. var loader = new THREE.MaterialLoader();
  6890. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6891. var data = json[ i ];
  6892. var material = loader.parse( data );
  6893. material.uuid = data.uuid;
  6894. if ( data.name !== undefined ) material.name = data.name;
  6895. materials[ data.uuid ] = material;
  6896. }
  6897. }
  6898. return materials;
  6899. },
  6900. parseObject: function () {
  6901. var matrix = new THREE.Matrix4();
  6902. return function ( data, geometries, materials ) {
  6903. var object;
  6904. switch ( data.type ) {
  6905. case 'Scene':
  6906. object = new THREE.Scene();
  6907. break;
  6908. case 'PerspectiveCamera':
  6909. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6910. break;
  6911. case 'OrthographicCamera':
  6912. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6913. break;
  6914. case 'AmbientLight':
  6915. object = new THREE.AmbientLight( data.color );
  6916. break;
  6917. case 'DirectionalLight':
  6918. object = new THREE.DirectionalLight( data.color, data.intensity );
  6919. break;
  6920. case 'PointLight':
  6921. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6922. break;
  6923. case 'SpotLight':
  6924. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6925. break;
  6926. case 'HemisphereLight':
  6927. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6928. break;
  6929. case 'Mesh':
  6930. var geometry = geometries[ data.geometry ];
  6931. var material = materials[ data.material ];
  6932. if ( geometry === undefined ) {
  6933. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  6934. }
  6935. if ( material === undefined ) {
  6936. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  6937. }
  6938. object = new THREE.Mesh( geometry, material );
  6939. break;
  6940. default:
  6941. object = new THREE.Object3D();
  6942. }
  6943. object.uuid = data.uuid;
  6944. if ( data.name !== undefined ) object.name = data.name;
  6945. if ( data.matrix !== undefined ) {
  6946. matrix.fromArray( data.matrix );
  6947. matrix.decompose( object.position, object.quaternion, object.scale );
  6948. } else {
  6949. if ( data.position !== undefined ) object.position.fromArray( data.position );
  6950. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  6951. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  6952. }
  6953. if ( data.visible !== undefined ) object.visible = data.visible;
  6954. if ( data.userData !== undefined ) object.userData = data.userData;
  6955. if ( data.children !== undefined ) {
  6956. for ( var child in data.children ) {
  6957. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6958. }
  6959. }
  6960. return object;
  6961. }
  6962. }()
  6963. };
  6964. /**
  6965. * @author alteredq / http://alteredqualia.com/
  6966. */
  6967. THREE.SceneLoader = function () {
  6968. this.onLoadStart = function () {};
  6969. this.onLoadProgress = function() {};
  6970. this.onLoadComplete = function () {};
  6971. this.callbackSync = function () {};
  6972. this.callbackProgress = function () {};
  6973. this.geometryHandlers = {};
  6974. this.hierarchyHandlers = {};
  6975. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6976. };
  6977. THREE.SceneLoader.prototype = {
  6978. constructor: THREE.SceneLoader,
  6979. load: function ( url, onLoad, onProgress, onError ) {
  6980. var scope = this;
  6981. var loader = new THREE.XHRLoader( scope.manager );
  6982. loader.setCrossOrigin( this.crossOrigin );
  6983. loader.load( url, function ( text ) {
  6984. scope.parse( JSON.parse( text ), onLoad, url );
  6985. } );
  6986. },
  6987. setCrossOrigin: function ( value ) {
  6988. this.crossOrigin = value;
  6989. },
  6990. addGeometryHandler: function ( typeID, loaderClass ) {
  6991. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  6992. },
  6993. addHierarchyHandler: function ( typeID, loaderClass ) {
  6994. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  6995. },
  6996. parse: function ( json, callbackFinished, url ) {
  6997. var scope = this;
  6998. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6999. var geometry, material, camera, fog,
  7000. texture, images, color,
  7001. light, hex, intensity,
  7002. counter_models, counter_textures,
  7003. total_models, total_textures,
  7004. result;
  7005. var target_array = [];
  7006. var data = json;
  7007. // async geometry loaders
  7008. for ( var typeID in this.geometryHandlers ) {
  7009. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7010. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7011. }
  7012. // async hierachy loaders
  7013. for ( var typeID in this.hierarchyHandlers ) {
  7014. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7015. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7016. }
  7017. counter_models = 0;
  7018. counter_textures = 0;
  7019. result = {
  7020. scene: new THREE.Scene(),
  7021. geometries: {},
  7022. face_materials: {},
  7023. materials: {},
  7024. textures: {},
  7025. objects: {},
  7026. cameras: {},
  7027. lights: {},
  7028. fogs: {},
  7029. empties: {},
  7030. groups: {}
  7031. };
  7032. if ( data.transform ) {
  7033. var position = data.transform.position,
  7034. rotation = data.transform.rotation,
  7035. scale = data.transform.scale;
  7036. if ( position ) {
  7037. result.scene.position.fromArray( position );
  7038. }
  7039. if ( rotation ) {
  7040. result.scene.rotation.fromArray( rotation );
  7041. }
  7042. if ( scale ) {
  7043. result.scene.scale.fromArray( scale );
  7044. }
  7045. if ( position || rotation || scale ) {
  7046. result.scene.updateMatrix();
  7047. result.scene.updateMatrixWorld();
  7048. }
  7049. }
  7050. function get_url( source_url, url_type ) {
  7051. if ( url_type == "relativeToHTML" ) {
  7052. return source_url;
  7053. } else {
  7054. return urlBase + "/" + source_url;
  7055. }
  7056. };
  7057. // toplevel loader function, delegates to handle_children
  7058. function handle_objects() {
  7059. handle_children( result.scene, data.objects );
  7060. }
  7061. // handle all the children from the loaded json and attach them to given parent
  7062. function handle_children( parent, children ) {
  7063. var mat, dst, pos, rot, scl, quat;
  7064. for ( var objID in children ) {
  7065. // check by id if child has already been handled,
  7066. // if not, create new object
  7067. var object = result.objects[ objID ];
  7068. var objJSON = children[ objID ];
  7069. if ( object === undefined ) {
  7070. // meshes
  7071. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7072. if ( objJSON.loading === undefined ) {
  7073. var reservedTypes = {
  7074. "type": 1, "url": 1, "material": 1,
  7075. "position": 1, "rotation": 1, "scale" : 1,
  7076. "visible": 1, "children": 1, "userData": 1,
  7077. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7078. };
  7079. var loaderParameters = {};
  7080. for ( var parType in objJSON ) {
  7081. if ( ! ( parType in reservedTypes ) ) {
  7082. loaderParameters[ parType ] = objJSON[ parType ];
  7083. }
  7084. }
  7085. material = result.materials[ objJSON.material ];
  7086. objJSON.loading = true;
  7087. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7088. // ColladaLoader
  7089. if ( loader.options ) {
  7090. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7091. // UTF8Loader
  7092. // OBJLoader
  7093. } else {
  7094. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7095. }
  7096. }
  7097. } else if ( objJSON.geometry !== undefined ) {
  7098. geometry = result.geometries[ objJSON.geometry ];
  7099. // geometry already loaded
  7100. if ( geometry ) {
  7101. var needsTangents = false;
  7102. material = result.materials[ objJSON.material ];
  7103. needsTangents = material instanceof THREE.ShaderMaterial;
  7104. pos = objJSON.position;
  7105. rot = objJSON.rotation;
  7106. scl = objJSON.scale;
  7107. mat = objJSON.matrix;
  7108. quat = objJSON.quaternion;
  7109. // use materials from the model file
  7110. // if there is no material specified in the object
  7111. if ( ! objJSON.material ) {
  7112. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7113. }
  7114. // use materials from the model file
  7115. // if there is just empty face material
  7116. // (must create new material as each model has its own face material)
  7117. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7118. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7119. }
  7120. if ( material instanceof THREE.MeshFaceMaterial ) {
  7121. for ( var i = 0; i < material.materials.length; i ++ ) {
  7122. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7123. }
  7124. }
  7125. if ( needsTangents ) {
  7126. geometry.computeTangents();
  7127. }
  7128. if ( objJSON.skin ) {
  7129. object = new THREE.SkinnedMesh( geometry, material );
  7130. } else if ( objJSON.morph ) {
  7131. object = new THREE.MorphAnimMesh( geometry, material );
  7132. if ( objJSON.duration !== undefined ) {
  7133. object.duration = objJSON.duration;
  7134. }
  7135. if ( objJSON.time !== undefined ) {
  7136. object.time = objJSON.time;
  7137. }
  7138. if ( objJSON.mirroredLoop !== undefined ) {
  7139. object.mirroredLoop = objJSON.mirroredLoop;
  7140. }
  7141. if ( material.morphNormals ) {
  7142. geometry.computeMorphNormals();
  7143. }
  7144. } else {
  7145. object = new THREE.Mesh( geometry, material );
  7146. }
  7147. object.name = objID;
  7148. if ( mat ) {
  7149. object.matrixAutoUpdate = false;
  7150. object.matrix.set(
  7151. mat[0], mat[1], mat[2], mat[3],
  7152. mat[4], mat[5], mat[6], mat[7],
  7153. mat[8], mat[9], mat[10], mat[11],
  7154. mat[12], mat[13], mat[14], mat[15]
  7155. );
  7156. } else {
  7157. object.position.fromArray( pos );
  7158. if ( quat ) {
  7159. object.quaternion.fromArray( quat );
  7160. } else {
  7161. object.rotation.fromArray( rot );
  7162. }
  7163. object.scale.fromArray( scl );
  7164. }
  7165. object.visible = objJSON.visible;
  7166. object.castShadow = objJSON.castShadow;
  7167. object.receiveShadow = objJSON.receiveShadow;
  7168. parent.add( object );
  7169. result.objects[ objID ] = object;
  7170. }
  7171. // lights
  7172. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7173. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  7174. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  7175. var color = objJSON.color;
  7176. var intensity = objJSON.intensity;
  7177. var distance = objJSON.distance;
  7178. var position = objJSON.position;
  7179. var rotation = objJSON.rotation;
  7180. switch ( objJSON.type ) {
  7181. case 'AmbientLight':
  7182. light = new THREE.AmbientLight( color );
  7183. break;
  7184. case 'PointLight':
  7185. light = new THREE.PointLight( color, intensity, distance );
  7186. light.position.fromArray( position );
  7187. break;
  7188. case 'DirectionalLight':
  7189. light = new THREE.DirectionalLight( color, intensity );
  7190. light.position.fromArray( objJSON.direction );
  7191. break;
  7192. case 'SpotLight':
  7193. light = new THREE.SpotLight( color, intensity, distance, 1 );
  7194. light.angle = objJSON.angle;
  7195. light.position.fromArray( position );
  7196. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7197. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7198. break;
  7199. case 'HemisphereLight':
  7200. light = new THREE.DirectionalLight( color, intensity, distance );
  7201. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7202. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7203. break;
  7204. case 'AreaLight':
  7205. light = new THREE.AreaLight(color, intensity);
  7206. light.position.fromArray( position );
  7207. light.width = objJSON.size;
  7208. light.height = objJSON.size_y;
  7209. break;
  7210. }
  7211. parent.add( light );
  7212. light.name = objID;
  7213. result.lights[ objID ] = light;
  7214. result.objects[ objID ] = light;
  7215. // cameras
  7216. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7217. pos = objJSON.position;
  7218. rot = objJSON.rotation;
  7219. quat = objJSON.quaternion;
  7220. if ( objJSON.type === "PerspectiveCamera" ) {
  7221. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7222. } else if ( objJSON.type === "OrthographicCamera" ) {
  7223. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7224. }
  7225. camera.name = objID;
  7226. camera.position.fromArray( pos );
  7227. if ( quat !== undefined ) {
  7228. camera.quaternion.fromArray( quat );
  7229. } else if ( rot !== undefined ) {
  7230. camera.rotation.fromArray( rot );
  7231. }
  7232. parent.add( camera );
  7233. result.cameras[ objID ] = camera;
  7234. result.objects[ objID ] = camera;
  7235. // pure Object3D
  7236. } else {
  7237. pos = objJSON.position;
  7238. rot = objJSON.rotation;
  7239. scl = objJSON.scale;
  7240. quat = objJSON.quaternion;
  7241. object = new THREE.Object3D();
  7242. object.name = objID;
  7243. object.position.fromArray( pos );
  7244. if ( quat ) {
  7245. object.quaternion.fromArray( quat );
  7246. } else {
  7247. object.rotation.fromArray( rot );
  7248. }
  7249. object.scale.fromArray( scl );
  7250. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7251. parent.add( object );
  7252. result.objects[ objID ] = object;
  7253. result.empties[ objID ] = object;
  7254. }
  7255. if ( object ) {
  7256. if ( objJSON.userData !== undefined ) {
  7257. for ( var key in objJSON.userData ) {
  7258. var value = objJSON.userData[ key ];
  7259. object.userData[ key ] = value;
  7260. }
  7261. }
  7262. if ( objJSON.groups !== undefined ) {
  7263. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7264. var groupID = objJSON.groups[ i ];
  7265. if ( result.groups[ groupID ] === undefined ) {
  7266. result.groups[ groupID ] = [];
  7267. }
  7268. result.groups[ groupID ].push( objID );
  7269. }
  7270. }
  7271. }
  7272. }
  7273. if ( object !== undefined && objJSON.children !== undefined ) {
  7274. handle_children( object, objJSON.children );
  7275. }
  7276. }
  7277. };
  7278. function handle_mesh( geo, mat, id ) {
  7279. result.geometries[ id ] = geo;
  7280. result.face_materials[ id ] = mat;
  7281. handle_objects();
  7282. };
  7283. function handle_hierarchy( node, id, parent, material, obj ) {
  7284. var p = obj.position;
  7285. var r = obj.rotation;
  7286. var q = obj.quaternion;
  7287. var s = obj.scale;
  7288. node.position.fromArray( p );
  7289. if ( q ) {
  7290. node.quaternion.fromArray( q );
  7291. } else {
  7292. node.rotation.fromArray( r );
  7293. }
  7294. node.scale.fromArray( s );
  7295. // override children materials
  7296. // if object material was specified in JSON explicitly
  7297. if ( material ) {
  7298. node.traverse( function ( child ) {
  7299. child.material = material;
  7300. } );
  7301. }
  7302. // override children visibility
  7303. // with root node visibility as specified in JSON
  7304. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7305. node.traverse( function ( child ) {
  7306. child.visible = visible;
  7307. } );
  7308. parent.add( node );
  7309. node.name = id;
  7310. result.objects[ id ] = node;
  7311. handle_objects();
  7312. };
  7313. function create_callback_geometry( id ) {
  7314. return function ( geo, mat ) {
  7315. geo.name = id;
  7316. handle_mesh( geo, mat, id );
  7317. counter_models -= 1;
  7318. scope.onLoadComplete();
  7319. async_callback_gate();
  7320. }
  7321. };
  7322. function create_callback_hierachy( id, parent, material, obj ) {
  7323. return function ( event ) {
  7324. var result;
  7325. // loaders which use EventDispatcher
  7326. if ( event.content ) {
  7327. result = event.content;
  7328. // ColladaLoader
  7329. } else if ( event.dae ) {
  7330. result = event.scene;
  7331. // UTF8Loader
  7332. } else {
  7333. result = event;
  7334. }
  7335. handle_hierarchy( result, id, parent, material, obj );
  7336. counter_models -= 1;
  7337. scope.onLoadComplete();
  7338. async_callback_gate();
  7339. }
  7340. };
  7341. function create_callback_embed( id ) {
  7342. return function ( geo, mat ) {
  7343. geo.name = id;
  7344. result.geometries[ id ] = geo;
  7345. result.face_materials[ id ] = mat;
  7346. }
  7347. };
  7348. function async_callback_gate() {
  7349. var progress = {
  7350. totalModels : total_models,
  7351. totalTextures : total_textures,
  7352. loadedModels : total_models - counter_models,
  7353. loadedTextures : total_textures - counter_textures
  7354. };
  7355. scope.callbackProgress( progress, result );
  7356. scope.onLoadProgress();
  7357. if ( counter_models === 0 && counter_textures === 0 ) {
  7358. finalize();
  7359. callbackFinished( result );
  7360. }
  7361. };
  7362. function finalize() {
  7363. // take care of targets which could be asynchronously loaded objects
  7364. for ( var i = 0; i < target_array.length; i ++ ) {
  7365. var ta = target_array[ i ];
  7366. var target = result.objects[ ta.targetName ];
  7367. if ( target ) {
  7368. ta.object.target = target;
  7369. } else {
  7370. // if there was error and target of specified name doesn't exist in the scene file
  7371. // create instead dummy target
  7372. // (target must be added to scene explicitly as parent is already added)
  7373. ta.object.target = new THREE.Object3D();
  7374. result.scene.add( ta.object.target );
  7375. }
  7376. ta.object.target.userData.targetInverse = ta.object;
  7377. }
  7378. };
  7379. var callbackTexture = function ( count ) {
  7380. counter_textures -= count;
  7381. async_callback_gate();
  7382. scope.onLoadComplete();
  7383. };
  7384. // must use this instead of just directly calling callbackTexture
  7385. // because of closure in the calling context loop
  7386. var generateTextureCallback = function ( count ) {
  7387. return function () {
  7388. callbackTexture( count );
  7389. };
  7390. };
  7391. function traverse_json_hierarchy( objJSON, callback ) {
  7392. callback( objJSON );
  7393. if ( objJSON.children !== undefined ) {
  7394. for ( var objChildID in objJSON.children ) {
  7395. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7396. }
  7397. }
  7398. };
  7399. // first go synchronous elements
  7400. // fogs
  7401. var fogID, fogJSON;
  7402. for ( fogID in data.fogs ) {
  7403. fogJSON = data.fogs[ fogID ];
  7404. if ( fogJSON.type === "linear" ) {
  7405. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7406. } else if ( fogJSON.type === "exp2" ) {
  7407. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7408. }
  7409. color = fogJSON.color;
  7410. fog.color.setRGB( color[0], color[1], color[2] );
  7411. result.fogs[ fogID ] = fog;
  7412. }
  7413. // now come potentially asynchronous elements
  7414. // geometries
  7415. // count how many geometries will be loaded asynchronously
  7416. var geoID, geoJSON;
  7417. for ( geoID in data.geometries ) {
  7418. geoJSON = data.geometries[ geoID ];
  7419. if ( geoJSON.type in this.geometryHandlers ) {
  7420. counter_models += 1;
  7421. scope.onLoadStart();
  7422. }
  7423. }
  7424. // count how many hierarchies will be loaded asynchronously
  7425. for ( var objID in data.objects ) {
  7426. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7427. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7428. counter_models += 1;
  7429. scope.onLoadStart();
  7430. }
  7431. });
  7432. }
  7433. total_models = counter_models;
  7434. for ( geoID in data.geometries ) {
  7435. geoJSON = data.geometries[ geoID ];
  7436. if ( geoJSON.type === "cube" ) {
  7437. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7438. geometry.name = geoID;
  7439. result.geometries[ geoID ] = geometry;
  7440. } else if ( geoJSON.type === "plane" ) {
  7441. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7442. geometry.name = geoID;
  7443. result.geometries[ geoID ] = geometry;
  7444. } else if ( geoJSON.type === "sphere" ) {
  7445. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7446. geometry.name = geoID;
  7447. result.geometries[ geoID ] = geometry;
  7448. } else if ( geoJSON.type === "cylinder" ) {
  7449. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7450. geometry.name = geoID;
  7451. result.geometries[ geoID ] = geometry;
  7452. } else if ( geoJSON.type === "torus" ) {
  7453. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7454. geometry.name = geoID;
  7455. result.geometries[ geoID ] = geometry;
  7456. } else if ( geoJSON.type === "icosahedron" ) {
  7457. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7458. geometry.name = geoID;
  7459. result.geometries[ geoID ] = geometry;
  7460. } else if ( geoJSON.type in this.geometryHandlers ) {
  7461. var loaderParameters = {};
  7462. for ( var parType in geoJSON ) {
  7463. if ( parType !== "type" && parType !== "url" ) {
  7464. loaderParameters[ parType ] = geoJSON[ parType ];
  7465. }
  7466. }
  7467. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7468. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7469. } else if ( geoJSON.type === "embedded" ) {
  7470. var modelJson = data.embeds[ geoJSON.id ],
  7471. texture_path = "";
  7472. // pass metadata along to jsonLoader so it knows the format version
  7473. modelJson.metadata = data.metadata;
  7474. if ( modelJson ) {
  7475. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7476. var model = jsonLoader.parse( modelJson, texture_path );
  7477. create_callback_embed( geoID )( model.geometry, model.materials );
  7478. }
  7479. }
  7480. }
  7481. // textures
  7482. // count how many textures will be loaded asynchronously
  7483. var textureID, textureJSON;
  7484. for ( textureID in data.textures ) {
  7485. textureJSON = data.textures[ textureID ];
  7486. if ( textureJSON.url instanceof Array ) {
  7487. counter_textures += textureJSON.url.length;
  7488. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7489. scope.onLoadStart();
  7490. }
  7491. } else {
  7492. counter_textures += 1;
  7493. scope.onLoadStart();
  7494. }
  7495. }
  7496. total_textures = counter_textures;
  7497. for ( textureID in data.textures ) {
  7498. textureJSON = data.textures[ textureID ];
  7499. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7500. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7501. }
  7502. if ( textureJSON.url instanceof Array ) {
  7503. var count = textureJSON.url.length;
  7504. var url_array = [];
  7505. for( var i = 0; i < count; i ++ ) {
  7506. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7507. }
  7508. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7509. if ( isCompressed ) {
  7510. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7511. } else {
  7512. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7513. }
  7514. } else {
  7515. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7516. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7517. var textureCallback = generateTextureCallback( 1 );
  7518. if ( isCompressed ) {
  7519. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7520. } else {
  7521. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7522. }
  7523. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7524. texture.minFilter = THREE[ textureJSON.minFilter ];
  7525. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7526. texture.magFilter = THREE[ textureJSON.magFilter ];
  7527. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7528. if ( textureJSON.repeat ) {
  7529. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7530. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7531. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7532. }
  7533. if ( textureJSON.offset ) {
  7534. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7535. }
  7536. // handle wrap after repeat so that default repeat can be overriden
  7537. if ( textureJSON.wrap ) {
  7538. var wrapMap = {
  7539. "repeat": THREE.RepeatWrapping,
  7540. "mirror": THREE.MirroredRepeatWrapping
  7541. }
  7542. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7543. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7544. }
  7545. }
  7546. result.textures[ textureID ] = texture;
  7547. }
  7548. // materials
  7549. var matID, matJSON;
  7550. var parID;
  7551. for ( matID in data.materials ) {
  7552. matJSON = data.materials[ matID ];
  7553. for ( parID in matJSON.parameters ) {
  7554. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7555. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7556. } else if ( parID === "shading" ) {
  7557. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7558. } else if ( parID === "side" ) {
  7559. if ( matJSON.parameters[ parID ] == "double" ) {
  7560. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7561. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7562. matJSON.parameters[ parID ] = THREE.BackSide;
  7563. } else {
  7564. matJSON.parameters[ parID ] = THREE.FrontSide;
  7565. }
  7566. } else if ( parID === "blending" ) {
  7567. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7568. } else if ( parID === "combine" ) {
  7569. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7570. } else if ( parID === "vertexColors" ) {
  7571. if ( matJSON.parameters[ parID ] == "face" ) {
  7572. matJSON.parameters[ parID ] = THREE.FaceColors;
  7573. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7574. } else if ( matJSON.parameters[ parID ] ) {
  7575. matJSON.parameters[ parID ] = THREE.VertexColors;
  7576. }
  7577. } else if ( parID === "wrapRGB" ) {
  7578. var v3 = matJSON.parameters[ parID ];
  7579. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7580. }
  7581. }
  7582. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7583. matJSON.parameters.transparent = true;
  7584. }
  7585. if ( matJSON.parameters.normalMap ) {
  7586. var shader = THREE.ShaderLib[ "normalmap" ];
  7587. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7588. var diffuse = matJSON.parameters.color;
  7589. var specular = matJSON.parameters.specular;
  7590. var ambient = matJSON.parameters.ambient;
  7591. var shininess = matJSON.parameters.shininess;
  7592. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7593. if ( matJSON.parameters.normalScale ) {
  7594. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7595. }
  7596. if ( matJSON.parameters.map ) {
  7597. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7598. uniforms[ "enableDiffuse" ].value = true;
  7599. }
  7600. if ( matJSON.parameters.envMap ) {
  7601. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7602. uniforms[ "enableReflection" ].value = true;
  7603. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7604. }
  7605. if ( matJSON.parameters.lightMap ) {
  7606. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7607. uniforms[ "enableAO" ].value = true;
  7608. }
  7609. if ( matJSON.parameters.specularMap ) {
  7610. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7611. uniforms[ "enableSpecular" ].value = true;
  7612. }
  7613. if ( matJSON.parameters.displacementMap ) {
  7614. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7615. uniforms[ "enableDisplacement" ].value = true;
  7616. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7617. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7618. }
  7619. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7620. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7621. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7622. uniforms[ "uShininess" ].value = shininess;
  7623. if ( matJSON.parameters.opacity ) {
  7624. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7625. }
  7626. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7627. material = new THREE.ShaderMaterial( parameters );
  7628. } else {
  7629. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7630. }
  7631. material.name = matID;
  7632. result.materials[ matID ] = material;
  7633. }
  7634. // second pass through all materials to initialize MeshFaceMaterials
  7635. // that could be referring to other materials out of order
  7636. for ( matID in data.materials ) {
  7637. matJSON = data.materials[ matID ];
  7638. if ( matJSON.parameters.materials ) {
  7639. var materialArray = [];
  7640. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7641. var label = matJSON.parameters.materials[ i ];
  7642. materialArray.push( result.materials[ label ] );
  7643. }
  7644. result.materials[ matID ].materials = materialArray;
  7645. }
  7646. }
  7647. // objects ( synchronous init of procedural primitives )
  7648. handle_objects();
  7649. // defaults
  7650. if ( result.cameras && data.defaults.camera ) {
  7651. result.currentCamera = result.cameras[ data.defaults.camera ];
  7652. }
  7653. if ( result.fogs && data.defaults.fog ) {
  7654. result.scene.fog = result.fogs[ data.defaults.fog ];
  7655. }
  7656. // synchronous callback
  7657. scope.callbackSync( result );
  7658. // just in case there are no async elements
  7659. async_callback_gate();
  7660. }
  7661. }
  7662. /**
  7663. * @author mrdoob / http://mrdoob.com/
  7664. */
  7665. THREE.TextureLoader = function ( manager ) {
  7666. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7667. };
  7668. THREE.TextureLoader.prototype = {
  7669. constructor: THREE.TextureLoader,
  7670. load: function ( url, onLoad, onProgress, onError ) {
  7671. var scope = this;
  7672. var loader = new THREE.ImageLoader( scope.manager );
  7673. loader.setCrossOrigin( this.crossOrigin );
  7674. loader.load( url, function ( image ) {
  7675. var texture = new THREE.Texture( image );
  7676. texture.needsUpdate = true;
  7677. if ( onLoad !== undefined ) {
  7678. onLoad( texture );
  7679. }
  7680. } );
  7681. },
  7682. setCrossOrigin: function ( value ) {
  7683. this.crossOrigin = value;
  7684. }
  7685. };
  7686. /**
  7687. * @author mrdoob / http://mrdoob.com/
  7688. * @author alteredq / http://alteredqualia.com/
  7689. */
  7690. THREE.Material = function () {
  7691. this.id = THREE.MaterialIdCount ++;
  7692. this.uuid = THREE.Math.generateUUID();
  7693. this.name = '';
  7694. this.side = THREE.FrontSide;
  7695. this.opacity = 1;
  7696. this.transparent = false;
  7697. this.blending = THREE.NormalBlending;
  7698. this.blendSrc = THREE.SrcAlphaFactor;
  7699. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7700. this.blendEquation = THREE.AddEquation;
  7701. this.depthTest = true;
  7702. this.depthWrite = true;
  7703. this.polygonOffset = false;
  7704. this.polygonOffsetFactor = 0;
  7705. this.polygonOffsetUnits = 0;
  7706. this.alphaTest = 0;
  7707. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7708. this.visible = true;
  7709. this.needsUpdate = true;
  7710. };
  7711. THREE.Material.prototype = {
  7712. constructor: THREE.Material,
  7713. setValues: function ( values ) {
  7714. if ( values === undefined ) return;
  7715. for ( var key in values ) {
  7716. var newValue = values[ key ];
  7717. if ( newValue === undefined ) {
  7718. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7719. continue;
  7720. }
  7721. if ( key in this ) {
  7722. var currentValue = this[ key ];
  7723. if ( currentValue instanceof THREE.Color ) {
  7724. currentValue.set( newValue );
  7725. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7726. currentValue.copy( newValue );
  7727. } else if ( key == 'overdraw') {
  7728. // ensure overdraw is backwards-compatable with legacy boolean type
  7729. this[ key ] = Number(newValue);
  7730. } else {
  7731. this[ key ] = newValue;
  7732. }
  7733. }
  7734. }
  7735. },
  7736. clone: function ( material ) {
  7737. if ( material === undefined ) material = new THREE.Material();
  7738. material.name = this.name;
  7739. material.side = this.side;
  7740. material.opacity = this.opacity;
  7741. material.transparent = this.transparent;
  7742. material.blending = this.blending;
  7743. material.blendSrc = this.blendSrc;
  7744. material.blendDst = this.blendDst;
  7745. material.blendEquation = this.blendEquation;
  7746. material.depthTest = this.depthTest;
  7747. material.depthWrite = this.depthWrite;
  7748. material.polygonOffset = this.polygonOffset;
  7749. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7750. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7751. material.alphaTest = this.alphaTest;
  7752. material.overdraw = this.overdraw;
  7753. material.visible = this.visible;
  7754. return material;
  7755. },
  7756. dispose: function () {
  7757. this.dispatchEvent( { type: 'dispose' } );
  7758. }
  7759. };
  7760. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7761. THREE.MaterialIdCount = 0;
  7762. /**
  7763. * @author mrdoob / http://mrdoob.com/
  7764. * @author alteredq / http://alteredqualia.com/
  7765. *
  7766. * parameters = {
  7767. * color: <hex>,
  7768. * opacity: <float>,
  7769. *
  7770. * blending: THREE.NormalBlending,
  7771. * depthTest: <bool>,
  7772. * depthWrite: <bool>,
  7773. *
  7774. * linewidth: <float>,
  7775. * linecap: "round",
  7776. * linejoin: "round",
  7777. *
  7778. * vertexColors: <bool>
  7779. *
  7780. * fog: <bool>
  7781. * }
  7782. */
  7783. THREE.LineBasicMaterial = function ( parameters ) {
  7784. THREE.Material.call( this );
  7785. this.color = new THREE.Color( 0xffffff );
  7786. this.linewidth = 1;
  7787. this.linecap = 'round';
  7788. this.linejoin = 'round';
  7789. this.vertexColors = false;
  7790. this.fog = true;
  7791. this.setValues( parameters );
  7792. };
  7793. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7794. THREE.LineBasicMaterial.prototype.clone = function () {
  7795. var material = new THREE.LineBasicMaterial();
  7796. THREE.Material.prototype.clone.call( this, material );
  7797. material.color.copy( this.color );
  7798. material.linewidth = this.linewidth;
  7799. material.linecap = this.linecap;
  7800. material.linejoin = this.linejoin;
  7801. material.vertexColors = this.vertexColors;
  7802. material.fog = this.fog;
  7803. return material;
  7804. };
  7805. /**
  7806. * @author alteredq / http://alteredqualia.com/
  7807. *
  7808. * parameters = {
  7809. * color: <hex>,
  7810. * opacity: <float>,
  7811. *
  7812. * blending: THREE.NormalBlending,
  7813. * depthTest: <bool>,
  7814. * depthWrite: <bool>,
  7815. *
  7816. * linewidth: <float>,
  7817. *
  7818. * scale: <float>,
  7819. * dashSize: <float>,
  7820. * gapSize: <float>,
  7821. *
  7822. * vertexColors: <bool>
  7823. *
  7824. * fog: <bool>
  7825. * }
  7826. */
  7827. THREE.LineDashedMaterial = function ( parameters ) {
  7828. THREE.Material.call( this );
  7829. this.color = new THREE.Color( 0xffffff );
  7830. this.linewidth = 1;
  7831. this.scale = 1;
  7832. this.dashSize = 3;
  7833. this.gapSize = 1;
  7834. this.vertexColors = false;
  7835. this.fog = true;
  7836. this.setValues( parameters );
  7837. };
  7838. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7839. THREE.LineDashedMaterial.prototype.clone = function () {
  7840. var material = new THREE.LineDashedMaterial();
  7841. THREE.Material.prototype.clone.call( this, material );
  7842. material.color.copy( this.color );
  7843. material.linewidth = this.linewidth;
  7844. material.scale = this.scale;
  7845. material.dashSize = this.dashSize;
  7846. material.gapSize = this.gapSize;
  7847. material.vertexColors = this.vertexColors;
  7848. material.fog = this.fog;
  7849. return material;
  7850. };
  7851. /**
  7852. * @author mrdoob / http://mrdoob.com/
  7853. * @author alteredq / http://alteredqualia.com/
  7854. *
  7855. * parameters = {
  7856. * color: <hex>,
  7857. * opacity: <float>,
  7858. * map: new THREE.Texture( <Image> ),
  7859. *
  7860. * lightMap: new THREE.Texture( <Image> ),
  7861. *
  7862. * specularMap: new THREE.Texture( <Image> ),
  7863. *
  7864. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7865. * combine: THREE.Multiply,
  7866. * reflectivity: <float>,
  7867. * refractionRatio: <float>,
  7868. *
  7869. * shading: THREE.SmoothShading,
  7870. * blending: THREE.NormalBlending,
  7871. * depthTest: <bool>,
  7872. * depthWrite: <bool>,
  7873. *
  7874. * wireframe: <boolean>,
  7875. * wireframeLinewidth: <float>,
  7876. *
  7877. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7878. *
  7879. * skinning: <bool>,
  7880. * morphTargets: <bool>,
  7881. *
  7882. * fog: <bool>
  7883. * }
  7884. */
  7885. THREE.MeshBasicMaterial = function ( parameters ) {
  7886. THREE.Material.call( this );
  7887. this.color = new THREE.Color( 0xffffff ); // emissive
  7888. this.map = null;
  7889. this.lightMap = null;
  7890. this.specularMap = null;
  7891. this.envMap = null;
  7892. this.combine = THREE.MultiplyOperation;
  7893. this.reflectivity = 1;
  7894. this.refractionRatio = 0.98;
  7895. this.fog = true;
  7896. this.shading = THREE.SmoothShading;
  7897. this.wireframe = false;
  7898. this.wireframeLinewidth = 1;
  7899. this.wireframeLinecap = 'round';
  7900. this.wireframeLinejoin = 'round';
  7901. this.vertexColors = THREE.NoColors;
  7902. this.skinning = false;
  7903. this.morphTargets = false;
  7904. this.setValues( parameters );
  7905. };
  7906. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7907. THREE.MeshBasicMaterial.prototype.clone = function () {
  7908. var material = new THREE.MeshBasicMaterial();
  7909. THREE.Material.prototype.clone.call( this, material );
  7910. material.color.copy( this.color );
  7911. material.map = this.map;
  7912. material.lightMap = this.lightMap;
  7913. material.specularMap = this.specularMap;
  7914. material.envMap = this.envMap;
  7915. material.combine = this.combine;
  7916. material.reflectivity = this.reflectivity;
  7917. material.refractionRatio = this.refractionRatio;
  7918. material.fog = this.fog;
  7919. material.shading = this.shading;
  7920. material.wireframe = this.wireframe;
  7921. material.wireframeLinewidth = this.wireframeLinewidth;
  7922. material.wireframeLinecap = this.wireframeLinecap;
  7923. material.wireframeLinejoin = this.wireframeLinejoin;
  7924. material.vertexColors = this.vertexColors;
  7925. material.skinning = this.skinning;
  7926. material.morphTargets = this.morphTargets;
  7927. return material;
  7928. };
  7929. /**
  7930. * @author mrdoob / http://mrdoob.com/
  7931. * @author alteredq / http://alteredqualia.com/
  7932. *
  7933. * parameters = {
  7934. * color: <hex>,
  7935. * ambient: <hex>,
  7936. * emissive: <hex>,
  7937. * opacity: <float>,
  7938. *
  7939. * map: new THREE.Texture( <Image> ),
  7940. *
  7941. * lightMap: new THREE.Texture( <Image> ),
  7942. *
  7943. * specularMap: new THREE.Texture( <Image> ),
  7944. *
  7945. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7946. * combine: THREE.Multiply,
  7947. * reflectivity: <float>,
  7948. * refractionRatio: <float>,
  7949. *
  7950. * shading: THREE.SmoothShading,
  7951. * blending: THREE.NormalBlending,
  7952. * depthTest: <bool>,
  7953. * depthWrite: <bool>,
  7954. *
  7955. * wireframe: <boolean>,
  7956. * wireframeLinewidth: <float>,
  7957. *
  7958. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7959. *
  7960. * skinning: <bool>,
  7961. * morphTargets: <bool>,
  7962. * morphNormals: <bool>,
  7963. *
  7964. * fog: <bool>
  7965. * }
  7966. */
  7967. THREE.MeshLambertMaterial = function ( parameters ) {
  7968. THREE.Material.call( this );
  7969. this.color = new THREE.Color( 0xffffff ); // diffuse
  7970. this.ambient = new THREE.Color( 0xffffff );
  7971. this.emissive = new THREE.Color( 0x000000 );
  7972. this.wrapAround = false;
  7973. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7974. this.map = null;
  7975. this.lightMap = null;
  7976. this.specularMap = null;
  7977. this.envMap = null;
  7978. this.combine = THREE.MultiplyOperation;
  7979. this.reflectivity = 1;
  7980. this.refractionRatio = 0.98;
  7981. this.fog = true;
  7982. this.shading = THREE.SmoothShading;
  7983. this.wireframe = false;
  7984. this.wireframeLinewidth = 1;
  7985. this.wireframeLinecap = 'round';
  7986. this.wireframeLinejoin = 'round';
  7987. this.vertexColors = THREE.NoColors;
  7988. this.skinning = false;
  7989. this.morphTargets = false;
  7990. this.morphNormals = false;
  7991. this.setValues( parameters );
  7992. };
  7993. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7994. THREE.MeshLambertMaterial.prototype.clone = function () {
  7995. var material = new THREE.MeshLambertMaterial();
  7996. THREE.Material.prototype.clone.call( this, material );
  7997. material.color.copy( this.color );
  7998. material.ambient.copy( this.ambient );
  7999. material.emissive.copy( this.emissive );
  8000. material.wrapAround = this.wrapAround;
  8001. material.wrapRGB.copy( this.wrapRGB );
  8002. material.map = this.map;
  8003. material.lightMap = this.lightMap;
  8004. material.specularMap = this.specularMap;
  8005. material.envMap = this.envMap;
  8006. material.combine = this.combine;
  8007. material.reflectivity = this.reflectivity;
  8008. material.refractionRatio = this.refractionRatio;
  8009. material.fog = this.fog;
  8010. material.shading = this.shading;
  8011. material.wireframe = this.wireframe;
  8012. material.wireframeLinewidth = this.wireframeLinewidth;
  8013. material.wireframeLinecap = this.wireframeLinecap;
  8014. material.wireframeLinejoin = this.wireframeLinejoin;
  8015. material.vertexColors = this.vertexColors;
  8016. material.skinning = this.skinning;
  8017. material.morphTargets = this.morphTargets;
  8018. material.morphNormals = this.morphNormals;
  8019. return material;
  8020. };
  8021. /**
  8022. * @author mrdoob / http://mrdoob.com/
  8023. * @author alteredq / http://alteredqualia.com/
  8024. *
  8025. * parameters = {
  8026. * color: <hex>,
  8027. * ambient: <hex>,
  8028. * emissive: <hex>,
  8029. * specular: <hex>,
  8030. * shininess: <float>,
  8031. * opacity: <float>,
  8032. *
  8033. * map: new THREE.Texture( <Image> ),
  8034. *
  8035. * lightMap: new THREE.Texture( <Image> ),
  8036. *
  8037. * bumpMap: new THREE.Texture( <Image> ),
  8038. * bumpScale: <float>,
  8039. *
  8040. * normalMap: new THREE.Texture( <Image> ),
  8041. * normalScale: <Vector2>,
  8042. *
  8043. * specularMap: new THREE.Texture( <Image> ),
  8044. *
  8045. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8046. * combine: THREE.Multiply,
  8047. * reflectivity: <float>,
  8048. * refractionRatio: <float>,
  8049. *
  8050. * shading: THREE.SmoothShading,
  8051. * blending: THREE.NormalBlending,
  8052. * depthTest: <bool>,
  8053. * depthWrite: <bool>,
  8054. *
  8055. * wireframe: <boolean>,
  8056. * wireframeLinewidth: <float>,
  8057. *
  8058. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8059. *
  8060. * skinning: <bool>,
  8061. * morphTargets: <bool>,
  8062. * morphNormals: <bool>,
  8063. *
  8064. * fog: <bool>
  8065. * }
  8066. */
  8067. THREE.MeshPhongMaterial = function ( parameters ) {
  8068. THREE.Material.call( this );
  8069. this.color = new THREE.Color( 0xffffff ); // diffuse
  8070. this.ambient = new THREE.Color( 0xffffff );
  8071. this.emissive = new THREE.Color( 0x000000 );
  8072. this.specular = new THREE.Color( 0x111111 );
  8073. this.shininess = 30;
  8074. this.metal = false;
  8075. this.perPixel = true;
  8076. this.wrapAround = false;
  8077. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8078. this.map = null;
  8079. this.lightMap = null;
  8080. this.bumpMap = null;
  8081. this.bumpScale = 1;
  8082. this.normalMap = null;
  8083. this.normalScale = new THREE.Vector2( 1, 1 );
  8084. this.specularMap = null;
  8085. this.envMap = null;
  8086. this.combine = THREE.MultiplyOperation;
  8087. this.reflectivity = 1;
  8088. this.refractionRatio = 0.98;
  8089. this.fog = true;
  8090. this.shading = THREE.SmoothShading;
  8091. this.wireframe = false;
  8092. this.wireframeLinewidth = 1;
  8093. this.wireframeLinecap = 'round';
  8094. this.wireframeLinejoin = 'round';
  8095. this.vertexColors = THREE.NoColors;
  8096. this.skinning = false;
  8097. this.morphTargets = false;
  8098. this.morphNormals = false;
  8099. this.setValues( parameters );
  8100. };
  8101. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8102. THREE.MeshPhongMaterial.prototype.clone = function () {
  8103. var material = new THREE.MeshPhongMaterial();
  8104. THREE.Material.prototype.clone.call( this, material );
  8105. material.color.copy( this.color );
  8106. material.ambient.copy( this.ambient );
  8107. material.emissive.copy( this.emissive );
  8108. material.specular.copy( this.specular );
  8109. material.shininess = this.shininess;
  8110. material.metal = this.metal;
  8111. material.perPixel = this.perPixel;
  8112. material.wrapAround = this.wrapAround;
  8113. material.wrapRGB.copy( this.wrapRGB );
  8114. material.map = this.map;
  8115. material.lightMap = this.lightMap;
  8116. material.bumpMap = this.bumpMap;
  8117. material.bumpScale = this.bumpScale;
  8118. material.normalMap = this.normalMap;
  8119. material.normalScale.copy( this.normalScale );
  8120. material.specularMap = this.specularMap;
  8121. material.envMap = this.envMap;
  8122. material.combine = this.combine;
  8123. material.reflectivity = this.reflectivity;
  8124. material.refractionRatio = this.refractionRatio;
  8125. material.fog = this.fog;
  8126. material.shading = this.shading;
  8127. material.wireframe = this.wireframe;
  8128. material.wireframeLinewidth = this.wireframeLinewidth;
  8129. material.wireframeLinecap = this.wireframeLinecap;
  8130. material.wireframeLinejoin = this.wireframeLinejoin;
  8131. material.vertexColors = this.vertexColors;
  8132. material.skinning = this.skinning;
  8133. material.morphTargets = this.morphTargets;
  8134. material.morphNormals = this.morphNormals;
  8135. return material;
  8136. };
  8137. /**
  8138. * @author mrdoob / http://mrdoob.com/
  8139. * @author alteredq / http://alteredqualia.com/
  8140. *
  8141. * parameters = {
  8142. * opacity: <float>,
  8143. *
  8144. * blending: THREE.NormalBlending,
  8145. * depthTest: <bool>,
  8146. * depthWrite: <bool>,
  8147. *
  8148. * wireframe: <boolean>,
  8149. * wireframeLinewidth: <float>
  8150. * }
  8151. */
  8152. THREE.MeshDepthMaterial = function ( parameters ) {
  8153. THREE.Material.call( this );
  8154. this.wireframe = false;
  8155. this.wireframeLinewidth = 1;
  8156. this.setValues( parameters );
  8157. };
  8158. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8159. THREE.MeshDepthMaterial.prototype.clone = function () {
  8160. var material = new THREE.MeshDepthMaterial();
  8161. THREE.Material.prototype.clone.call( this, material );
  8162. material.wireframe = this.wireframe;
  8163. material.wireframeLinewidth = this.wireframeLinewidth;
  8164. return material;
  8165. };
  8166. /**
  8167. * @author mrdoob / http://mrdoob.com/
  8168. *
  8169. * parameters = {
  8170. * opacity: <float>,
  8171. *
  8172. * shading: THREE.FlatShading,
  8173. * blending: THREE.NormalBlending,
  8174. * depthTest: <bool>,
  8175. * depthWrite: <bool>,
  8176. *
  8177. * wireframe: <boolean>,
  8178. * wireframeLinewidth: <float>
  8179. * }
  8180. */
  8181. THREE.MeshNormalMaterial = function ( parameters ) {
  8182. THREE.Material.call( this, parameters );
  8183. this.shading = THREE.FlatShading;
  8184. this.wireframe = false;
  8185. this.wireframeLinewidth = 1;
  8186. this.morphTargets = false;
  8187. this.setValues( parameters );
  8188. };
  8189. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8190. THREE.MeshNormalMaterial.prototype.clone = function () {
  8191. var material = new THREE.MeshNormalMaterial();
  8192. THREE.Material.prototype.clone.call( this, material );
  8193. material.shading = this.shading;
  8194. material.wireframe = this.wireframe;
  8195. material.wireframeLinewidth = this.wireframeLinewidth;
  8196. return material;
  8197. };
  8198. /**
  8199. * @author mrdoob / http://mrdoob.com/
  8200. */
  8201. THREE.MeshFaceMaterial = function ( materials ) {
  8202. this.materials = materials instanceof Array ? materials : [];
  8203. };
  8204. THREE.MeshFaceMaterial.prototype.clone = function () {
  8205. var material = new THREE.MeshFaceMaterial();
  8206. for ( var i = 0; i < this.materials.length; i ++ ) {
  8207. material.materials.push( this.materials[ i ].clone() );
  8208. }
  8209. return material;
  8210. };
  8211. /**
  8212. * @author mrdoob / http://mrdoob.com/
  8213. * @author alteredq / http://alteredqualia.com/
  8214. *
  8215. * parameters = {
  8216. * color: <hex>,
  8217. * opacity: <float>,
  8218. * map: new THREE.Texture( <Image> ),
  8219. *
  8220. * size: <float>,
  8221. *
  8222. * blending: THREE.NormalBlending,
  8223. * depthTest: <bool>,
  8224. * depthWrite: <bool>,
  8225. *
  8226. * vertexColors: <bool>,
  8227. *
  8228. * fog: <bool>
  8229. * }
  8230. */
  8231. THREE.ParticleSystemMaterial = function ( parameters ) {
  8232. THREE.Material.call( this );
  8233. this.color = new THREE.Color( 0xffffff );
  8234. this.map = null;
  8235. this.size = 1;
  8236. this.sizeAttenuation = true;
  8237. this.vertexColors = false;
  8238. this.fog = true;
  8239. this.setValues( parameters );
  8240. };
  8241. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8242. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8243. var material = new THREE.ParticleSystemMaterial();
  8244. THREE.Material.prototype.clone.call( this, material );
  8245. material.color.copy( this.color );
  8246. material.map = this.map;
  8247. material.size = this.size;
  8248. material.sizeAttenuation = this.sizeAttenuation;
  8249. material.vertexColors = this.vertexColors;
  8250. material.fog = this.fog;
  8251. return material;
  8252. };
  8253. // backwards compatibility
  8254. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8255. /**
  8256. * @author alteredq / http://alteredqualia.com/
  8257. *
  8258. * parameters = {
  8259. * fragmentShader: <string>,
  8260. * vertexShader: <string>,
  8261. *
  8262. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8263. *
  8264. * defines: { "label" : "value" },
  8265. *
  8266. * shading: THREE.SmoothShading,
  8267. * blending: THREE.NormalBlending,
  8268. * depthTest: <bool>,
  8269. * depthWrite: <bool>,
  8270. *
  8271. * wireframe: <boolean>,
  8272. * wireframeLinewidth: <float>,
  8273. *
  8274. * lights: <bool>,
  8275. *
  8276. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8277. *
  8278. * skinning: <bool>,
  8279. * morphTargets: <bool>,
  8280. * morphNormals: <bool>,
  8281. *
  8282. * fog: <bool>
  8283. * }
  8284. */
  8285. THREE.ShaderMaterial = function ( parameters ) {
  8286. THREE.Material.call( this );
  8287. this.fragmentShader = "void main() {}";
  8288. this.vertexShader = "void main() {}";
  8289. this.uniforms = {};
  8290. this.defines = {};
  8291. this.attributes = null;
  8292. this.shading = THREE.SmoothShading;
  8293. this.linewidth = 1;
  8294. this.wireframe = false;
  8295. this.wireframeLinewidth = 1;
  8296. this.fog = false; // set to use scene fog
  8297. this.lights = false; // set to use scene lights
  8298. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8299. this.skinning = false; // set to use skinning attribute streams
  8300. this.morphTargets = false; // set to use morph targets
  8301. this.morphNormals = false; // set to use morph normals
  8302. // When rendered geometry doesn't include these attributes but the material does,
  8303. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8304. this.defaultAttributeValues = {
  8305. "color" : [ 1, 1, 1],
  8306. "uv" : [ 0, 0 ],
  8307. "uv2" : [ 0, 0 ]
  8308. };
  8309. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8310. // should always be used to avoid potentially expensive emulation.
  8311. this.index0AttributeName = "position";
  8312. this.setValues( parameters );
  8313. };
  8314. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8315. THREE.ShaderMaterial.prototype.clone = function () {
  8316. var material = new THREE.ShaderMaterial();
  8317. THREE.Material.prototype.clone.call( this, material );
  8318. material.fragmentShader = this.fragmentShader;
  8319. material.vertexShader = this.vertexShader;
  8320. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8321. material.attributes = this.attributes;
  8322. material.defines = this.defines;
  8323. material.shading = this.shading;
  8324. material.wireframe = this.wireframe;
  8325. material.wireframeLinewidth = this.wireframeLinewidth;
  8326. material.fog = this.fog;
  8327. material.lights = this.lights;
  8328. material.vertexColors = this.vertexColors;
  8329. material.skinning = this.skinning;
  8330. material.morphTargets = this.morphTargets;
  8331. material.morphNormals = this.morphNormals;
  8332. return material;
  8333. };
  8334. /**
  8335. * @author alteredq / http://alteredqualia.com/
  8336. *
  8337. * parameters = {
  8338. * color: <hex>,
  8339. * opacity: <float>,
  8340. * map: new THREE.Texture( <Image> ),
  8341. *
  8342. * blending: THREE.NormalBlending,
  8343. * depthTest: <bool>,
  8344. * depthWrite: <bool>,
  8345. *
  8346. * uvOffset: new THREE.Vector2(),
  8347. * uvScale: new THREE.Vector2(),
  8348. *
  8349. * fog: <bool>
  8350. * }
  8351. */
  8352. THREE.SpriteMaterial = function ( parameters ) {
  8353. THREE.Material.call( this );
  8354. // defaults
  8355. this.color = new THREE.Color( 0xffffff );
  8356. this.map = new THREE.Texture();
  8357. this.depthTest = true;
  8358. this.sizeAttenuation = true;
  8359. this.rotation = 0;
  8360. this.fog = false;
  8361. this.uvOffset = new THREE.Vector2( 0, 0 );
  8362. this.uvScale = new THREE.Vector2( 1, 1 );
  8363. // set parameters
  8364. this.setValues( parameters );
  8365. };
  8366. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8367. THREE.SpriteMaterial.prototype.clone = function () {
  8368. var material = new THREE.SpriteMaterial();
  8369. THREE.Material.prototype.clone.call( this, material );
  8370. material.color.copy( this.color );
  8371. material.map = this.map;
  8372. material.rotation = this.rotation;
  8373. material.uvOffset.copy( this.uvOffset );
  8374. material.uvScale.copy( this.uvScale );
  8375. material.fog = this.fog;
  8376. return material;
  8377. };
  8378. /**
  8379. * @author mrdoob / http://mrdoob.com/
  8380. *
  8381. * parameters = {
  8382. * color: <hex>,
  8383. * program: <function>,
  8384. * opacity: <float>,
  8385. * blending: THREE.NormalBlending
  8386. * }
  8387. */
  8388. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8389. THREE.Material.call( this );
  8390. this.color = new THREE.Color( 0xffffff );
  8391. this.program = function ( context, color ) {};
  8392. this.setValues( parameters );
  8393. };
  8394. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8395. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8396. var material = new THREE.SpriteCanvasMaterial();
  8397. THREE.Material.prototype.clone.call( this, material );
  8398. material.color.copy( this.color );
  8399. material.program = this.program;
  8400. return material;
  8401. };
  8402. // backwards compatibility
  8403. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8404. /**
  8405. * @author mrdoob / http://mrdoob.com/
  8406. * @author alteredq / http://alteredqualia.com/
  8407. * @author szimek / https://github.com/szimek/
  8408. */
  8409. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8410. this.id = THREE.TextureIdCount ++;
  8411. this.uuid = THREE.Math.generateUUID();
  8412. this.name = '';
  8413. this.image = image;
  8414. this.mipmaps = [];
  8415. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8416. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8417. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8418. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8419. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8420. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8421. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8422. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8423. this.offset = new THREE.Vector2( 0, 0 );
  8424. this.repeat = new THREE.Vector2( 1, 1 );
  8425. this.generateMipmaps = true;
  8426. this.premultiplyAlpha = false;
  8427. this.flipY = true;
  8428. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8429. this.needsUpdate = false;
  8430. this.onUpdate = null;
  8431. };
  8432. THREE.Texture.prototype = {
  8433. constructor: THREE.Texture,
  8434. clone: function ( texture ) {
  8435. if ( texture === undefined ) texture = new THREE.Texture();
  8436. texture.image = this.image;
  8437. texture.mipmaps = this.mipmaps.slice(0);
  8438. texture.mapping = this.mapping;
  8439. texture.wrapS = this.wrapS;
  8440. texture.wrapT = this.wrapT;
  8441. texture.magFilter = this.magFilter;
  8442. texture.minFilter = this.minFilter;
  8443. texture.anisotropy = this.anisotropy;
  8444. texture.format = this.format;
  8445. texture.type = this.type;
  8446. texture.offset.copy( this.offset );
  8447. texture.repeat.copy( this.repeat );
  8448. texture.generateMipmaps = this.generateMipmaps;
  8449. texture.premultiplyAlpha = this.premultiplyAlpha;
  8450. texture.flipY = this.flipY;
  8451. texture.unpackAlignment = this.unpackAlignment;
  8452. return texture;
  8453. },
  8454. dispose: function () {
  8455. this.dispatchEvent( { type: 'dispose' } );
  8456. }
  8457. };
  8458. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8459. THREE.TextureIdCount = 0;
  8460. /**
  8461. * @author alteredq / http://alteredqualia.com/
  8462. */
  8463. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8464. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8465. this.image = { width: width, height: height };
  8466. this.mipmaps = mipmaps;
  8467. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8468. };
  8469. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8470. THREE.CompressedTexture.prototype.clone = function () {
  8471. var texture = new THREE.CompressedTexture();
  8472. THREE.Texture.prototype.clone.call( this, texture );
  8473. return texture;
  8474. };
  8475. /**
  8476. * @author alteredq / http://alteredqualia.com/
  8477. */
  8478. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8479. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8480. this.image = { data: data, width: width, height: height };
  8481. };
  8482. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8483. THREE.DataTexture.prototype.clone = function () {
  8484. var texture = new THREE.DataTexture();
  8485. THREE.Texture.prototype.clone.call( this, texture );
  8486. return texture;
  8487. };
  8488. /**
  8489. * @author alteredq / http://alteredqualia.com/
  8490. */
  8491. THREE.ParticleSystem = function ( geometry, material ) {
  8492. THREE.Object3D.call( this );
  8493. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8494. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  8495. this.sortParticles = false;
  8496. this.frustumCulled = false;
  8497. };
  8498. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8499. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8500. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8501. object.sortParticles = this.sortParticles;
  8502. THREE.Object3D.prototype.clone.call( this, object );
  8503. return object;
  8504. };
  8505. /**
  8506. * @author mrdoob / http://mrdoob.com/
  8507. */
  8508. THREE.Line = function ( geometry, material, type ) {
  8509. THREE.Object3D.call( this );
  8510. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8511. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8512. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8513. };
  8514. THREE.LineStrip = 0;
  8515. THREE.LinePieces = 1;
  8516. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8517. THREE.Line.prototype.clone = function ( object ) {
  8518. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8519. THREE.Object3D.prototype.clone.call( this, object );
  8520. return object;
  8521. };
  8522. /**
  8523. * @author mrdoob / http://mrdoob.com/
  8524. * @author alteredq / http://alteredqualia.com/
  8525. * @author mikael emtinger / http://gomo.se/
  8526. * @author jonobr1 / http://jonobr1.com/
  8527. */
  8528. THREE.Mesh = function ( geometry, material ) {
  8529. THREE.Object3D.call( this );
  8530. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8531. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8532. this.updateMorphTargets();
  8533. };
  8534. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8535. THREE.Mesh.prototype.updateMorphTargets = function () {
  8536. if ( this.geometry.morphTargets.length > 0 ) {
  8537. this.morphTargetBase = -1;
  8538. this.morphTargetForcedOrder = [];
  8539. this.morphTargetInfluences = [];
  8540. this.morphTargetDictionary = {};
  8541. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8542. this.morphTargetInfluences.push( 0 );
  8543. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8544. }
  8545. }
  8546. };
  8547. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8548. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8549. return this.morphTargetDictionary[ name ];
  8550. }
  8551. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8552. return 0;
  8553. };
  8554. THREE.Mesh.prototype.clone = function ( object ) {
  8555. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8556. THREE.Object3D.prototype.clone.call( this, object );
  8557. return object;
  8558. };
  8559. /**
  8560. * @author mikael emtinger / http://gomo.se/
  8561. * @author alteredq / http://alteredqualia.com/
  8562. */
  8563. THREE.Bone = function( belongsToSkin ) {
  8564. THREE.Object3D.call( this );
  8565. this.skin = belongsToSkin;
  8566. this.skinMatrix = new THREE.Matrix4();
  8567. };
  8568. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8569. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8570. // update local
  8571. if ( this.matrixAutoUpdate ) {
  8572. forceUpdate |= this.updateMatrix();
  8573. }
  8574. // update skin matrix
  8575. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8576. if( parentSkinMatrix ) {
  8577. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8578. } else {
  8579. this.skinMatrix.copy( this.matrix );
  8580. }
  8581. this.matrixWorldNeedsUpdate = false;
  8582. forceUpdate = true;
  8583. }
  8584. // update children
  8585. var child, i, l = this.children.length;
  8586. for ( i = 0; i < l; i ++ ) {
  8587. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8588. }
  8589. };
  8590. /**
  8591. * @author mikael emtinger / http://gomo.se/
  8592. * @author alteredq / http://alteredqualia.com/
  8593. */
  8594. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8595. THREE.Mesh.call( this, geometry, material );
  8596. //
  8597. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8598. // init bones
  8599. this.identityMatrix = new THREE.Matrix4();
  8600. this.bones = [];
  8601. this.boneMatrices = [];
  8602. var b, bone, gbone, p, q, s;
  8603. if ( this.geometry && this.geometry.bones !== undefined ) {
  8604. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8605. gbone = this.geometry.bones[ b ];
  8606. p = gbone.pos;
  8607. q = gbone.rotq;
  8608. s = gbone.scl;
  8609. bone = this.addBone();
  8610. bone.name = gbone.name;
  8611. bone.position.set( p[0], p[1], p[2] );
  8612. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8613. if ( s !== undefined ) {
  8614. bone.scale.set( s[0], s[1], s[2] );
  8615. } else {
  8616. bone.scale.set( 1, 1, 1 );
  8617. }
  8618. }
  8619. for ( b = 0; b < this.bones.length; b ++ ) {
  8620. gbone = this.geometry.bones[ b ];
  8621. bone = this.bones[ b ];
  8622. if ( gbone.parent === -1 ) {
  8623. this.add( bone );
  8624. } else {
  8625. this.bones[ gbone.parent ].add( bone );
  8626. }
  8627. }
  8628. //
  8629. var nBones = this.bones.length;
  8630. if ( this.useVertexTexture ) {
  8631. // layout (1 matrix = 4 pixels)
  8632. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8633. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8634. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8635. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8636. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8637. var size;
  8638. if ( nBones > 256 )
  8639. size = 64;
  8640. else if ( nBones > 64 )
  8641. size = 32;
  8642. else if ( nBones > 16 )
  8643. size = 16;
  8644. else
  8645. size = 8;
  8646. this.boneTextureWidth = size;
  8647. this.boneTextureHeight = size;
  8648. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8649. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8650. this.boneTexture.minFilter = THREE.NearestFilter;
  8651. this.boneTexture.magFilter = THREE.NearestFilter;
  8652. this.boneTexture.generateMipmaps = false;
  8653. this.boneTexture.flipY = false;
  8654. } else {
  8655. this.boneMatrices = new Float32Array( 16 * nBones );
  8656. }
  8657. this.pose();
  8658. }
  8659. };
  8660. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8661. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8662. if ( bone === undefined ) {
  8663. bone = new THREE.Bone( this );
  8664. }
  8665. this.bones.push( bone );
  8666. return bone;
  8667. };
  8668. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8669. var offsetMatrix = new THREE.Matrix4();
  8670. return function ( force ) {
  8671. this.matrixAutoUpdate && this.updateMatrix();
  8672. // update matrixWorld
  8673. if ( this.matrixWorldNeedsUpdate || force ) {
  8674. if ( this.parent ) {
  8675. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8676. } else {
  8677. this.matrixWorld.copy( this.matrix );
  8678. }
  8679. this.matrixWorldNeedsUpdate = false;
  8680. force = true;
  8681. }
  8682. // update children
  8683. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8684. var child = this.children[ i ];
  8685. if ( child instanceof THREE.Bone ) {
  8686. child.update( this.identityMatrix, false );
  8687. } else {
  8688. child.updateMatrixWorld( true );
  8689. }
  8690. }
  8691. // make a snapshot of the bones' rest position
  8692. if ( this.boneInverses == undefined ) {
  8693. this.boneInverses = [];
  8694. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8695. var inverse = new THREE.Matrix4();
  8696. inverse.getInverse( this.bones[ b ].skinMatrix );
  8697. this.boneInverses.push( inverse );
  8698. }
  8699. }
  8700. // flatten bone matrices to array
  8701. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8702. // compute the offset between the current and the original transform;
  8703. // TODO: we could get rid of this multiplication step if the skinMatrix
  8704. // was already representing the offset; however, this requires some
  8705. // major changes to the animation system
  8706. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8707. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8708. }
  8709. if ( this.useVertexTexture ) {
  8710. this.boneTexture.needsUpdate = true;
  8711. }
  8712. };
  8713. }();
  8714. THREE.SkinnedMesh.prototype.pose = function () {
  8715. this.updateMatrixWorld( true );
  8716. this.normalizeSkinWeights();
  8717. };
  8718. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8719. if ( this.geometry instanceof THREE.Geometry ) {
  8720. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8721. var sw = this.geometry.skinWeights[ i ];
  8722. var scale = 1.0 / sw.lengthManhattan();
  8723. if ( scale !== Infinity ) {
  8724. sw.multiplyScalar( scale );
  8725. } else {
  8726. sw.set( 1 ); // this will be normalized by the shader anyway
  8727. }
  8728. }
  8729. } else {
  8730. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8731. }
  8732. };
  8733. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8734. if ( object === undefined ) {
  8735. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8736. }
  8737. THREE.Mesh.prototype.clone.call( this, object );
  8738. return object;
  8739. };
  8740. /**
  8741. * @author alteredq / http://alteredqualia.com/
  8742. */
  8743. THREE.MorphAnimMesh = function ( geometry, material ) {
  8744. THREE.Mesh.call( this, geometry, material );
  8745. // API
  8746. this.duration = 1000; // milliseconds
  8747. this.mirroredLoop = false;
  8748. this.time = 0;
  8749. // internals
  8750. this.lastKeyframe = 0;
  8751. this.currentKeyframe = 0;
  8752. this.direction = 1;
  8753. this.directionBackwards = false;
  8754. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8755. };
  8756. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8757. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8758. this.startKeyframe = start;
  8759. this.endKeyframe = end;
  8760. this.length = this.endKeyframe - this.startKeyframe + 1;
  8761. };
  8762. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8763. this.direction = 1;
  8764. this.directionBackwards = false;
  8765. };
  8766. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8767. this.direction = -1;
  8768. this.directionBackwards = true;
  8769. };
  8770. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8771. var geometry = this.geometry;
  8772. if ( ! geometry.animations ) geometry.animations = {};
  8773. var firstAnimation, animations = geometry.animations;
  8774. var pattern = /([a-z]+)(\d+)/;
  8775. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8776. var morph = geometry.morphTargets[ i ];
  8777. var parts = morph.name.match( pattern );
  8778. if ( parts && parts.length > 1 ) {
  8779. var label = parts[ 1 ];
  8780. var num = parts[ 2 ];
  8781. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8782. var animation = animations[ label ];
  8783. if ( i < animation.start ) animation.start = i;
  8784. if ( i > animation.end ) animation.end = i;
  8785. if ( ! firstAnimation ) firstAnimation = label;
  8786. }
  8787. }
  8788. geometry.firstAnimation = firstAnimation;
  8789. };
  8790. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8791. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8792. this.geometry.animations[ label ] = { start: start, end: end };
  8793. };
  8794. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8795. var animation = this.geometry.animations[ label ];
  8796. if ( animation ) {
  8797. this.setFrameRange( animation.start, animation.end );
  8798. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8799. this.time = 0;
  8800. } else {
  8801. console.warn( "animation[" + label + "] undefined" );
  8802. }
  8803. };
  8804. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8805. var frameTime = this.duration / this.length;
  8806. this.time += this.direction * delta;
  8807. if ( this.mirroredLoop ) {
  8808. if ( this.time > this.duration || this.time < 0 ) {
  8809. this.direction *= -1;
  8810. if ( this.time > this.duration ) {
  8811. this.time = this.duration;
  8812. this.directionBackwards = true;
  8813. }
  8814. if ( this.time < 0 ) {
  8815. this.time = 0;
  8816. this.directionBackwards = false;
  8817. }
  8818. }
  8819. } else {
  8820. this.time = this.time % this.duration;
  8821. if ( this.time < 0 ) this.time += this.duration;
  8822. }
  8823. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8824. if ( keyframe !== this.currentKeyframe ) {
  8825. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8826. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8827. this.morphTargetInfluences[ keyframe ] = 0;
  8828. this.lastKeyframe = this.currentKeyframe;
  8829. this.currentKeyframe = keyframe;
  8830. }
  8831. var mix = ( this.time % frameTime ) / frameTime;
  8832. if ( this.directionBackwards ) {
  8833. mix = 1 - mix;
  8834. }
  8835. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8836. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8837. };
  8838. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8839. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8840. object.duration = this.duration;
  8841. object.mirroredLoop = this.mirroredLoop;
  8842. object.time = this.time;
  8843. object.lastKeyframe = this.lastKeyframe;
  8844. object.currentKeyframe = this.currentKeyframe;
  8845. object.direction = this.direction;
  8846. object.directionBackwards = this.directionBackwards;
  8847. THREE.Mesh.prototype.clone.call( this, object );
  8848. return object;
  8849. };
  8850. /**
  8851. * @author mikael emtinger / http://gomo.se/
  8852. * @author alteredq / http://alteredqualia.com/
  8853. * @author mrdoob / http://mrdoob.com/
  8854. */
  8855. THREE.LOD = function () {
  8856. THREE.Object3D.call( this );
  8857. this.objects = [];
  8858. };
  8859. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8860. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8861. if ( distance === undefined ) distance = 0;
  8862. distance = Math.abs( distance );
  8863. for ( var l = 0; l < this.objects.length; l ++ ) {
  8864. if ( distance < this.objects[ l ].distance ) {
  8865. break;
  8866. }
  8867. }
  8868. this.objects.splice( l, 0, { distance: distance, object: object } );
  8869. this.add( object );
  8870. };
  8871. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8872. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8873. if ( distance < this.objects[ i ].distance ) {
  8874. break;
  8875. }
  8876. }
  8877. return this.objects[ i - 1 ].object;
  8878. };
  8879. THREE.LOD.prototype.update = function () {
  8880. var v1 = new THREE.Vector3();
  8881. var v2 = new THREE.Vector3();
  8882. return function ( camera ) {
  8883. if ( this.objects.length > 1 ) {
  8884. v1.getPositionFromMatrix( camera.matrixWorld );
  8885. v2.getPositionFromMatrix( this.matrixWorld );
  8886. var distance = v1.distanceTo( v2 );
  8887. this.objects[ 0 ].object.visible = true;
  8888. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8889. if ( distance >= this.objects[ i ].distance ) {
  8890. this.objects[ i - 1 ].object.visible = false;
  8891. this.objects[ i ].object.visible = true;
  8892. } else {
  8893. break;
  8894. }
  8895. }
  8896. for( ; i < l; i ++ ) {
  8897. this.objects[ i ].object.visible = false;
  8898. }
  8899. }
  8900. };
  8901. }();
  8902. THREE.LOD.prototype.clone = function () {
  8903. // TODO
  8904. };
  8905. /**
  8906. * @author mikael emtinger / http://gomo.se/
  8907. * @author alteredq / http://alteredqualia.com/
  8908. */
  8909. THREE.Sprite = function ( material ) {
  8910. THREE.Object3D.call( this );
  8911. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8912. };
  8913. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8914. /*
  8915. * Custom update matrix
  8916. */
  8917. THREE.Sprite.prototype.updateMatrix = function () {
  8918. this.matrix.compose( this.position, this.quaternion, this.scale );
  8919. this.matrixWorldNeedsUpdate = true;
  8920. };
  8921. THREE.Sprite.prototype.clone = function ( object ) {
  8922. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8923. THREE.Object3D.prototype.clone.call( this, object );
  8924. return object;
  8925. };
  8926. // Backwards compatibility
  8927. THREE.Particle = THREE.Sprite;
  8928. /**
  8929. * @author mrdoob / http://mrdoob.com/
  8930. */
  8931. THREE.Scene = function () {
  8932. THREE.Object3D.call( this );
  8933. this.fog = null;
  8934. this.overrideMaterial = null;
  8935. this.autoUpdate = true; // checked by the renderer
  8936. this.matrixAutoUpdate = false;
  8937. this.__lights = [];
  8938. this.__objectsAdded = [];
  8939. this.__objectsRemoved = [];
  8940. };
  8941. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8942. THREE.Scene.prototype.__addObject = function ( object ) {
  8943. if ( object instanceof THREE.Light ) {
  8944. if ( this.__lights.indexOf( object ) === - 1 ) {
  8945. this.__lights.push( object );
  8946. }
  8947. if ( object.target && object.target.parent === undefined ) {
  8948. this.add( object.target );
  8949. }
  8950. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8951. this.__objectsAdded.push( object );
  8952. // check if previously removed
  8953. var i = this.__objectsRemoved.indexOf( object );
  8954. if ( i !== -1 ) {
  8955. this.__objectsRemoved.splice( i, 1 );
  8956. }
  8957. }
  8958. for ( var c = 0; c < object.children.length; c ++ ) {
  8959. this.__addObject( object.children[ c ] );
  8960. }
  8961. };
  8962. THREE.Scene.prototype.__removeObject = function ( object ) {
  8963. if ( object instanceof THREE.Light ) {
  8964. var i = this.__lights.indexOf( object );
  8965. if ( i !== -1 ) {
  8966. this.__lights.splice( i, 1 );
  8967. }
  8968. if ( object.shadowCascadeArray ) {
  8969. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  8970. this.__removeObject( object.shadowCascadeArray[ x ] );
  8971. }
  8972. }
  8973. } else if ( !( object instanceof THREE.Camera ) ) {
  8974. this.__objectsRemoved.push( object );
  8975. // check if previously added
  8976. var i = this.__objectsAdded.indexOf( object );
  8977. if ( i !== -1 ) {
  8978. this.__objectsAdded.splice( i, 1 );
  8979. }
  8980. }
  8981. for ( var c = 0; c < object.children.length; c ++ ) {
  8982. this.__removeObject( object.children[ c ] );
  8983. }
  8984. };
  8985. THREE.Scene.prototype.clone = function ( object ) {
  8986. if ( object === undefined ) object = new THREE.Scene();
  8987. THREE.Object3D.prototype.clone.call(this, object);
  8988. if ( this.fog !== null ) object.fog = this.fog.clone();
  8989. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  8990. object.autoUpdate = this.autoUpdate;
  8991. object.matrixAutoUpdate = this.matrixAutoUpdate;
  8992. return object;
  8993. };
  8994. /**
  8995. * @author mrdoob / http://mrdoob.com/
  8996. * @author alteredq / http://alteredqualia.com/
  8997. */
  8998. THREE.Fog = function ( hex, near, far ) {
  8999. this.name = '';
  9000. this.color = new THREE.Color( hex );
  9001. this.near = ( near !== undefined ) ? near : 1;
  9002. this.far = ( far !== undefined ) ? far : 1000;
  9003. };
  9004. THREE.Fog.prototype.clone = function () {
  9005. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9006. };
  9007. /**
  9008. * @author mrdoob / http://mrdoob.com/
  9009. * @author alteredq / http://alteredqualia.com/
  9010. */
  9011. THREE.FogExp2 = function ( hex, density ) {
  9012. this.name = '';
  9013. this.color = new THREE.Color( hex );
  9014. this.density = ( density !== undefined ) ? density : 0.00025;
  9015. };
  9016. THREE.FogExp2.prototype.clone = function () {
  9017. return new THREE.FogExp2( this.color.getHex(), this.density );
  9018. };
  9019. /**
  9020. * @author mrdoob / http://mrdoob.com/
  9021. */
  9022. THREE.CanvasRenderer = function ( parameters ) {
  9023. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9024. var smoothstep = THREE.Math.smoothstep;
  9025. parameters = parameters || {};
  9026. var _this = this,
  9027. _renderData, _elements, _lights,
  9028. _projector = new THREE.Projector(),
  9029. _canvas = parameters.canvas !== undefined
  9030. ? parameters.canvas
  9031. : document.createElement( 'canvas' ),
  9032. _canvasWidth = _canvas.width,
  9033. _canvasHeight = _canvas.height,
  9034. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9035. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9036. _context = _canvas.getContext( '2d' ),
  9037. _clearColor = new THREE.Color( 0x000000 ),
  9038. _clearAlpha = 0,
  9039. _contextGlobalAlpha = 1,
  9040. _contextGlobalCompositeOperation = 0,
  9041. _contextStrokeStyle = null,
  9042. _contextFillStyle = null,
  9043. _contextLineWidth = null,
  9044. _contextLineCap = null,
  9045. _contextLineJoin = null,
  9046. _contextDashSize = null,
  9047. _contextGapSize = 0,
  9048. _camera,
  9049. _v1, _v2, _v3, _v4,
  9050. _v5 = new THREE.RenderableVertex(),
  9051. _v6 = new THREE.RenderableVertex(),
  9052. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9053. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9054. _color = new THREE.Color(),
  9055. _color1 = new THREE.Color(),
  9056. _color2 = new THREE.Color(),
  9057. _color3 = new THREE.Color(),
  9058. _color4 = new THREE.Color(),
  9059. _diffuseColor = new THREE.Color(),
  9060. _emissiveColor = new THREE.Color(),
  9061. _lightColor = new THREE.Color(),
  9062. _patterns = {}, _imagedatas = {},
  9063. _near, _far,
  9064. _image, _uvs,
  9065. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9066. _clipBox = new THREE.Box2(),
  9067. _clearBox = new THREE.Box2(),
  9068. _elemBox = new THREE.Box2(),
  9069. _ambientLight = new THREE.Color(),
  9070. _directionalLights = new THREE.Color(),
  9071. _pointLights = new THREE.Color(),
  9072. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9073. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  9074. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  9075. _pixelMap = document.createElement( 'canvas' );
  9076. _pixelMap.width = _pixelMap.height = 2;
  9077. _pixelMapContext = _pixelMap.getContext( '2d' );
  9078. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  9079. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  9080. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  9081. _pixelMapData = _pixelMapImage.data;
  9082. _gradientMap = document.createElement( 'canvas' );
  9083. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  9084. _gradientMapContext = _gradientMap.getContext( '2d' );
  9085. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  9086. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  9087. _gradientMapQuality --; // Fix UVs
  9088. // dash+gap fallbacks for Firefox and everything else
  9089. if ( _context.setLineDash === undefined ) {
  9090. if ( _context.mozDash !== undefined ) {
  9091. _context.setLineDash = function ( values ) {
  9092. _context.mozDash = values[ 0 ] !== null ? values : null;
  9093. }
  9094. } else {
  9095. _context.setLineDash = function () {}
  9096. }
  9097. }
  9098. this.domElement = _canvas;
  9099. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9100. ? parameters.devicePixelRatio
  9101. : self.devicePixelRatio !== undefined
  9102. ? self.devicePixelRatio
  9103. : 1;
  9104. this.autoClear = true;
  9105. this.sortObjects = true;
  9106. this.sortElements = true;
  9107. this.info = {
  9108. render: {
  9109. vertices: 0,
  9110. faces: 0
  9111. }
  9112. }
  9113. // WebGLRenderer compatibility
  9114. this.supportsVertexTextures = function () {};
  9115. this.setFaceCulling = function () {};
  9116. this.setSize = function ( width, height, updateStyle ) {
  9117. _canvasWidth = width * this.devicePixelRatio;
  9118. _canvasHeight = height * this.devicePixelRatio;
  9119. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9120. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9121. _canvas.width = _canvasWidth;
  9122. _canvas.height = _canvasHeight;
  9123. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9124. _canvas.style.width = width + 'px';
  9125. _canvas.style.height = height + 'px';
  9126. }
  9127. _clipBox.set(
  9128. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9129. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9130. );
  9131. _clearBox.set(
  9132. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9133. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9134. );
  9135. _contextGlobalAlpha = 1;
  9136. _contextGlobalCompositeOperation = 0;
  9137. _contextStrokeStyle = null;
  9138. _contextFillStyle = null;
  9139. _contextLineWidth = null;
  9140. _contextLineCap = null;
  9141. _contextLineJoin = null;
  9142. };
  9143. this.setClearColor = function ( color, alpha ) {
  9144. _clearColor.set( color );
  9145. _clearAlpha = alpha !== undefined ? alpha : 1;
  9146. _clearBox.set(
  9147. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9148. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9149. );
  9150. };
  9151. this.setClearColorHex = function ( hex, alpha ) {
  9152. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9153. this.setClearColor( hex, alpha );
  9154. };
  9155. this.getMaxAnisotropy = function () {
  9156. return 0;
  9157. };
  9158. this.clear = function () {
  9159. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9160. if ( _clearBox.empty() === false ) {
  9161. _clearBox.intersect( _clipBox );
  9162. _clearBox.expandByScalar( 2 );
  9163. if ( _clearAlpha < 1 ) {
  9164. _context.clearRect(
  9165. _clearBox.min.x | 0,
  9166. _clearBox.min.y | 0,
  9167. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9168. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9169. );
  9170. }
  9171. if ( _clearAlpha > 0 ) {
  9172. setBlending( THREE.NormalBlending );
  9173. setOpacity( 1 );
  9174. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9175. _context.fillRect(
  9176. _clearBox.min.x | 0,
  9177. _clearBox.min.y | 0,
  9178. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9179. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9180. );
  9181. }
  9182. _clearBox.makeEmpty();
  9183. }
  9184. };
  9185. this.render = function ( scene, camera ) {
  9186. if ( camera instanceof THREE.Camera === false ) {
  9187. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9188. return;
  9189. }
  9190. if ( this.autoClear === true ) this.clear();
  9191. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9192. _this.info.render.vertices = 0;
  9193. _this.info.render.faces = 0;
  9194. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9195. _elements = _renderData.elements;
  9196. _lights = _renderData.lights;
  9197. _camera = camera;
  9198. /* DEBUG
  9199. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9200. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9201. */
  9202. calculateLights();
  9203. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  9204. var element = _elements[ e ];
  9205. var material = element.material;
  9206. if ( material === undefined || material.visible === false ) continue;
  9207. _elemBox.makeEmpty();
  9208. if ( element instanceof THREE.RenderableSprite ) {
  9209. _v1 = element;
  9210. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9211. renderSprite( _v1, element, material );
  9212. } else if ( element instanceof THREE.RenderableLine ) {
  9213. _v1 = element.v1; _v2 = element.v2;
  9214. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9215. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9216. _elemBox.setFromPoints( [
  9217. _v1.positionScreen,
  9218. _v2.positionScreen
  9219. ] );
  9220. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9221. renderLine( _v1, _v2, element, material );
  9222. }
  9223. } else if ( element instanceof THREE.RenderableFace3 ) {
  9224. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9225. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9226. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9227. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9228. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9229. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9230. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9231. if ( material.overdraw > 0 ) {
  9232. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9233. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9234. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9235. }
  9236. _elemBox.setFromPoints( [
  9237. _v1.positionScreen,
  9238. _v2.positionScreen,
  9239. _v3.positionScreen
  9240. ] );
  9241. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9242. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9243. }
  9244. }
  9245. /* DEBUG
  9246. setLineWidth( 1 );
  9247. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9248. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9249. */
  9250. _clearBox.union( _elemBox );
  9251. }
  9252. /* DEBUG
  9253. setLineWidth( 1 );
  9254. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9255. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9256. */
  9257. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9258. };
  9259. //
  9260. function calculateLights() {
  9261. _ambientLight.setRGB( 0, 0, 0 );
  9262. _directionalLights.setRGB( 0, 0, 0 );
  9263. _pointLights.setRGB( 0, 0, 0 );
  9264. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9265. var light = _lights[ l ];
  9266. var lightColor = light.color;
  9267. if ( light instanceof THREE.AmbientLight ) {
  9268. _ambientLight.add( lightColor );
  9269. } else if ( light instanceof THREE.DirectionalLight ) {
  9270. // for sprites
  9271. _directionalLights.add( lightColor );
  9272. } else if ( light instanceof THREE.PointLight ) {
  9273. // for sprites
  9274. _pointLights.add( lightColor );
  9275. }
  9276. }
  9277. }
  9278. function calculateLight( position, normal, color ) {
  9279. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9280. var light = _lights[ l ];
  9281. _lightColor.copy( light.color );
  9282. if ( light instanceof THREE.DirectionalLight ) {
  9283. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  9284. var amount = normal.dot( lightPosition );
  9285. if ( amount <= 0 ) continue;
  9286. amount *= light.intensity;
  9287. color.add( _lightColor.multiplyScalar( amount ) );
  9288. } else if ( light instanceof THREE.PointLight ) {
  9289. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  9290. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9291. if ( amount <= 0 ) continue;
  9292. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9293. if ( amount == 0 ) continue;
  9294. amount *= light.intensity;
  9295. color.add( _lightColor.multiplyScalar( amount ) );
  9296. }
  9297. }
  9298. }
  9299. function renderSprite( v1, element, material ) {
  9300. setOpacity( material.opacity );
  9301. setBlending( material.blending );
  9302. var scaleX = element.scale.x * _canvasWidthHalf;
  9303. var scaleY = element.scale.y * _canvasHeightHalf;
  9304. _elemBox.min.set( v1.x - ( scaleX * 0.5 ), v1.y - ( scaleY * 0.5 ) );
  9305. _elemBox.max.set( v1.x + ( scaleX * 0.5 ), v1.y + ( scaleY * 0.5 ) );
  9306. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9307. _elemBox.makeEmpty();
  9308. return;
  9309. }
  9310. if ( material instanceof THREE.SpriteMaterial ||
  9311. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  9312. if ( material.map.image !== undefined ) {
  9313. var bitmap = material.map.image;
  9314. _context.save();
  9315. _context.translate( v1.x, v1.y );
  9316. _context.rotate( - material.rotation );
  9317. _context.scale( scaleX, - scaleY );
  9318. _context.drawImage( bitmap, 0, 0, bitmap.width, bitmap.height, - 0.5, - 0.5, 1, 1 );
  9319. _context.restore();
  9320. } else {
  9321. setFillStyle( material.color.getStyle() );
  9322. _context.save();
  9323. _context.translate( v1.x, v1.y );
  9324. _context.rotate( - element.rotation );
  9325. _context.scale( scaleX, scaleY );
  9326. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9327. _context.restore();
  9328. }
  9329. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9330. setStrokeStyle( material.color.getStyle() );
  9331. setFillStyle( material.color.getStyle() );
  9332. _context.save();
  9333. _context.translate( v1.x, v1.y );
  9334. _context.rotate( - element.rotation );
  9335. _context.scale( scaleX, scaleY );
  9336. material.program( _context );
  9337. _context.restore();
  9338. }
  9339. /* DEBUG
  9340. setStrokeStyle( 'rgb(255,255,0)' );
  9341. _context.beginPath();
  9342. _context.moveTo( v1.x - 10, v1.y );
  9343. _context.lineTo( v1.x + 10, v1.y );
  9344. _context.moveTo( v1.x, v1.y - 10 );
  9345. _context.lineTo( v1.x, v1.y + 10 );
  9346. _context.stroke();
  9347. */
  9348. }
  9349. function renderLine( v1, v2, element, material ) {
  9350. setOpacity( material.opacity );
  9351. setBlending( material.blending );
  9352. _context.beginPath();
  9353. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9354. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9355. if ( material instanceof THREE.LineBasicMaterial ) {
  9356. setLineWidth( material.linewidth );
  9357. setLineCap( material.linecap );
  9358. setLineJoin( material.linejoin );
  9359. if ( material.vertexColors !== THREE.VertexColors ) {
  9360. setStrokeStyle( material.color.getStyle() );
  9361. } else {
  9362. var colorStyle1 = element.vertexColors[0].getStyle();
  9363. var colorStyle2 = element.vertexColors[1].getStyle();
  9364. if ( colorStyle1 === colorStyle2 ) {
  9365. setStrokeStyle( colorStyle1 );
  9366. } else {
  9367. try {
  9368. var grad = _context.createLinearGradient(
  9369. v1.positionScreen.x,
  9370. v1.positionScreen.y,
  9371. v2.positionScreen.x,
  9372. v2.positionScreen.y
  9373. );
  9374. grad.addColorStop( 0, colorStyle1 );
  9375. grad.addColorStop( 1, colorStyle2 );
  9376. } catch ( exception ) {
  9377. grad = colorStyle1;
  9378. }
  9379. setStrokeStyle( grad );
  9380. }
  9381. }
  9382. _context.stroke();
  9383. _elemBox.expandByScalar( material.linewidth * 2 );
  9384. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9385. setLineWidth( material.linewidth );
  9386. setLineCap( material.linecap );
  9387. setLineJoin( material.linejoin );
  9388. setStrokeStyle( material.color.getStyle() );
  9389. setDashAndGap( material.dashSize, material.gapSize );
  9390. _context.stroke();
  9391. _elemBox.expandByScalar( material.linewidth * 2 );
  9392. setDashAndGap( null, null );
  9393. }
  9394. }
  9395. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9396. _this.info.render.vertices += 3;
  9397. _this.info.render.faces ++;
  9398. setOpacity( material.opacity );
  9399. setBlending( material.blending );
  9400. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9401. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9402. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9403. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9404. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9405. _diffuseColor.copy( material.color );
  9406. _emissiveColor.copy( material.emissive );
  9407. if ( material.vertexColors === THREE.FaceColors ) {
  9408. _diffuseColor.multiply( element.color );
  9409. }
  9410. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  9411. _color1.copy( _ambientLight );
  9412. _color2.copy( _ambientLight );
  9413. _color3.copy( _ambientLight );
  9414. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9415. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9416. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9417. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9418. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9419. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9420. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9421. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9422. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9423. } else {
  9424. _color.copy( _ambientLight );
  9425. calculateLight( element.centroidModel, element.normalModel, _color );
  9426. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9427. material.wireframe === true
  9428. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9429. : fillPath( _color );
  9430. }
  9431. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9432. if ( material.map !== null ) {
  9433. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9434. _uvs = element.uvs[ 0 ];
  9435. 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 );
  9436. }
  9437. } else if ( material.envMap !== null ) {
  9438. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9439. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9440. _uv1x = 0.5 * _vector3.x + 0.5;
  9441. _uv1y = 0.5 * _vector3.y + 0.5;
  9442. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9443. _uv2x = 0.5 * _vector3.x + 0.5;
  9444. _uv2y = 0.5 * _vector3.y + 0.5;
  9445. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9446. _uv3x = 0.5 * _vector3.x + 0.5;
  9447. _uv3y = 0.5 * _vector3.y + 0.5;
  9448. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9449. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  9450. }*/
  9451. } else {
  9452. _color.copy( material.color );
  9453. if ( material.vertexColors === THREE.FaceColors ) {
  9454. _color.multiply( element.color );
  9455. }
  9456. material.wireframe === true
  9457. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9458. : fillPath( _color );
  9459. }
  9460. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9461. _near = _camera.near;
  9462. _far = _camera.far;
  9463. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9464. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9465. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9466. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9467. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9468. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9469. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9470. var normal;
  9471. if ( material.shading == THREE.FlatShading ) {
  9472. normal = element.normalModelView;
  9473. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9474. material.wireframe === true
  9475. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9476. : fillPath( _color );
  9477. } else if ( material.shading == THREE.SmoothShading ) {
  9478. normal = element.vertexNormalsModelView[ uv1 ];
  9479. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9480. normal = element.vertexNormalsModelView[ uv2 ];
  9481. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9482. normal = element.vertexNormalsModelView[ uv3 ];
  9483. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9484. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9485. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9486. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9487. }
  9488. }
  9489. }
  9490. //
  9491. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9492. _context.beginPath();
  9493. _context.moveTo( x0, y0 );
  9494. _context.lineTo( x1, y1 );
  9495. _context.lineTo( x2, y2 );
  9496. _context.closePath();
  9497. }
  9498. function strokePath( color, linewidth, linecap, linejoin ) {
  9499. setLineWidth( linewidth );
  9500. setLineCap( linecap );
  9501. setLineJoin( linejoin );
  9502. setStrokeStyle( color.getStyle() );
  9503. _context.stroke();
  9504. _elemBox.expandByScalar( linewidth * 2 );
  9505. }
  9506. function fillPath( color ) {
  9507. setFillStyle( color.getStyle() );
  9508. _context.fill();
  9509. }
  9510. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9511. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  9512. if ( texture.needsUpdate === true ) {
  9513. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  9514. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  9515. _patterns[ texture.id ] = _context.createPattern(
  9516. texture.image, repeatX === true && repeatY === true
  9517. ? 'repeat'
  9518. : repeatX === true && repeatY === false
  9519. ? 'repeat-x'
  9520. : repeatX === false && repeatY === true
  9521. ? 'repeat-y'
  9522. : 'no-repeat'
  9523. );
  9524. texture.needsUpdate = false;
  9525. }
  9526. _patterns[ texture.id ] === undefined
  9527. ? setFillStyle( 'rgba(0,0,0,1)' )
  9528. : setFillStyle( _patterns[ texture.id ] );
  9529. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9530. var a, b, c, d, e, f, det, idet,
  9531. offsetX = texture.offset.x / texture.repeat.x,
  9532. offsetY = texture.offset.y / texture.repeat.y,
  9533. width = texture.image.width * texture.repeat.x,
  9534. height = texture.image.height * texture.repeat.y;
  9535. u0 = ( u0 + offsetX ) * width;
  9536. v0 = ( 1.0 - v0 + offsetY ) * height;
  9537. u1 = ( u1 + offsetX ) * width;
  9538. v1 = ( 1.0 - v1 + offsetY ) * height;
  9539. u2 = ( u2 + offsetX ) * width;
  9540. v2 = ( 1.0 - v2 + offsetY ) * height;
  9541. x1 -= x0; y1 -= y0;
  9542. x2 -= x0; y2 -= y0;
  9543. u1 -= u0; v1 -= v0;
  9544. u2 -= u0; v2 -= v0;
  9545. det = u1 * v2 - u2 * v1;
  9546. if ( det === 0 ) {
  9547. if ( _imagedatas[ texture.id ] === undefined ) {
  9548. var canvas = document.createElement( 'canvas' )
  9549. canvas.width = texture.image.width;
  9550. canvas.height = texture.image.height;
  9551. var context = canvas.getContext( '2d' );
  9552. context.drawImage( texture.image, 0, 0 );
  9553. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9554. }
  9555. var data = _imagedatas[ texture.id ];
  9556. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9557. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9558. fillPath( _color );
  9559. return;
  9560. }
  9561. idet = 1 / det;
  9562. a = ( v2 * x1 - v1 * x2 ) * idet;
  9563. b = ( v2 * y1 - v1 * y2 ) * idet;
  9564. c = ( u1 * x2 - u2 * x1 ) * idet;
  9565. d = ( u1 * y2 - u2 * y1 ) * idet;
  9566. e = x0 - a * u0 - c * v0;
  9567. f = y0 - b * u0 - d * v0;
  9568. _context.save();
  9569. _context.transform( a, b, c, d, e, f );
  9570. _context.fill();
  9571. _context.restore();
  9572. }
  9573. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9574. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9575. var a, b, c, d, e, f, det, idet,
  9576. width = image.width - 1,
  9577. height = image.height - 1;
  9578. u0 *= width; v0 *= height;
  9579. u1 *= width; v1 *= height;
  9580. u2 *= width; v2 *= height;
  9581. x1 -= x0; y1 -= y0;
  9582. x2 -= x0; y2 -= y0;
  9583. u1 -= u0; v1 -= v0;
  9584. u2 -= u0; v2 -= v0;
  9585. det = u1 * v2 - u2 * v1;
  9586. idet = 1 / det;
  9587. a = ( v2 * x1 - v1 * x2 ) * idet;
  9588. b = ( v2 * y1 - v1 * y2 ) * idet;
  9589. c = ( u1 * x2 - u2 * x1 ) * idet;
  9590. d = ( u1 * y2 - u2 * y1 ) * idet;
  9591. e = x0 - a * u0 - c * v0;
  9592. f = y0 - b * u0 - d * v0;
  9593. _context.save();
  9594. _context.transform( a, b, c, d, e, f );
  9595. _context.clip();
  9596. _context.drawImage( image, 0, 0 );
  9597. _context.restore();
  9598. }
  9599. function getGradientTexture( color1, color2, color3, color4 ) {
  9600. // http://mrdoob.com/blog/post/710
  9601. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9602. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9603. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9604. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9605. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9606. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9607. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9608. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9609. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9610. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9611. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9612. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9613. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9614. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9615. return _gradientMap;
  9616. }
  9617. // Hide anti-alias gaps
  9618. function expand( v1, v2, pixels ) {
  9619. var x = v2.x - v1.x, y = v2.y - v1.y,
  9620. det = x * x + y * y, idet;
  9621. if ( det === 0 ) return;
  9622. idet = pixels / Math.sqrt( det );
  9623. x *= idet; y *= idet;
  9624. v2.x += x; v2.y += y;
  9625. v1.x -= x; v1.y -= y;
  9626. }
  9627. // Context cached methods.
  9628. function setOpacity( value ) {
  9629. if ( _contextGlobalAlpha !== value ) {
  9630. _context.globalAlpha = value;
  9631. _contextGlobalAlpha = value;
  9632. }
  9633. }
  9634. function setBlending( value ) {
  9635. if ( _contextGlobalCompositeOperation !== value ) {
  9636. if ( value === THREE.NormalBlending ) {
  9637. _context.globalCompositeOperation = 'source-over';
  9638. } else if ( value === THREE.AdditiveBlending ) {
  9639. _context.globalCompositeOperation = 'lighter';
  9640. } else if ( value === THREE.SubtractiveBlending ) {
  9641. _context.globalCompositeOperation = 'darker';
  9642. }
  9643. _contextGlobalCompositeOperation = value;
  9644. }
  9645. }
  9646. function setLineWidth( value ) {
  9647. if ( _contextLineWidth !== value ) {
  9648. _context.lineWidth = value;
  9649. _contextLineWidth = value;
  9650. }
  9651. }
  9652. function setLineCap( value ) {
  9653. // "butt", "round", "square"
  9654. if ( _contextLineCap !== value ) {
  9655. _context.lineCap = value;
  9656. _contextLineCap = value;
  9657. }
  9658. }
  9659. function setLineJoin( value ) {
  9660. // "round", "bevel", "miter"
  9661. if ( _contextLineJoin !== value ) {
  9662. _context.lineJoin = value;
  9663. _contextLineJoin = value;
  9664. }
  9665. }
  9666. function setStrokeStyle( value ) {
  9667. if ( _contextStrokeStyle !== value ) {
  9668. _context.strokeStyle = value;
  9669. _contextStrokeStyle = value;
  9670. }
  9671. }
  9672. function setFillStyle( value ) {
  9673. if ( _contextFillStyle !== value ) {
  9674. _context.fillStyle = value;
  9675. _contextFillStyle = value;
  9676. }
  9677. }
  9678. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9679. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9680. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9681. _contextDashSize = dashSizeValue;
  9682. _contextGapSize = gapSizeValue;
  9683. }
  9684. }
  9685. };
  9686. /**
  9687. * @author alteredq / http://alteredqualia.com/
  9688. * @author mrdoob / http://mrdoob.com/
  9689. * @author mikael emtinger / http://gomo.se/
  9690. */
  9691. THREE.ShaderChunk = {
  9692. // FOG
  9693. fog_pars_fragment: [
  9694. "#ifdef USE_FOG",
  9695. "uniform vec3 fogColor;",
  9696. "#ifdef FOG_EXP2",
  9697. "uniform float fogDensity;",
  9698. "#else",
  9699. "uniform float fogNear;",
  9700. "uniform float fogFar;",
  9701. "#endif",
  9702. "#endif"
  9703. ].join("\n"),
  9704. fog_fragment: [
  9705. "#ifdef USE_FOG",
  9706. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9707. "#ifdef FOG_EXP2",
  9708. "const float LOG2 = 1.442695;",
  9709. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9710. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9711. "#else",
  9712. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9713. "#endif",
  9714. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9715. "#endif"
  9716. ].join("\n"),
  9717. // ENVIRONMENT MAP
  9718. envmap_pars_fragment: [
  9719. "#ifdef USE_ENVMAP",
  9720. "uniform float reflectivity;",
  9721. "uniform samplerCube envMap;",
  9722. "uniform float flipEnvMap;",
  9723. "uniform int combine;",
  9724. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9725. "uniform bool useRefract;",
  9726. "uniform float refractionRatio;",
  9727. "#else",
  9728. "varying vec3 vReflect;",
  9729. "#endif",
  9730. "#endif"
  9731. ].join("\n"),
  9732. envmap_fragment: [
  9733. "#ifdef USE_ENVMAP",
  9734. "vec3 reflectVec;",
  9735. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9736. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9737. "if ( useRefract ) {",
  9738. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9739. "} else { ",
  9740. "reflectVec = reflect( cameraToVertex, normal );",
  9741. "}",
  9742. "#else",
  9743. "reflectVec = vReflect;",
  9744. "#endif",
  9745. "#ifdef DOUBLE_SIDED",
  9746. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9747. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9748. "#else",
  9749. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9750. "#endif",
  9751. "#ifdef GAMMA_INPUT",
  9752. "cubeColor.xyz *= cubeColor.xyz;",
  9753. "#endif",
  9754. "if ( combine == 1 ) {",
  9755. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9756. "} else if ( combine == 2 ) {",
  9757. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9758. "} else {",
  9759. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9760. "}",
  9761. "#endif"
  9762. ].join("\n"),
  9763. envmap_pars_vertex: [
  9764. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9765. "varying vec3 vReflect;",
  9766. "uniform float refractionRatio;",
  9767. "uniform bool useRefract;",
  9768. "#endif"
  9769. ].join("\n"),
  9770. worldpos_vertex : [
  9771. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9772. "#ifdef USE_SKINNING",
  9773. "vec4 worldPosition = modelMatrix * skinned;",
  9774. "#endif",
  9775. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9776. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9777. "#endif",
  9778. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9779. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9780. "#endif",
  9781. "#endif"
  9782. ].join("\n"),
  9783. envmap_vertex : [
  9784. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9785. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9786. "worldNormal = normalize( worldNormal );",
  9787. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9788. "if ( useRefract ) {",
  9789. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9790. "} else {",
  9791. "vReflect = reflect( cameraToVertex, worldNormal );",
  9792. "}",
  9793. "#endif"
  9794. ].join("\n"),
  9795. // COLOR MAP (particles)
  9796. map_particle_pars_fragment: [
  9797. "#ifdef USE_MAP",
  9798. "uniform sampler2D map;",
  9799. "#endif"
  9800. ].join("\n"),
  9801. map_particle_fragment: [
  9802. "#ifdef USE_MAP",
  9803. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9804. "#endif"
  9805. ].join("\n"),
  9806. // COLOR MAP (triangles)
  9807. map_pars_vertex: [
  9808. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9809. "varying vec2 vUv;",
  9810. "uniform vec4 offsetRepeat;",
  9811. "#endif"
  9812. ].join("\n"),
  9813. map_pars_fragment: [
  9814. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9815. "varying vec2 vUv;",
  9816. "#endif",
  9817. "#ifdef USE_MAP",
  9818. "uniform sampler2D map;",
  9819. "#endif"
  9820. ].join("\n"),
  9821. map_vertex: [
  9822. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9823. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9824. "#endif"
  9825. ].join("\n"),
  9826. map_fragment: [
  9827. "#ifdef USE_MAP",
  9828. "vec4 texelColor = texture2D( map, vUv );",
  9829. "#ifdef GAMMA_INPUT",
  9830. "texelColor.xyz *= texelColor.xyz;",
  9831. "#endif",
  9832. "gl_FragColor = gl_FragColor * texelColor;",
  9833. "#endif"
  9834. ].join("\n"),
  9835. // LIGHT MAP
  9836. lightmap_pars_fragment: [
  9837. "#ifdef USE_LIGHTMAP",
  9838. "varying vec2 vUv2;",
  9839. "uniform sampler2D lightMap;",
  9840. "#endif"
  9841. ].join("\n"),
  9842. lightmap_pars_vertex: [
  9843. "#ifdef USE_LIGHTMAP",
  9844. "varying vec2 vUv2;",
  9845. "#endif"
  9846. ].join("\n"),
  9847. lightmap_fragment: [
  9848. "#ifdef USE_LIGHTMAP",
  9849. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9850. "#endif"
  9851. ].join("\n"),
  9852. lightmap_vertex: [
  9853. "#ifdef USE_LIGHTMAP",
  9854. "vUv2 = uv2;",
  9855. "#endif"
  9856. ].join("\n"),
  9857. // BUMP MAP
  9858. bumpmap_pars_fragment: [
  9859. "#ifdef USE_BUMPMAP",
  9860. "uniform sampler2D bumpMap;",
  9861. "uniform float bumpScale;",
  9862. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9863. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9864. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9865. "vec2 dHdxy_fwd() {",
  9866. "vec2 dSTdx = dFdx( vUv );",
  9867. "vec2 dSTdy = dFdy( vUv );",
  9868. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9869. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9870. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9871. "return vec2( dBx, dBy );",
  9872. "}",
  9873. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9874. "vec3 vSigmaX = dFdx( surf_pos );",
  9875. "vec3 vSigmaY = dFdy( surf_pos );",
  9876. "vec3 vN = surf_norm;", // normalized
  9877. "vec3 R1 = cross( vSigmaY, vN );",
  9878. "vec3 R2 = cross( vN, vSigmaX );",
  9879. "float fDet = dot( vSigmaX, R1 );",
  9880. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9881. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9882. "}",
  9883. "#endif"
  9884. ].join("\n"),
  9885. // NORMAL MAP
  9886. normalmap_pars_fragment: [
  9887. "#ifdef USE_NORMALMAP",
  9888. "uniform sampler2D normalMap;",
  9889. "uniform vec2 normalScale;",
  9890. // Per-Pixel Tangent Space Normal Mapping
  9891. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9892. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9893. "vec3 q0 = dFdx( eye_pos.xyz );",
  9894. "vec3 q1 = dFdy( eye_pos.xyz );",
  9895. "vec2 st0 = dFdx( vUv.st );",
  9896. "vec2 st1 = dFdy( vUv.st );",
  9897. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9898. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9899. "vec3 N = normalize( surf_norm );",
  9900. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9901. "mapN.xy = normalScale * mapN.xy;",
  9902. "mat3 tsn = mat3( S, T, N );",
  9903. "return normalize( tsn * mapN );",
  9904. "}",
  9905. "#endif"
  9906. ].join("\n"),
  9907. // SPECULAR MAP
  9908. specularmap_pars_fragment: [
  9909. "#ifdef USE_SPECULARMAP",
  9910. "uniform sampler2D specularMap;",
  9911. "#endif"
  9912. ].join("\n"),
  9913. specularmap_fragment: [
  9914. "float specularStrength;",
  9915. "#ifdef USE_SPECULARMAP",
  9916. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9917. "specularStrength = texelSpecular.r;",
  9918. "#else",
  9919. "specularStrength = 1.0;",
  9920. "#endif"
  9921. ].join("\n"),
  9922. // LIGHTS LAMBERT
  9923. lights_lambert_pars_vertex: [
  9924. "uniform vec3 ambient;",
  9925. "uniform vec3 diffuse;",
  9926. "uniform vec3 emissive;",
  9927. "uniform vec3 ambientLightColor;",
  9928. "#if MAX_DIR_LIGHTS > 0",
  9929. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9930. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9931. "#endif",
  9932. "#if MAX_HEMI_LIGHTS > 0",
  9933. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9934. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9935. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9936. "#endif",
  9937. "#if MAX_POINT_LIGHTS > 0",
  9938. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9939. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9940. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9941. "#endif",
  9942. "#if MAX_SPOT_LIGHTS > 0",
  9943. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9944. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9945. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9946. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9947. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9948. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9949. "#endif",
  9950. "#ifdef WRAP_AROUND",
  9951. "uniform vec3 wrapRGB;",
  9952. "#endif"
  9953. ].join("\n"),
  9954. lights_lambert_vertex: [
  9955. "vLightFront = vec3( 0.0 );",
  9956. "#ifdef DOUBLE_SIDED",
  9957. "vLightBack = vec3( 0.0 );",
  9958. "#endif",
  9959. "transformedNormal = normalize( transformedNormal );",
  9960. "#if MAX_DIR_LIGHTS > 0",
  9961. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9962. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9963. "vec3 dirVector = normalize( lDirection.xyz );",
  9964. "float dotProduct = dot( transformedNormal, dirVector );",
  9965. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9966. "#ifdef DOUBLE_SIDED",
  9967. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9968. "#ifdef WRAP_AROUND",
  9969. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9970. "#endif",
  9971. "#endif",
  9972. "#ifdef WRAP_AROUND",
  9973. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9974. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9975. "#ifdef DOUBLE_SIDED",
  9976. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9977. "#endif",
  9978. "#endif",
  9979. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9980. "#ifdef DOUBLE_SIDED",
  9981. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9982. "#endif",
  9983. "}",
  9984. "#endif",
  9985. "#if MAX_POINT_LIGHTS > 0",
  9986. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9987. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9988. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9989. "float lDistance = 1.0;",
  9990. "if ( pointLightDistance[ i ] > 0.0 )",
  9991. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9992. "lVector = normalize( lVector );",
  9993. "float dotProduct = dot( transformedNormal, lVector );",
  9994. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9995. "#ifdef DOUBLE_SIDED",
  9996. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9997. "#ifdef WRAP_AROUND",
  9998. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9999. "#endif",
  10000. "#endif",
  10001. "#ifdef WRAP_AROUND",
  10002. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10003. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10004. "#ifdef DOUBLE_SIDED",
  10005. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10006. "#endif",
  10007. "#endif",
  10008. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10009. "#ifdef DOUBLE_SIDED",
  10010. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10011. "#endif",
  10012. "}",
  10013. "#endif",
  10014. "#if MAX_SPOT_LIGHTS > 0",
  10015. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10016. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10017. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10018. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10019. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10020. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10021. "float lDistance = 1.0;",
  10022. "if ( spotLightDistance[ i ] > 0.0 )",
  10023. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10024. "lVector = normalize( lVector );",
  10025. "float dotProduct = dot( transformedNormal, lVector );",
  10026. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10027. "#ifdef DOUBLE_SIDED",
  10028. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10029. "#ifdef WRAP_AROUND",
  10030. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10031. "#endif",
  10032. "#endif",
  10033. "#ifdef WRAP_AROUND",
  10034. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10035. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10036. "#ifdef DOUBLE_SIDED",
  10037. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10038. "#endif",
  10039. "#endif",
  10040. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10041. "#ifdef DOUBLE_SIDED",
  10042. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10043. "#endif",
  10044. "}",
  10045. "}",
  10046. "#endif",
  10047. "#if MAX_HEMI_LIGHTS > 0",
  10048. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10049. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10050. "vec3 lVector = normalize( lDirection.xyz );",
  10051. "float dotProduct = dot( transformedNormal, lVector );",
  10052. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10053. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10054. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10055. "#ifdef DOUBLE_SIDED",
  10056. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10057. "#endif",
  10058. "}",
  10059. "#endif",
  10060. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10061. "#ifdef DOUBLE_SIDED",
  10062. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10063. "#endif"
  10064. ].join("\n"),
  10065. // LIGHTS PHONG
  10066. lights_phong_pars_vertex: [
  10067. "#ifndef PHONG_PER_PIXEL",
  10068. "#if MAX_POINT_LIGHTS > 0",
  10069. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10070. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10071. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10072. "#endif",
  10073. "#if MAX_SPOT_LIGHTS > 0",
  10074. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10075. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10076. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10077. "#endif",
  10078. "#endif",
  10079. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10080. "varying vec3 vWorldPosition;",
  10081. "#endif"
  10082. ].join("\n"),
  10083. lights_phong_vertex: [
  10084. "#ifndef PHONG_PER_PIXEL",
  10085. "#if MAX_POINT_LIGHTS > 0",
  10086. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10087. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10088. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10089. "float lDistance = 1.0;",
  10090. "if ( pointLightDistance[ i ] > 0.0 )",
  10091. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10092. "vPointLight[ i ] = vec4( lVector, lDistance );",
  10093. "}",
  10094. "#endif",
  10095. "#if MAX_SPOT_LIGHTS > 0",
  10096. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10097. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10098. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10099. "float lDistance = 1.0;",
  10100. "if ( spotLightDistance[ i ] > 0.0 )",
  10101. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10102. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  10103. "}",
  10104. "#endif",
  10105. "#endif",
  10106. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10107. "vWorldPosition = worldPosition.xyz;",
  10108. "#endif"
  10109. ].join("\n"),
  10110. lights_phong_pars_fragment: [
  10111. "uniform vec3 ambientLightColor;",
  10112. "#if MAX_DIR_LIGHTS > 0",
  10113. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10114. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10115. "#endif",
  10116. "#if MAX_HEMI_LIGHTS > 0",
  10117. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10118. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10119. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10120. "#endif",
  10121. "#if MAX_POINT_LIGHTS > 0",
  10122. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10123. "#ifdef PHONG_PER_PIXEL",
  10124. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10125. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10126. "#else",
  10127. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10128. "#endif",
  10129. "#endif",
  10130. "#if MAX_SPOT_LIGHTS > 0",
  10131. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10132. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10133. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10134. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10135. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10136. "#ifdef PHONG_PER_PIXEL",
  10137. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10138. "#else",
  10139. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10140. "#endif",
  10141. "#endif",
  10142. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10143. "varying vec3 vWorldPosition;",
  10144. "#endif",
  10145. "#ifdef WRAP_AROUND",
  10146. "uniform vec3 wrapRGB;",
  10147. "#endif",
  10148. "varying vec3 vViewPosition;",
  10149. "varying vec3 vNormal;"
  10150. ].join("\n"),
  10151. lights_phong_fragment: [
  10152. "vec3 normal = normalize( vNormal );",
  10153. "vec3 viewPosition = normalize( vViewPosition );",
  10154. "#ifdef DOUBLE_SIDED",
  10155. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10156. "#endif",
  10157. "#ifdef USE_NORMALMAP",
  10158. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10159. "#elif defined( USE_BUMPMAP )",
  10160. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10161. "#endif",
  10162. "#if MAX_POINT_LIGHTS > 0",
  10163. "vec3 pointDiffuse = vec3( 0.0 );",
  10164. "vec3 pointSpecular = vec3( 0.0 );",
  10165. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10166. "#ifdef PHONG_PER_PIXEL",
  10167. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10168. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10169. "float lDistance = 1.0;",
  10170. "if ( pointLightDistance[ i ] > 0.0 )",
  10171. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10172. "lVector = normalize( lVector );",
  10173. "#else",
  10174. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10175. "float lDistance = vPointLight[ i ].w;",
  10176. "#endif",
  10177. // diffuse
  10178. "float dotProduct = dot( normal, lVector );",
  10179. "#ifdef WRAP_AROUND",
  10180. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10181. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10182. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10183. "#else",
  10184. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10185. "#endif",
  10186. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10187. // specular
  10188. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10189. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10190. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10191. "#ifdef PHYSICALLY_BASED_SHADING",
  10192. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10193. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10194. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10195. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10196. "#else",
  10197. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  10198. "#endif",
  10199. "}",
  10200. "#endif",
  10201. "#if MAX_SPOT_LIGHTS > 0",
  10202. "vec3 spotDiffuse = vec3( 0.0 );",
  10203. "vec3 spotSpecular = vec3( 0.0 );",
  10204. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10205. "#ifdef PHONG_PER_PIXEL",
  10206. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10207. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10208. "float lDistance = 1.0;",
  10209. "if ( spotLightDistance[ i ] > 0.0 )",
  10210. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10211. "lVector = normalize( lVector );",
  10212. "#else",
  10213. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10214. "float lDistance = vSpotLight[ i ].w;",
  10215. "#endif",
  10216. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10217. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10218. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10219. // diffuse
  10220. "float dotProduct = dot( normal, lVector );",
  10221. "#ifdef WRAP_AROUND",
  10222. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10223. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10224. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10225. "#else",
  10226. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10227. "#endif",
  10228. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10229. // specular
  10230. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10231. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10232. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10233. "#ifdef PHYSICALLY_BASED_SHADING",
  10234. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10235. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10236. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10237. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10238. "#else",
  10239. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10240. "#endif",
  10241. "}",
  10242. "}",
  10243. "#endif",
  10244. "#if MAX_DIR_LIGHTS > 0",
  10245. "vec3 dirDiffuse = vec3( 0.0 );",
  10246. "vec3 dirSpecular = vec3( 0.0 );" ,
  10247. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10248. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10249. "vec3 dirVector = normalize( lDirection.xyz );",
  10250. // diffuse
  10251. "float dotProduct = dot( normal, dirVector );",
  10252. "#ifdef WRAP_AROUND",
  10253. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10254. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10255. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10256. "#else",
  10257. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10258. "#endif",
  10259. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10260. // specular
  10261. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10262. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10263. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10264. "#ifdef PHYSICALLY_BASED_SHADING",
  10265. /*
  10266. // fresnel term from skin shader
  10267. "const float F0 = 0.128;",
  10268. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10269. "float exponential = pow( base, 5.0 );",
  10270. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10271. */
  10272. /*
  10273. // fresnel term from fresnel shader
  10274. "const float mFresnelBias = 0.08;",
  10275. "const float mFresnelScale = 0.3;",
  10276. "const float mFresnelPower = 5.0;",
  10277. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10278. */
  10279. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10280. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10281. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10282. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10283. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10284. "#else",
  10285. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10286. "#endif",
  10287. "}",
  10288. "#endif",
  10289. "#if MAX_HEMI_LIGHTS > 0",
  10290. "vec3 hemiDiffuse = vec3( 0.0 );",
  10291. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10292. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10293. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10294. "vec3 lVector = normalize( lDirection.xyz );",
  10295. // diffuse
  10296. "float dotProduct = dot( normal, lVector );",
  10297. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10298. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10299. "hemiDiffuse += diffuse * hemiColor;",
  10300. // specular (sky light)
  10301. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10302. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10303. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10304. // specular (ground light)
  10305. "vec3 lVectorGround = -lVector;",
  10306. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10307. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10308. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10309. "#ifdef PHYSICALLY_BASED_SHADING",
  10310. "float dotProductGround = dot( normal, lVectorGround );",
  10311. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10312. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10313. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10314. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10315. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10316. "#else",
  10317. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10318. "#endif",
  10319. "}",
  10320. "#endif",
  10321. "vec3 totalDiffuse = vec3( 0.0 );",
  10322. "vec3 totalSpecular = vec3( 0.0 );",
  10323. "#if MAX_DIR_LIGHTS > 0",
  10324. "totalDiffuse += dirDiffuse;",
  10325. "totalSpecular += dirSpecular;",
  10326. "#endif",
  10327. "#if MAX_HEMI_LIGHTS > 0",
  10328. "totalDiffuse += hemiDiffuse;",
  10329. "totalSpecular += hemiSpecular;",
  10330. "#endif",
  10331. "#if MAX_POINT_LIGHTS > 0",
  10332. "totalDiffuse += pointDiffuse;",
  10333. "totalSpecular += pointSpecular;",
  10334. "#endif",
  10335. "#if MAX_SPOT_LIGHTS > 0",
  10336. "totalDiffuse += spotDiffuse;",
  10337. "totalSpecular += spotSpecular;",
  10338. "#endif",
  10339. "#ifdef METAL",
  10340. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10341. "#else",
  10342. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10343. "#endif"
  10344. ].join("\n"),
  10345. // VERTEX COLORS
  10346. color_pars_fragment: [
  10347. "#ifdef USE_COLOR",
  10348. "varying vec3 vColor;",
  10349. "#endif"
  10350. ].join("\n"),
  10351. color_fragment: [
  10352. "#ifdef USE_COLOR",
  10353. "gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10354. "#endif"
  10355. ].join("\n"),
  10356. color_pars_vertex: [
  10357. "#ifdef USE_COLOR",
  10358. "varying vec3 vColor;",
  10359. "#endif"
  10360. ].join("\n"),
  10361. color_vertex: [
  10362. "#ifdef USE_COLOR",
  10363. "#ifdef GAMMA_INPUT",
  10364. "vColor = color * color;",
  10365. "#else",
  10366. "vColor = color;",
  10367. "#endif",
  10368. "#endif"
  10369. ].join("\n"),
  10370. // SKINNING
  10371. skinning_pars_vertex: [
  10372. "#ifdef USE_SKINNING",
  10373. "#ifdef BONE_TEXTURE",
  10374. "uniform sampler2D boneTexture;",
  10375. "uniform int boneTextureWidth;",
  10376. "uniform int boneTextureHeight;",
  10377. "mat4 getBoneMatrix( const in float i ) {",
  10378. "float j = i * 4.0;",
  10379. "float x = mod( j, float( boneTextureWidth ) );",
  10380. "float y = floor( j / float( boneTextureWidth ) );",
  10381. "float dx = 1.0 / float( boneTextureWidth );",
  10382. "float dy = 1.0 / float( boneTextureHeight );",
  10383. "y = dy * ( y + 0.5 );",
  10384. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10385. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10386. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10387. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10388. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10389. "return bone;",
  10390. "}",
  10391. "#else",
  10392. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10393. "mat4 getBoneMatrix( const in float i ) {",
  10394. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10395. "return bone;",
  10396. "}",
  10397. "#endif",
  10398. "#endif"
  10399. ].join("\n"),
  10400. skinbase_vertex: [
  10401. "#ifdef USE_SKINNING",
  10402. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10403. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10404. "#endif"
  10405. ].join("\n"),
  10406. skinning_vertex: [
  10407. "#ifdef USE_SKINNING",
  10408. "#ifdef USE_MORPHTARGETS",
  10409. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10410. "#else",
  10411. "vec4 skinVertex = vec4( position, 1.0 );",
  10412. "#endif",
  10413. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10414. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10415. "#endif"
  10416. ].join("\n"),
  10417. // MORPHING
  10418. morphtarget_pars_vertex: [
  10419. "#ifdef USE_MORPHTARGETS",
  10420. "#ifndef USE_MORPHNORMALS",
  10421. "uniform float morphTargetInfluences[ 8 ];",
  10422. "#else",
  10423. "uniform float morphTargetInfluences[ 4 ];",
  10424. "#endif",
  10425. "#endif"
  10426. ].join("\n"),
  10427. morphtarget_vertex: [
  10428. "#ifdef USE_MORPHTARGETS",
  10429. "vec3 morphed = vec3( 0.0 );",
  10430. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10431. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10432. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10433. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10434. "#ifndef USE_MORPHNORMALS",
  10435. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10436. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10437. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10438. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10439. "#endif",
  10440. "morphed += position;",
  10441. "#endif"
  10442. ].join("\n"),
  10443. default_vertex : [
  10444. "vec4 mvPosition;",
  10445. "#ifdef USE_SKINNING",
  10446. "mvPosition = modelViewMatrix * skinned;",
  10447. "#endif",
  10448. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10449. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10450. "#endif",
  10451. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10452. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10453. "#endif",
  10454. "gl_Position = projectionMatrix * mvPosition;"
  10455. ].join("\n"),
  10456. morphnormal_vertex: [
  10457. "#ifdef USE_MORPHNORMALS",
  10458. "vec3 morphedNormal = vec3( 0.0 );",
  10459. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10460. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10461. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10462. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10463. "morphedNormal += normal;",
  10464. "#endif"
  10465. ].join("\n"),
  10466. skinnormal_vertex: [
  10467. "#ifdef USE_SKINNING",
  10468. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10469. "skinMatrix += skinWeight.y * boneMatY;",
  10470. "#ifdef USE_MORPHNORMALS",
  10471. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10472. "#else",
  10473. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10474. "#endif",
  10475. "#endif"
  10476. ].join("\n"),
  10477. defaultnormal_vertex: [
  10478. "vec3 objectNormal;",
  10479. "#ifdef USE_SKINNING",
  10480. "objectNormal = skinnedNormal.xyz;",
  10481. "#endif",
  10482. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10483. "objectNormal = morphedNormal;",
  10484. "#endif",
  10485. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10486. "objectNormal = normal;",
  10487. "#endif",
  10488. "#ifdef FLIP_SIDED",
  10489. "objectNormal = -objectNormal;",
  10490. "#endif",
  10491. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10492. ].join("\n"),
  10493. // SHADOW MAP
  10494. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10495. // http://spidergl.org/example.php?id=6
  10496. // http://fabiensanglard.net/shadowmapping
  10497. shadowmap_pars_fragment: [
  10498. "#ifdef USE_SHADOWMAP",
  10499. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10500. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10501. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10502. "uniform float shadowBias[ MAX_SHADOWS ];",
  10503. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10504. "float unpackDepth( const in vec4 rgba_depth ) {",
  10505. "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 );",
  10506. "float depth = dot( rgba_depth, bit_shift );",
  10507. "return depth;",
  10508. "}",
  10509. "#endif"
  10510. ].join("\n"),
  10511. shadowmap_fragment: [
  10512. "#ifdef USE_SHADOWMAP",
  10513. "#ifdef SHADOWMAP_DEBUG",
  10514. "vec3 frustumColors[3];",
  10515. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10516. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10517. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10518. "#endif",
  10519. "#ifdef SHADOWMAP_CASCADE",
  10520. "int inFrustumCount = 0;",
  10521. "#endif",
  10522. "float fDepth;",
  10523. "vec3 shadowColor = vec3( 1.0 );",
  10524. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10525. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10526. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10527. // "if ( all( something, something ) )" using this instead
  10528. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10529. "bool inFrustum = all( inFrustumVec );",
  10530. // don't shadow pixels outside of light frustum
  10531. // use just first frustum (for cascades)
  10532. // don't shadow pixels behind far plane of light frustum
  10533. "#ifdef SHADOWMAP_CASCADE",
  10534. "inFrustumCount += int( inFrustum );",
  10535. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10536. "#else",
  10537. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10538. "#endif",
  10539. "bool frustumTest = all( frustumTestVec );",
  10540. "if ( frustumTest ) {",
  10541. "shadowCoord.z += shadowBias[ i ];",
  10542. "#if defined( SHADOWMAP_TYPE_PCF )",
  10543. // Percentage-close filtering
  10544. // (9 pixel kernel)
  10545. // http://fabiensanglard.net/shadowmappingPCF/
  10546. "float shadow = 0.0;",
  10547. /*
  10548. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10549. // must enroll loop manually
  10550. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10551. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10552. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10553. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10554. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10555. "float fDepth = unpackDepth( rgbaDepth );",
  10556. "if ( fDepth < shadowCoord.z )",
  10557. "shadow += 1.0;",
  10558. "}",
  10559. "shadow /= 9.0;",
  10560. */
  10561. "const float shadowDelta = 1.0 / 9.0;",
  10562. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10563. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10564. "float dx0 = -1.25 * xPixelOffset;",
  10565. "float dy0 = -1.25 * yPixelOffset;",
  10566. "float dx1 = 1.25 * xPixelOffset;",
  10567. "float dy1 = 1.25 * yPixelOffset;",
  10568. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10569. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10570. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10571. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10572. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10573. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10574. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10575. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10576. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10577. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10578. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10579. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10580. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10581. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10582. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10583. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10584. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10585. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10586. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10587. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10588. // Percentage-close filtering
  10589. // (9 pixel kernel)
  10590. // http://fabiensanglard.net/shadowmappingPCF/
  10591. "float shadow = 0.0;",
  10592. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10593. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10594. "float dx0 = -1.0 * xPixelOffset;",
  10595. "float dy0 = -1.0 * yPixelOffset;",
  10596. "float dx1 = 1.0 * xPixelOffset;",
  10597. "float dy1 = 1.0 * yPixelOffset;",
  10598. "mat3 shadowKernel;",
  10599. "mat3 depthKernel;",
  10600. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10601. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10602. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10603. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10604. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10605. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10606. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10607. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10608. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10609. "vec3 shadowZ = vec3( shadowCoord.z );",
  10610. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10611. "shadowKernel[0] *= vec3(0.25);",
  10612. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10613. "shadowKernel[1] *= vec3(0.25);",
  10614. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10615. "shadowKernel[2] *= vec3(0.25);",
  10616. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10617. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10618. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10619. "vec4 shadowValues;",
  10620. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10621. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10622. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10623. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10624. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10625. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10626. "#else",
  10627. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10628. "float fDepth = unpackDepth( rgbaDepth );",
  10629. "if ( fDepth < shadowCoord.z )",
  10630. // spot with multiple shadows is darker
  10631. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10632. // spot with multiple shadows has the same color as single shadow spot
  10633. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10634. "#endif",
  10635. "}",
  10636. "#ifdef SHADOWMAP_DEBUG",
  10637. "#ifdef SHADOWMAP_CASCADE",
  10638. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10639. "#else",
  10640. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10641. "#endif",
  10642. "#endif",
  10643. "}",
  10644. "#ifdef GAMMA_OUTPUT",
  10645. "shadowColor *= shadowColor;",
  10646. "#endif",
  10647. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10648. "#endif"
  10649. ].join("\n"),
  10650. shadowmap_pars_vertex: [
  10651. "#ifdef USE_SHADOWMAP",
  10652. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10653. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10654. "#endif"
  10655. ].join("\n"),
  10656. shadowmap_vertex: [
  10657. "#ifdef USE_SHADOWMAP",
  10658. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10659. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10660. "}",
  10661. "#endif"
  10662. ].join("\n"),
  10663. // ALPHATEST
  10664. alphatest_fragment: [
  10665. "#ifdef ALPHATEST",
  10666. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10667. "#endif"
  10668. ].join("\n"),
  10669. // LINEAR SPACE
  10670. linear_to_gamma_fragment: [
  10671. "#ifdef GAMMA_OUTPUT",
  10672. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10673. "#endif"
  10674. ].join("\n")
  10675. };
  10676. THREE.UniformsUtils = {
  10677. merge: function ( uniforms ) {
  10678. var u, p, tmp, merged = {};
  10679. for ( u = 0; u < uniforms.length; u ++ ) {
  10680. tmp = this.clone( uniforms[ u ] );
  10681. for ( p in tmp ) {
  10682. merged[ p ] = tmp[ p ];
  10683. }
  10684. }
  10685. return merged;
  10686. },
  10687. clone: function ( uniforms_src ) {
  10688. var u, p, parameter, parameter_src, uniforms_dst = {};
  10689. for ( u in uniforms_src ) {
  10690. uniforms_dst[ u ] = {};
  10691. for ( p in uniforms_src[ u ] ) {
  10692. parameter_src = uniforms_src[ u ][ p ];
  10693. if ( parameter_src instanceof THREE.Color ||
  10694. parameter_src instanceof THREE.Vector2 ||
  10695. parameter_src instanceof THREE.Vector3 ||
  10696. parameter_src instanceof THREE.Vector4 ||
  10697. parameter_src instanceof THREE.Matrix4 ||
  10698. parameter_src instanceof THREE.Texture ) {
  10699. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10700. } else if ( parameter_src instanceof Array ) {
  10701. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10702. } else {
  10703. uniforms_dst[ u ][ p ] = parameter_src;
  10704. }
  10705. }
  10706. }
  10707. return uniforms_dst;
  10708. }
  10709. };
  10710. THREE.UniformsLib = {
  10711. common: {
  10712. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10713. "opacity" : { type: "f", value: 1.0 },
  10714. "map" : { type: "t", value: null },
  10715. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10716. "lightMap" : { type: "t", value: null },
  10717. "specularMap" : { type: "t", value: null },
  10718. "envMap" : { type: "t", value: null },
  10719. "flipEnvMap" : { type: "f", value: -1 },
  10720. "useRefract" : { type: "i", value: 0 },
  10721. "reflectivity" : { type: "f", value: 1.0 },
  10722. "refractionRatio" : { type: "f", value: 0.98 },
  10723. "combine" : { type: "i", value: 0 },
  10724. "morphTargetInfluences" : { type: "f", value: 0 }
  10725. },
  10726. bump: {
  10727. "bumpMap" : { type: "t", value: null },
  10728. "bumpScale" : { type: "f", value: 1 }
  10729. },
  10730. normalmap: {
  10731. "normalMap" : { type: "t", value: null },
  10732. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10733. },
  10734. fog : {
  10735. "fogDensity" : { type: "f", value: 0.00025 },
  10736. "fogNear" : { type: "f", value: 1 },
  10737. "fogFar" : { type: "f", value: 2000 },
  10738. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10739. },
  10740. lights: {
  10741. "ambientLightColor" : { type: "fv", value: [] },
  10742. "directionalLightDirection" : { type: "fv", value: [] },
  10743. "directionalLightColor" : { type: "fv", value: [] },
  10744. "hemisphereLightDirection" : { type: "fv", value: [] },
  10745. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10746. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10747. "pointLightColor" : { type: "fv", value: [] },
  10748. "pointLightPosition" : { type: "fv", value: [] },
  10749. "pointLightDistance" : { type: "fv1", value: [] },
  10750. "spotLightColor" : { type: "fv", value: [] },
  10751. "spotLightPosition" : { type: "fv", value: [] },
  10752. "spotLightDirection" : { type: "fv", value: [] },
  10753. "spotLightDistance" : { type: "fv1", value: [] },
  10754. "spotLightAngleCos" : { type: "fv1", value: [] },
  10755. "spotLightExponent" : { type: "fv1", value: [] }
  10756. },
  10757. particle: {
  10758. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10759. "opacity" : { type: "f", value: 1.0 },
  10760. "size" : { type: "f", value: 1.0 },
  10761. "scale" : { type: "f", value: 1.0 },
  10762. "map" : { type: "t", value: null },
  10763. "fogDensity" : { type: "f", value: 0.00025 },
  10764. "fogNear" : { type: "f", value: 1 },
  10765. "fogFar" : { type: "f", value: 2000 },
  10766. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10767. },
  10768. shadowmap: {
  10769. "shadowMap": { type: "tv", value: [] },
  10770. "shadowMapSize": { type: "v2v", value: [] },
  10771. "shadowBias" : { type: "fv1", value: [] },
  10772. "shadowDarkness": { type: "fv1", value: [] },
  10773. "shadowMatrix" : { type: "m4v", value: [] }
  10774. }
  10775. };
  10776. THREE.ShaderLib = {
  10777. 'basic': {
  10778. uniforms: THREE.UniformsUtils.merge( [
  10779. THREE.UniformsLib[ "common" ],
  10780. THREE.UniformsLib[ "fog" ],
  10781. THREE.UniformsLib[ "shadowmap" ]
  10782. ] ),
  10783. vertexShader: [
  10784. THREE.ShaderChunk[ "map_pars_vertex" ],
  10785. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10786. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10787. THREE.ShaderChunk[ "color_pars_vertex" ],
  10788. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10789. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10790. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10791. "void main() {",
  10792. THREE.ShaderChunk[ "map_vertex" ],
  10793. THREE.ShaderChunk[ "lightmap_vertex" ],
  10794. THREE.ShaderChunk[ "color_vertex" ],
  10795. THREE.ShaderChunk[ "skinbase_vertex" ],
  10796. "#ifdef USE_ENVMAP",
  10797. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10798. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10799. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10800. "#endif",
  10801. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10802. THREE.ShaderChunk[ "skinning_vertex" ],
  10803. THREE.ShaderChunk[ "default_vertex" ],
  10804. THREE.ShaderChunk[ "worldpos_vertex" ],
  10805. THREE.ShaderChunk[ "envmap_vertex" ],
  10806. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10807. "}"
  10808. ].join("\n"),
  10809. fragmentShader: [
  10810. "uniform vec3 diffuse;",
  10811. "uniform float opacity;",
  10812. THREE.ShaderChunk[ "color_pars_fragment" ],
  10813. THREE.ShaderChunk[ "map_pars_fragment" ],
  10814. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10815. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10816. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10817. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10818. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10819. "void main() {",
  10820. "gl_FragColor = vec4( diffuse, opacity );",
  10821. THREE.ShaderChunk[ "map_fragment" ],
  10822. THREE.ShaderChunk[ "alphatest_fragment" ],
  10823. THREE.ShaderChunk[ "specularmap_fragment" ],
  10824. THREE.ShaderChunk[ "lightmap_fragment" ],
  10825. THREE.ShaderChunk[ "color_fragment" ],
  10826. THREE.ShaderChunk[ "envmap_fragment" ],
  10827. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10828. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10829. THREE.ShaderChunk[ "fog_fragment" ],
  10830. "}"
  10831. ].join("\n")
  10832. },
  10833. 'lambert': {
  10834. uniforms: THREE.UniformsUtils.merge( [
  10835. THREE.UniformsLib[ "common" ],
  10836. THREE.UniformsLib[ "fog" ],
  10837. THREE.UniformsLib[ "lights" ],
  10838. THREE.UniformsLib[ "shadowmap" ],
  10839. {
  10840. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10841. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10842. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10843. }
  10844. ] ),
  10845. vertexShader: [
  10846. "#define LAMBERT",
  10847. "varying vec3 vLightFront;",
  10848. "#ifdef DOUBLE_SIDED",
  10849. "varying vec3 vLightBack;",
  10850. "#endif",
  10851. THREE.ShaderChunk[ "map_pars_vertex" ],
  10852. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10853. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10854. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10855. THREE.ShaderChunk[ "color_pars_vertex" ],
  10856. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10857. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10858. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10859. "void main() {",
  10860. THREE.ShaderChunk[ "map_vertex" ],
  10861. THREE.ShaderChunk[ "lightmap_vertex" ],
  10862. THREE.ShaderChunk[ "color_vertex" ],
  10863. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10864. THREE.ShaderChunk[ "skinbase_vertex" ],
  10865. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10866. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10867. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10868. THREE.ShaderChunk[ "skinning_vertex" ],
  10869. THREE.ShaderChunk[ "default_vertex" ],
  10870. THREE.ShaderChunk[ "worldpos_vertex" ],
  10871. THREE.ShaderChunk[ "envmap_vertex" ],
  10872. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10873. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10874. "}"
  10875. ].join("\n"),
  10876. fragmentShader: [
  10877. "uniform float opacity;",
  10878. "varying vec3 vLightFront;",
  10879. "#ifdef DOUBLE_SIDED",
  10880. "varying vec3 vLightBack;",
  10881. "#endif",
  10882. THREE.ShaderChunk[ "color_pars_fragment" ],
  10883. THREE.ShaderChunk[ "map_pars_fragment" ],
  10884. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10885. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10886. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10887. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10888. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10889. "void main() {",
  10890. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10891. THREE.ShaderChunk[ "map_fragment" ],
  10892. THREE.ShaderChunk[ "alphatest_fragment" ],
  10893. THREE.ShaderChunk[ "specularmap_fragment" ],
  10894. "#ifdef DOUBLE_SIDED",
  10895. //"float isFront = float( gl_FrontFacing );",
  10896. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10897. "if ( gl_FrontFacing )",
  10898. "gl_FragColor.xyz *= vLightFront;",
  10899. "else",
  10900. "gl_FragColor.xyz *= vLightBack;",
  10901. "#else",
  10902. "gl_FragColor.xyz *= vLightFront;",
  10903. "#endif",
  10904. THREE.ShaderChunk[ "lightmap_fragment" ],
  10905. THREE.ShaderChunk[ "color_fragment" ],
  10906. THREE.ShaderChunk[ "envmap_fragment" ],
  10907. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10908. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10909. THREE.ShaderChunk[ "fog_fragment" ],
  10910. "}"
  10911. ].join("\n")
  10912. },
  10913. 'phong': {
  10914. uniforms: THREE.UniformsUtils.merge( [
  10915. THREE.UniformsLib[ "common" ],
  10916. THREE.UniformsLib[ "bump" ],
  10917. THREE.UniformsLib[ "normalmap" ],
  10918. THREE.UniformsLib[ "fog" ],
  10919. THREE.UniformsLib[ "lights" ],
  10920. THREE.UniformsLib[ "shadowmap" ],
  10921. {
  10922. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10923. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10924. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10925. "shininess": { type: "f", value: 30 },
  10926. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10927. }
  10928. ] ),
  10929. vertexShader: [
  10930. "#define PHONG",
  10931. "varying vec3 vViewPosition;",
  10932. "varying vec3 vNormal;",
  10933. THREE.ShaderChunk[ "map_pars_vertex" ],
  10934. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10935. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10936. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10937. THREE.ShaderChunk[ "color_pars_vertex" ],
  10938. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10939. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10940. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10941. "void main() {",
  10942. THREE.ShaderChunk[ "map_vertex" ],
  10943. THREE.ShaderChunk[ "lightmap_vertex" ],
  10944. THREE.ShaderChunk[ "color_vertex" ],
  10945. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10946. THREE.ShaderChunk[ "skinbase_vertex" ],
  10947. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10948. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10949. "vNormal = normalize( transformedNormal );",
  10950. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10951. THREE.ShaderChunk[ "skinning_vertex" ],
  10952. THREE.ShaderChunk[ "default_vertex" ],
  10953. "vViewPosition = -mvPosition.xyz;",
  10954. THREE.ShaderChunk[ "worldpos_vertex" ],
  10955. THREE.ShaderChunk[ "envmap_vertex" ],
  10956. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10957. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10958. "}"
  10959. ].join("\n"),
  10960. fragmentShader: [
  10961. "uniform vec3 diffuse;",
  10962. "uniform float opacity;",
  10963. "uniform vec3 ambient;",
  10964. "uniform vec3 emissive;",
  10965. "uniform vec3 specular;",
  10966. "uniform float shininess;",
  10967. THREE.ShaderChunk[ "color_pars_fragment" ],
  10968. THREE.ShaderChunk[ "map_pars_fragment" ],
  10969. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10970. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10971. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10972. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10973. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10974. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10975. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10976. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10977. "void main() {",
  10978. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10979. THREE.ShaderChunk[ "map_fragment" ],
  10980. THREE.ShaderChunk[ "alphatest_fragment" ],
  10981. THREE.ShaderChunk[ "specularmap_fragment" ],
  10982. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10983. THREE.ShaderChunk[ "lightmap_fragment" ],
  10984. THREE.ShaderChunk[ "color_fragment" ],
  10985. THREE.ShaderChunk[ "envmap_fragment" ],
  10986. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10987. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10988. THREE.ShaderChunk[ "fog_fragment" ],
  10989. "}"
  10990. ].join("\n")
  10991. },
  10992. 'particle_basic': {
  10993. uniforms: THREE.UniformsUtils.merge( [
  10994. THREE.UniformsLib[ "particle" ],
  10995. THREE.UniformsLib[ "shadowmap" ]
  10996. ] ),
  10997. vertexShader: [
  10998. "uniform float size;",
  10999. "uniform float scale;",
  11000. THREE.ShaderChunk[ "color_pars_vertex" ],
  11001. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11002. "void main() {",
  11003. THREE.ShaderChunk[ "color_vertex" ],
  11004. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11005. "#ifdef USE_SIZEATTENUATION",
  11006. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11007. "#else",
  11008. "gl_PointSize = size;",
  11009. "#endif",
  11010. "gl_Position = projectionMatrix * mvPosition;",
  11011. THREE.ShaderChunk[ "worldpos_vertex" ],
  11012. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11013. "}"
  11014. ].join("\n"),
  11015. fragmentShader: [
  11016. "uniform vec3 psColor;",
  11017. "uniform float opacity;",
  11018. THREE.ShaderChunk[ "color_pars_fragment" ],
  11019. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11020. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11021. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11022. "void main() {",
  11023. "gl_FragColor = vec4( psColor, opacity );",
  11024. THREE.ShaderChunk[ "map_particle_fragment" ],
  11025. THREE.ShaderChunk[ "alphatest_fragment" ],
  11026. THREE.ShaderChunk[ "color_fragment" ],
  11027. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11028. THREE.ShaderChunk[ "fog_fragment" ],
  11029. "}"
  11030. ].join("\n")
  11031. },
  11032. 'dashed': {
  11033. uniforms: THREE.UniformsUtils.merge( [
  11034. THREE.UniformsLib[ "common" ],
  11035. THREE.UniformsLib[ "fog" ],
  11036. {
  11037. "scale": { type: "f", value: 1 },
  11038. "dashSize": { type: "f", value: 1 },
  11039. "totalSize": { type: "f", value: 2 }
  11040. }
  11041. ] ),
  11042. vertexShader: [
  11043. "uniform float scale;",
  11044. "attribute float lineDistance;",
  11045. "varying float vLineDistance;",
  11046. THREE.ShaderChunk[ "color_pars_vertex" ],
  11047. "void main() {",
  11048. THREE.ShaderChunk[ "color_vertex" ],
  11049. "vLineDistance = scale * lineDistance;",
  11050. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11051. "gl_Position = projectionMatrix * mvPosition;",
  11052. "}"
  11053. ].join("\n"),
  11054. fragmentShader: [
  11055. "uniform vec3 diffuse;",
  11056. "uniform float opacity;",
  11057. "uniform float dashSize;",
  11058. "uniform float totalSize;",
  11059. "varying float vLineDistance;",
  11060. THREE.ShaderChunk[ "color_pars_fragment" ],
  11061. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11062. "void main() {",
  11063. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11064. "discard;",
  11065. "}",
  11066. "gl_FragColor = vec4( diffuse, opacity );",
  11067. THREE.ShaderChunk[ "color_fragment" ],
  11068. THREE.ShaderChunk[ "fog_fragment" ],
  11069. "}"
  11070. ].join("\n")
  11071. },
  11072. 'depth': {
  11073. uniforms: {
  11074. "mNear": { type: "f", value: 1.0 },
  11075. "mFar" : { type: "f", value: 2000.0 },
  11076. "opacity" : { type: "f", value: 1.0 }
  11077. },
  11078. vertexShader: [
  11079. "void main() {",
  11080. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11081. "}"
  11082. ].join("\n"),
  11083. fragmentShader: [
  11084. "uniform float mNear;",
  11085. "uniform float mFar;",
  11086. "uniform float opacity;",
  11087. "void main() {",
  11088. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11089. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11090. "gl_FragColor = vec4( vec3( color ), opacity );",
  11091. "}"
  11092. ].join("\n")
  11093. },
  11094. 'normal': {
  11095. uniforms: {
  11096. "opacity" : { type: "f", value: 1.0 }
  11097. },
  11098. vertexShader: [
  11099. "varying vec3 vNormal;",
  11100. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11101. "void main() {",
  11102. "vNormal = normalize( normalMatrix * normal );",
  11103. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11104. THREE.ShaderChunk[ "default_vertex" ],
  11105. "}"
  11106. ].join("\n"),
  11107. fragmentShader: [
  11108. "uniform float opacity;",
  11109. "varying vec3 vNormal;",
  11110. "void main() {",
  11111. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11112. "}"
  11113. ].join("\n")
  11114. },
  11115. /* -------------------------------------------------------------------------
  11116. // Normal map shader
  11117. // - Blinn-Phong
  11118. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11119. // - point and directional lights (use with "lights: true" material option)
  11120. ------------------------------------------------------------------------- */
  11121. 'normalmap' : {
  11122. uniforms: THREE.UniformsUtils.merge( [
  11123. THREE.UniformsLib[ "fog" ],
  11124. THREE.UniformsLib[ "lights" ],
  11125. THREE.UniformsLib[ "shadowmap" ],
  11126. {
  11127. "enableAO" : { type: "i", value: 0 },
  11128. "enableDiffuse" : { type: "i", value: 0 },
  11129. "enableSpecular" : { type: "i", value: 0 },
  11130. "enableReflection": { type: "i", value: 0 },
  11131. "enableDisplacement": { type: "i", value: 0 },
  11132. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11133. "tDiffuse" : { type: "t", value: null },
  11134. "tCube" : { type: "t", value: null },
  11135. "tNormal" : { type: "t", value: null },
  11136. "tSpecular" : { type: "t", value: null },
  11137. "tAO" : { type: "t", value: null },
  11138. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11139. "uDisplacementBias": { type: "f", value: 0.0 },
  11140. "uDisplacementScale": { type: "f", value: 1.0 },
  11141. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11142. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11143. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11144. "uShininess": { type: "f", value: 30 },
  11145. "uOpacity": { type: "f", value: 1 },
  11146. "useRefract": { type: "i", value: 0 },
  11147. "uRefractionRatio": { type: "f", value: 0.98 },
  11148. "uReflectivity": { type: "f", value: 0.5 },
  11149. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11150. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11151. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11152. }
  11153. ] ),
  11154. fragmentShader: [
  11155. "uniform vec3 uAmbientColor;",
  11156. "uniform vec3 uDiffuseColor;",
  11157. "uniform vec3 uSpecularColor;",
  11158. "uniform float uShininess;",
  11159. "uniform float uOpacity;",
  11160. "uniform bool enableDiffuse;",
  11161. "uniform bool enableSpecular;",
  11162. "uniform bool enableAO;",
  11163. "uniform bool enableReflection;",
  11164. "uniform sampler2D tDiffuse;",
  11165. "uniform sampler2D tNormal;",
  11166. "uniform sampler2D tSpecular;",
  11167. "uniform sampler2D tAO;",
  11168. "uniform samplerCube tCube;",
  11169. "uniform vec2 uNormalScale;",
  11170. "uniform bool useRefract;",
  11171. "uniform float uRefractionRatio;",
  11172. "uniform float uReflectivity;",
  11173. "varying vec3 vTangent;",
  11174. "varying vec3 vBinormal;",
  11175. "varying vec3 vNormal;",
  11176. "varying vec2 vUv;",
  11177. "uniform vec3 ambientLightColor;",
  11178. "#if MAX_DIR_LIGHTS > 0",
  11179. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11180. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11181. "#endif",
  11182. "#if MAX_HEMI_LIGHTS > 0",
  11183. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11184. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11185. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11186. "#endif",
  11187. "#if MAX_POINT_LIGHTS > 0",
  11188. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11189. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11190. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11191. "#endif",
  11192. "#if MAX_SPOT_LIGHTS > 0",
  11193. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11194. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11195. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11196. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11197. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11198. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11199. "#endif",
  11200. "#ifdef WRAP_AROUND",
  11201. "uniform vec3 wrapRGB;",
  11202. "#endif",
  11203. "varying vec3 vWorldPosition;",
  11204. "varying vec3 vViewPosition;",
  11205. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11206. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11207. "void main() {",
  11208. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11209. "vec3 specularTex = vec3( 1.0 );",
  11210. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11211. "normalTex.xy *= uNormalScale;",
  11212. "normalTex = normalize( normalTex );",
  11213. "if( enableDiffuse ) {",
  11214. "#ifdef GAMMA_INPUT",
  11215. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11216. "texelColor.xyz *= texelColor.xyz;",
  11217. "gl_FragColor = gl_FragColor * texelColor;",
  11218. "#else",
  11219. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11220. "#endif",
  11221. "}",
  11222. "if( enableAO ) {",
  11223. "#ifdef GAMMA_INPUT",
  11224. "vec4 aoColor = texture2D( tAO, vUv );",
  11225. "aoColor.xyz *= aoColor.xyz;",
  11226. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11227. "#else",
  11228. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11229. "#endif",
  11230. "}",
  11231. "if( enableSpecular )",
  11232. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11233. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11234. "vec3 finalNormal = tsb * normalTex;",
  11235. "#ifdef FLIP_SIDED",
  11236. "finalNormal = -finalNormal;",
  11237. "#endif",
  11238. "vec3 normal = normalize( finalNormal );",
  11239. "vec3 viewPosition = normalize( vViewPosition );",
  11240. // point lights
  11241. "#if MAX_POINT_LIGHTS > 0",
  11242. "vec3 pointDiffuse = vec3( 0.0 );",
  11243. "vec3 pointSpecular = vec3( 0.0 );",
  11244. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11245. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11246. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11247. "float pointDistance = 1.0;",
  11248. "if ( pointLightDistance[ i ] > 0.0 )",
  11249. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11250. "pointVector = normalize( pointVector );",
  11251. // diffuse
  11252. "#ifdef WRAP_AROUND",
  11253. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11254. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11255. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11256. "#else",
  11257. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11258. "#endif",
  11259. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11260. // specular
  11261. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11262. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11263. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11264. "#ifdef PHYSICALLY_BASED_SHADING",
  11265. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11266. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11267. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11268. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11269. "#else",
  11270. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11271. "#endif",
  11272. "}",
  11273. "#endif",
  11274. // spot lights
  11275. "#if MAX_SPOT_LIGHTS > 0",
  11276. "vec3 spotDiffuse = vec3( 0.0 );",
  11277. "vec3 spotSpecular = vec3( 0.0 );",
  11278. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11279. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11280. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11281. "float spotDistance = 1.0;",
  11282. "if ( spotLightDistance[ i ] > 0.0 )",
  11283. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11284. "spotVector = normalize( spotVector );",
  11285. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11286. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11287. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11288. // diffuse
  11289. "#ifdef WRAP_AROUND",
  11290. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11291. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11292. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11293. "#else",
  11294. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11295. "#endif",
  11296. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11297. // specular
  11298. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11299. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11300. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11301. "#ifdef PHYSICALLY_BASED_SHADING",
  11302. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11303. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11304. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11305. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11306. "#else",
  11307. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11308. "#endif",
  11309. "}",
  11310. "}",
  11311. "#endif",
  11312. // directional lights
  11313. "#if MAX_DIR_LIGHTS > 0",
  11314. "vec3 dirDiffuse = vec3( 0.0 );",
  11315. "vec3 dirSpecular = vec3( 0.0 );",
  11316. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11317. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11318. "vec3 dirVector = normalize( lDirection.xyz );",
  11319. // diffuse
  11320. "#ifdef WRAP_AROUND",
  11321. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11322. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11323. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11324. "#else",
  11325. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11326. "#endif",
  11327. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11328. // specular
  11329. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11330. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11331. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11332. "#ifdef PHYSICALLY_BASED_SHADING",
  11333. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11334. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11335. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11336. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11337. "#else",
  11338. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11339. "#endif",
  11340. "}",
  11341. "#endif",
  11342. // hemisphere lights
  11343. "#if MAX_HEMI_LIGHTS > 0",
  11344. "vec3 hemiDiffuse = vec3( 0.0 );",
  11345. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11346. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11347. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11348. "vec3 lVector = normalize( lDirection.xyz );",
  11349. // diffuse
  11350. "float dotProduct = dot( normal, lVector );",
  11351. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11352. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11353. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11354. // specular (sky light)
  11355. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11356. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11357. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11358. // specular (ground light)
  11359. "vec3 lVectorGround = -lVector;",
  11360. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11361. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11362. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11363. "#ifdef PHYSICALLY_BASED_SHADING",
  11364. "float dotProductGround = dot( normal, lVectorGround );",
  11365. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11366. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11367. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11368. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11369. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11370. "#else",
  11371. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11372. "#endif",
  11373. "}",
  11374. "#endif",
  11375. // all lights contribution summation
  11376. "vec3 totalDiffuse = vec3( 0.0 );",
  11377. "vec3 totalSpecular = vec3( 0.0 );",
  11378. "#if MAX_DIR_LIGHTS > 0",
  11379. "totalDiffuse += dirDiffuse;",
  11380. "totalSpecular += dirSpecular;",
  11381. "#endif",
  11382. "#if MAX_HEMI_LIGHTS > 0",
  11383. "totalDiffuse += hemiDiffuse;",
  11384. "totalSpecular += hemiSpecular;",
  11385. "#endif",
  11386. "#if MAX_POINT_LIGHTS > 0",
  11387. "totalDiffuse += pointDiffuse;",
  11388. "totalSpecular += pointSpecular;",
  11389. "#endif",
  11390. "#if MAX_SPOT_LIGHTS > 0",
  11391. "totalDiffuse += spotDiffuse;",
  11392. "totalSpecular += spotSpecular;",
  11393. "#endif",
  11394. "#ifdef METAL",
  11395. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11396. "#else",
  11397. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11398. "#endif",
  11399. "if ( enableReflection ) {",
  11400. "vec3 vReflect;",
  11401. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11402. "if ( useRefract ) {",
  11403. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11404. "} else {",
  11405. "vReflect = reflect( cameraToVertex, normal );",
  11406. "}",
  11407. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11408. "#ifdef GAMMA_INPUT",
  11409. "cubeColor.xyz *= cubeColor.xyz;",
  11410. "#endif",
  11411. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11412. "}",
  11413. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11414. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11415. THREE.ShaderChunk[ "fog_fragment" ],
  11416. "}"
  11417. ].join("\n"),
  11418. vertexShader: [
  11419. "attribute vec4 tangent;",
  11420. "uniform vec2 uOffset;",
  11421. "uniform vec2 uRepeat;",
  11422. "uniform bool enableDisplacement;",
  11423. "#ifdef VERTEX_TEXTURES",
  11424. "uniform sampler2D tDisplacement;",
  11425. "uniform float uDisplacementScale;",
  11426. "uniform float uDisplacementBias;",
  11427. "#endif",
  11428. "varying vec3 vTangent;",
  11429. "varying vec3 vBinormal;",
  11430. "varying vec3 vNormal;",
  11431. "varying vec2 vUv;",
  11432. "varying vec3 vWorldPosition;",
  11433. "varying vec3 vViewPosition;",
  11434. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11435. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11436. "void main() {",
  11437. THREE.ShaderChunk[ "skinbase_vertex" ],
  11438. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11439. // normal, tangent and binormal vectors
  11440. "#ifdef USE_SKINNING",
  11441. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11442. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11443. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11444. "#else",
  11445. "vNormal = normalize( normalMatrix * normal );",
  11446. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11447. "#endif",
  11448. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11449. "vUv = uv * uRepeat + uOffset;",
  11450. // displacement mapping
  11451. "vec3 displacedPosition;",
  11452. "#ifdef VERTEX_TEXTURES",
  11453. "if ( enableDisplacement ) {",
  11454. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11455. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11456. "displacedPosition = position + normalize( normal ) * df;",
  11457. "} else {",
  11458. "#ifdef USE_SKINNING",
  11459. "vec4 skinVertex = vec4( position, 1.0 );",
  11460. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11461. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11462. "displacedPosition = skinned.xyz;",
  11463. "#else",
  11464. "displacedPosition = position;",
  11465. "#endif",
  11466. "}",
  11467. "#else",
  11468. "#ifdef USE_SKINNING",
  11469. "vec4 skinVertex = vec4( position, 1.0 );",
  11470. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11471. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11472. "displacedPosition = skinned.xyz;",
  11473. "#else",
  11474. "displacedPosition = position;",
  11475. "#endif",
  11476. "#endif",
  11477. //
  11478. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11479. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11480. "gl_Position = projectionMatrix * mvPosition;",
  11481. //
  11482. "vWorldPosition = worldPosition.xyz;",
  11483. "vViewPosition = -mvPosition.xyz;",
  11484. // shadows
  11485. "#ifdef USE_SHADOWMAP",
  11486. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11487. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11488. "}",
  11489. "#endif",
  11490. "}"
  11491. ].join("\n")
  11492. },
  11493. /* -------------------------------------------------------------------------
  11494. // Cube map shader
  11495. ------------------------------------------------------------------------- */
  11496. 'cube': {
  11497. uniforms: { "tCube": { type: "t", value: null },
  11498. "tFlip": { type: "f", value: -1 } },
  11499. vertexShader: [
  11500. "varying vec3 vWorldPosition;",
  11501. "void main() {",
  11502. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11503. "vWorldPosition = worldPosition.xyz;",
  11504. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11505. "}"
  11506. ].join("\n"),
  11507. fragmentShader: [
  11508. "uniform samplerCube tCube;",
  11509. "uniform float tFlip;",
  11510. "varying vec3 vWorldPosition;",
  11511. "void main() {",
  11512. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11513. "}"
  11514. ].join("\n")
  11515. },
  11516. // Depth encoding into RGBA texture
  11517. // based on SpiderGL shadow map example
  11518. // http://spidergl.org/example.php?id=6
  11519. // originally from
  11520. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11521. // see also here:
  11522. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11523. 'depthRGBA': {
  11524. uniforms: {},
  11525. vertexShader: [
  11526. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11527. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11528. "void main() {",
  11529. THREE.ShaderChunk[ "skinbase_vertex" ],
  11530. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11531. THREE.ShaderChunk[ "skinning_vertex" ],
  11532. THREE.ShaderChunk[ "default_vertex" ],
  11533. "}"
  11534. ].join("\n"),
  11535. fragmentShader: [
  11536. "vec4 pack_depth( const in float depth ) {",
  11537. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11538. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11539. "vec4 res = fract( depth * bit_shift );",
  11540. "res -= res.xxyz * bit_mask;",
  11541. "return res;",
  11542. "}",
  11543. "void main() {",
  11544. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11545. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11546. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11547. //"gl_FragData[ 0 ] = pack_depth( z );",
  11548. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11549. "}"
  11550. ].join("\n")
  11551. }
  11552. };
  11553. /**
  11554. * @author supereggbert / http://www.paulbrunt.co.uk/
  11555. * @author mrdoob / http://mrdoob.com/
  11556. * @author alteredq / http://alteredqualia.com/
  11557. * @author szimek / https://github.com/szimek/
  11558. */
  11559. THREE.WebGLRenderer = function ( parameters ) {
  11560. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11561. parameters = parameters || {};
  11562. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11563. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11564. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11565. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11566. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11567. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11568. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11569. _clearColor = new THREE.Color( 0x000000 ),
  11570. _clearAlpha = 0;
  11571. // public properties
  11572. this.domElement = _canvas;
  11573. this.context = null;
  11574. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11575. ? parameters.devicePixelRatio
  11576. : self.devicePixelRatio !== undefined
  11577. ? self.devicePixelRatio
  11578. : 1;
  11579. // clearing
  11580. this.autoClear = true;
  11581. this.autoClearColor = true;
  11582. this.autoClearDepth = true;
  11583. this.autoClearStencil = true;
  11584. // scene graph
  11585. this.sortObjects = true;
  11586. this.autoUpdateObjects = true;
  11587. // physically based shading
  11588. this.gammaInput = false;
  11589. this.gammaOutput = false;
  11590. this.physicallyBasedShading = false;
  11591. // shadow map
  11592. this.shadowMapEnabled = false;
  11593. this.shadowMapAutoUpdate = true;
  11594. this.shadowMapType = THREE.PCFShadowMap;
  11595. this.shadowMapCullFace = THREE.CullFaceFront;
  11596. this.shadowMapDebug = false;
  11597. this.shadowMapCascade = false;
  11598. // morphs
  11599. this.maxMorphTargets = 8;
  11600. this.maxMorphNormals = 4;
  11601. // flags
  11602. this.autoScaleCubemaps = true;
  11603. // custom render plugins
  11604. this.renderPluginsPre = [];
  11605. this.renderPluginsPost = [];
  11606. // info
  11607. this.info = {
  11608. memory: {
  11609. programs: 0,
  11610. geometries: 0,
  11611. textures: 0
  11612. },
  11613. render: {
  11614. calls: 0,
  11615. vertices: 0,
  11616. faces: 0,
  11617. points: 0
  11618. }
  11619. };
  11620. // internal properties
  11621. var _this = this,
  11622. _programs = [],
  11623. _programs_counter = 0,
  11624. // internal state cache
  11625. _currentProgram = null,
  11626. _currentFramebuffer = null,
  11627. _currentMaterialId = -1,
  11628. _currentGeometryGroupHash = null,
  11629. _currentCamera = null,
  11630. _geometryGroupCounter = 0,
  11631. _usedTextureUnits = 0,
  11632. // GL state cache
  11633. _oldDoubleSided = -1,
  11634. _oldFlipSided = -1,
  11635. _oldBlending = -1,
  11636. _oldBlendEquation = -1,
  11637. _oldBlendSrc = -1,
  11638. _oldBlendDst = -1,
  11639. _oldDepthTest = -1,
  11640. _oldDepthWrite = -1,
  11641. _oldPolygonOffset = null,
  11642. _oldPolygonOffsetFactor = null,
  11643. _oldPolygonOffsetUnits = null,
  11644. _oldLineWidth = null,
  11645. _viewportX = 0,
  11646. _viewportY = 0,
  11647. _viewportWidth = _canvas.width,
  11648. _viewportHeight = _canvas.height,
  11649. _currentWidth = 0,
  11650. _currentHeight = 0,
  11651. _enabledAttributes = {},
  11652. // frustum
  11653. _frustum = new THREE.Frustum(),
  11654. // camera matrices cache
  11655. _projScreenMatrix = new THREE.Matrix4(),
  11656. _projScreenMatrixPS = new THREE.Matrix4(),
  11657. _vector3 = new THREE.Vector3(),
  11658. // light arrays cache
  11659. _direction = new THREE.Vector3(),
  11660. _lightsNeedUpdate = true,
  11661. _lights = {
  11662. ambient: [ 0, 0, 0 ],
  11663. directional: { length: 0, colors: new Array(), positions: new Array() },
  11664. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11665. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11666. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11667. };
  11668. // initialize
  11669. var _gl;
  11670. var _glExtensionTextureFloat;
  11671. var _glExtensionTextureFloatLinear;
  11672. var _glExtensionStandardDerivatives;
  11673. var _glExtensionTextureFilterAnisotropic;
  11674. var _glExtensionCompressedTextureS3TC;
  11675. initGL();
  11676. setDefaultGLState();
  11677. this.context = _gl;
  11678. // GPU capabilities
  11679. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11680. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11681. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11682. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11683. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11684. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11685. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11686. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11687. //
  11688. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11689. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11690. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11691. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11692. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11693. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11694. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11695. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11696. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11697. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11698. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11699. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11700. // clamp precision to maximum available
  11701. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11702. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11703. if ( _precision === "highp" && ! highpAvailable ) {
  11704. if ( mediumpAvailable ) {
  11705. _precision = "mediump";
  11706. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11707. } else {
  11708. _precision = "lowp";
  11709. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11710. }
  11711. }
  11712. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11713. _precision = "lowp";
  11714. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11715. }
  11716. // API
  11717. this.getContext = function () {
  11718. return _gl;
  11719. };
  11720. this.supportsVertexTextures = function () {
  11721. return _supportsVertexTextures;
  11722. };
  11723. this.supportsFloatTextures = function () {
  11724. return _glExtensionTextureFloat;
  11725. };
  11726. this.supportsStandardDerivatives = function () {
  11727. return _glExtensionStandardDerivatives;
  11728. };
  11729. this.supportsCompressedTextureS3TC = function () {
  11730. return _glExtensionCompressedTextureS3TC;
  11731. };
  11732. this.getMaxAnisotropy = function () {
  11733. return _maxAnisotropy;
  11734. };
  11735. this.getPrecision = function () {
  11736. return _precision;
  11737. };
  11738. this.setSize = function ( width, height, updateStyle ) {
  11739. _canvas.width = width * this.devicePixelRatio;
  11740. _canvas.height = height * this.devicePixelRatio;
  11741. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11742. _canvas.style.width = width + 'px';
  11743. _canvas.style.height = height + 'px';
  11744. }
  11745. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11746. };
  11747. this.setViewport = function ( x, y, width, height ) {
  11748. _viewportX = x !== undefined ? x : 0;
  11749. _viewportY = y !== undefined ? y : 0;
  11750. _viewportWidth = width !== undefined ? width : _canvas.width;
  11751. _viewportHeight = height !== undefined ? height : _canvas.height;
  11752. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11753. };
  11754. this.setScissor = function ( x, y, width, height ) {
  11755. _gl.scissor( x, y, width, height );
  11756. };
  11757. this.enableScissorTest = function ( enable ) {
  11758. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11759. };
  11760. // Clearing
  11761. this.setClearColor = function ( color, alpha ) {
  11762. _clearColor.set( color );
  11763. _clearAlpha = alpha !== undefined ? alpha : 1;
  11764. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11765. };
  11766. this.setClearColorHex = function ( hex, alpha ) {
  11767. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11768. this.setClearColor( hex, alpha );
  11769. };
  11770. this.getClearColor = function () {
  11771. return _clearColor;
  11772. };
  11773. this.getClearAlpha = function () {
  11774. return _clearAlpha;
  11775. };
  11776. this.clear = function ( color, depth, stencil ) {
  11777. var bits = 0;
  11778. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11779. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11780. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11781. _gl.clear( bits );
  11782. };
  11783. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11784. this.setRenderTarget( renderTarget );
  11785. this.clear( color, depth, stencil );
  11786. };
  11787. // Plugins
  11788. this.addPostPlugin = function ( plugin ) {
  11789. plugin.init( this );
  11790. this.renderPluginsPost.push( plugin );
  11791. };
  11792. this.addPrePlugin = function ( plugin ) {
  11793. plugin.init( this );
  11794. this.renderPluginsPre.push( plugin );
  11795. };
  11796. // Rendering
  11797. this.updateShadowMap = function ( scene, camera ) {
  11798. _currentProgram = null;
  11799. _oldBlending = -1;
  11800. _oldDepthTest = -1;
  11801. _oldDepthWrite = -1;
  11802. _currentGeometryGroupHash = -1;
  11803. _currentMaterialId = -1;
  11804. _lightsNeedUpdate = true;
  11805. _oldDoubleSided = -1;
  11806. _oldFlipSided = -1;
  11807. this.shadowMapPlugin.update( scene, camera );
  11808. };
  11809. // Internal functions
  11810. // Buffer allocation
  11811. function createParticleBuffers ( geometry ) {
  11812. geometry.__webglVertexBuffer = _gl.createBuffer();
  11813. geometry.__webglColorBuffer = _gl.createBuffer();
  11814. _this.info.memory.geometries ++;
  11815. };
  11816. function createLineBuffers ( geometry ) {
  11817. geometry.__webglVertexBuffer = _gl.createBuffer();
  11818. geometry.__webglColorBuffer = _gl.createBuffer();
  11819. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11820. _this.info.memory.geometries ++;
  11821. };
  11822. function createMeshBuffers ( geometryGroup ) {
  11823. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11824. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11825. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11826. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11827. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11828. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11829. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11830. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11831. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11832. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11833. var m, ml;
  11834. if ( geometryGroup.numMorphTargets ) {
  11835. geometryGroup.__webglMorphTargetsBuffers = [];
  11836. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11837. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11838. }
  11839. }
  11840. if ( geometryGroup.numMorphNormals ) {
  11841. geometryGroup.__webglMorphNormalsBuffers = [];
  11842. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11843. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11844. }
  11845. }
  11846. _this.info.memory.geometries ++;
  11847. };
  11848. // Events
  11849. var onGeometryDispose = function ( event ) {
  11850. var geometry = event.target;
  11851. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11852. deallocateGeometry( geometry );
  11853. };
  11854. var onTextureDispose = function ( event ) {
  11855. var texture = event.target;
  11856. texture.removeEventListener( 'dispose', onTextureDispose );
  11857. deallocateTexture( texture );
  11858. _this.info.memory.textures --;
  11859. };
  11860. var onRenderTargetDispose = function ( event ) {
  11861. var renderTarget = event.target;
  11862. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11863. deallocateRenderTarget( renderTarget );
  11864. _this.info.memory.textures --;
  11865. };
  11866. var onMaterialDispose = function ( event ) {
  11867. var material = event.target;
  11868. material.removeEventListener( 'dispose', onMaterialDispose );
  11869. deallocateMaterial( material );
  11870. };
  11871. // Buffer deallocation
  11872. var deleteBuffers = function ( geometry ) {
  11873. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11874. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11875. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11876. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11877. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11878. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11879. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11880. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11881. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11882. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11883. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11884. // custom attributes
  11885. if ( geometry.__webglCustomAttributesList !== undefined ) {
  11886. for ( var id in geometry.__webglCustomAttributesList ) {
  11887. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11888. }
  11889. }
  11890. _this.info.memory.geometries --;
  11891. };
  11892. var deallocateGeometry = function ( geometry ) {
  11893. geometry.__webglInit = undefined;
  11894. if ( geometry instanceof THREE.BufferGeometry ) {
  11895. var attributes = geometry.attributes;
  11896. for ( var key in attributes ) {
  11897. if ( attributes[ key ].buffer !== undefined ) {
  11898. _gl.deleteBuffer( attributes[ key ].buffer );
  11899. }
  11900. }
  11901. _this.info.memory.geometries --;
  11902. } else {
  11903. if ( geometry.geometryGroups !== undefined ) {
  11904. for ( var g in geometry.geometryGroups ) {
  11905. var geometryGroup = geometry.geometryGroups[ g ];
  11906. if ( geometryGroup.numMorphTargets !== undefined ) {
  11907. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11908. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11909. }
  11910. }
  11911. if ( geometryGroup.numMorphNormals !== undefined ) {
  11912. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11913. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11914. }
  11915. }
  11916. deleteBuffers( geometryGroup );
  11917. }
  11918. } else {
  11919. deleteBuffers( geometry );
  11920. }
  11921. }
  11922. };
  11923. var deallocateTexture = function ( texture ) {
  11924. if ( texture.image && texture.image.__webglTextureCube ) {
  11925. // cube texture
  11926. _gl.deleteTexture( texture.image.__webglTextureCube );
  11927. } else {
  11928. // 2D texture
  11929. if ( ! texture.__webglInit ) return;
  11930. texture.__webglInit = false;
  11931. _gl.deleteTexture( texture.__webglTexture );
  11932. }
  11933. };
  11934. var deallocateRenderTarget = function ( renderTarget ) {
  11935. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11936. _gl.deleteTexture( renderTarget.__webglTexture );
  11937. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11938. for ( var i = 0; i < 6; i ++ ) {
  11939. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11940. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11941. }
  11942. } else {
  11943. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11944. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11945. }
  11946. };
  11947. var deallocateMaterial = function ( material ) {
  11948. var program = material.program;
  11949. if ( program === undefined ) return;
  11950. material.program = undefined;
  11951. // only deallocate GL program if this was the last use of shared program
  11952. // assumed there is only single copy of any program in the _programs list
  11953. // (that's how it's constructed)
  11954. var i, il, programInfo;
  11955. var deleteProgram = false;
  11956. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11957. programInfo = _programs[ i ];
  11958. if ( programInfo.program === program ) {
  11959. programInfo.usedTimes --;
  11960. if ( programInfo.usedTimes === 0 ) {
  11961. deleteProgram = true;
  11962. }
  11963. break;
  11964. }
  11965. }
  11966. if ( deleteProgram === true ) {
  11967. // avoid using array.splice, this is costlier than creating new array from scratch
  11968. var newPrograms = [];
  11969. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11970. programInfo = _programs[ i ];
  11971. if ( programInfo.program !== program ) {
  11972. newPrograms.push( programInfo );
  11973. }
  11974. }
  11975. _programs = newPrograms;
  11976. _gl.deleteProgram( program );
  11977. _this.info.memory.programs --;
  11978. }
  11979. };
  11980. // Buffer initialization
  11981. function initCustomAttributes ( geometry, object ) {
  11982. var nvertices = geometry.vertices.length;
  11983. var material = object.material;
  11984. if ( material.attributes ) {
  11985. if ( geometry.__webglCustomAttributesList === undefined ) {
  11986. geometry.__webglCustomAttributesList = [];
  11987. }
  11988. for ( var a in material.attributes ) {
  11989. var attribute = material.attributes[ a ];
  11990. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11991. attribute.__webglInitialized = true;
  11992. var size = 1; // "f" and "i"
  11993. if ( attribute.type === "v2" ) size = 2;
  11994. else if ( attribute.type === "v3" ) size = 3;
  11995. else if ( attribute.type === "v4" ) size = 4;
  11996. else if ( attribute.type === "c" ) size = 3;
  11997. attribute.size = size;
  11998. attribute.array = new Float32Array( nvertices * size );
  11999. attribute.buffer = _gl.createBuffer();
  12000. attribute.buffer.belongsToAttribute = a;
  12001. attribute.needsUpdate = true;
  12002. }
  12003. geometry.__webglCustomAttributesList.push( attribute );
  12004. }
  12005. }
  12006. };
  12007. function initParticleBuffers ( geometry, object ) {
  12008. var nvertices = geometry.vertices.length;
  12009. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12010. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12011. geometry.__sortArray = [];
  12012. geometry.__webglParticleCount = nvertices;
  12013. initCustomAttributes ( geometry, object );
  12014. };
  12015. function initLineBuffers ( geometry, object ) {
  12016. var nvertices = geometry.vertices.length;
  12017. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12018. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12019. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12020. geometry.__webglLineCount = nvertices;
  12021. initCustomAttributes ( geometry, object );
  12022. };
  12023. function initMeshBuffers ( geometryGroup, object ) {
  12024. var geometry = object.geometry,
  12025. faces3 = geometryGroup.faces3,
  12026. nvertices = faces3.length * 3,
  12027. ntris = faces3.length * 1,
  12028. nlines = faces3.length * 3,
  12029. material = getBufferMaterial( object, geometryGroup ),
  12030. uvType = bufferGuessUVType( material ),
  12031. normalType = bufferGuessNormalType( material ),
  12032. vertexColorType = bufferGuessVertexColorType( material );
  12033. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12034. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12035. if ( normalType ) {
  12036. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12037. }
  12038. if ( geometry.hasTangents ) {
  12039. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12040. }
  12041. if ( vertexColorType ) {
  12042. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12043. }
  12044. if ( uvType ) {
  12045. if ( geometry.faceVertexUvs.length > 0 ) {
  12046. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12047. }
  12048. if ( geometry.faceVertexUvs.length > 1 ) {
  12049. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12050. }
  12051. }
  12052. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12053. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12054. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12055. }
  12056. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  12057. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  12058. var m, ml;
  12059. if ( geometryGroup.numMorphTargets ) {
  12060. geometryGroup.__morphTargetsArrays = [];
  12061. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12062. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12063. }
  12064. }
  12065. if ( geometryGroup.numMorphNormals ) {
  12066. geometryGroup.__morphNormalsArrays = [];
  12067. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12068. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12069. }
  12070. }
  12071. geometryGroup.__webglFaceCount = ntris * 3;
  12072. geometryGroup.__webglLineCount = nlines * 2;
  12073. // custom attributes
  12074. if ( material.attributes ) {
  12075. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12076. geometryGroup.__webglCustomAttributesList = [];
  12077. }
  12078. for ( var a in material.attributes ) {
  12079. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12080. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12081. var originalAttribute = material.attributes[ a ];
  12082. var attribute = {};
  12083. for ( var property in originalAttribute ) {
  12084. attribute[ property ] = originalAttribute[ property ];
  12085. }
  12086. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12087. attribute.__webglInitialized = true;
  12088. var size = 1; // "f" and "i"
  12089. if( attribute.type === "v2" ) size = 2;
  12090. else if( attribute.type === "v3" ) size = 3;
  12091. else if( attribute.type === "v4" ) size = 4;
  12092. else if( attribute.type === "c" ) size = 3;
  12093. attribute.size = size;
  12094. attribute.array = new Float32Array( nvertices * size );
  12095. attribute.buffer = _gl.createBuffer();
  12096. attribute.buffer.belongsToAttribute = a;
  12097. originalAttribute.needsUpdate = true;
  12098. attribute.__original = originalAttribute;
  12099. }
  12100. geometryGroup.__webglCustomAttributesList.push( attribute );
  12101. }
  12102. }
  12103. geometryGroup.__inittedArrays = true;
  12104. };
  12105. function getBufferMaterial( object, geometryGroup ) {
  12106. return object.material instanceof THREE.MeshFaceMaterial
  12107. ? object.material.materials[ geometryGroup.materialIndex ]
  12108. : object.material;
  12109. };
  12110. function materialNeedsSmoothNormals ( material ) {
  12111. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12112. };
  12113. function bufferGuessNormalType ( material ) {
  12114. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12115. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12116. return false;
  12117. }
  12118. if ( materialNeedsSmoothNormals( material ) ) {
  12119. return THREE.SmoothShading;
  12120. } else {
  12121. return THREE.FlatShading;
  12122. }
  12123. };
  12124. function bufferGuessVertexColorType( material ) {
  12125. if ( material.vertexColors ) {
  12126. return material.vertexColors;
  12127. }
  12128. return false;
  12129. };
  12130. function bufferGuessUVType( material ) {
  12131. // material must use some texture to require uvs
  12132. if ( material.map ||
  12133. material.lightMap ||
  12134. material.bumpMap ||
  12135. material.normalMap ||
  12136. material.specularMap ||
  12137. material instanceof THREE.ShaderMaterial ) {
  12138. return true;
  12139. }
  12140. return false;
  12141. };
  12142. //
  12143. function initDirectBuffers( geometry ) {
  12144. var a, attribute, type;
  12145. for ( a in geometry.attributes ) {
  12146. if ( a === "index" ) {
  12147. type = _gl.ELEMENT_ARRAY_BUFFER;
  12148. } else {
  12149. type = _gl.ARRAY_BUFFER;
  12150. }
  12151. attribute = geometry.attributes[ a ];
  12152. if ( attribute.numItems === undefined ) {
  12153. attribute.numItems = attribute.array.length;
  12154. }
  12155. attribute.buffer = _gl.createBuffer();
  12156. _gl.bindBuffer( type, attribute.buffer );
  12157. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12158. }
  12159. };
  12160. // Buffer setting
  12161. function setParticleBuffers ( geometry, hint, object ) {
  12162. var v, c, vertex, offset, index, color,
  12163. vertices = geometry.vertices,
  12164. vl = vertices.length,
  12165. colors = geometry.colors,
  12166. cl = colors.length,
  12167. vertexArray = geometry.__vertexArray,
  12168. colorArray = geometry.__colorArray,
  12169. sortArray = geometry.__sortArray,
  12170. dirtyVertices = geometry.verticesNeedUpdate,
  12171. dirtyElements = geometry.elementsNeedUpdate,
  12172. dirtyColors = geometry.colorsNeedUpdate,
  12173. customAttributes = geometry.__webglCustomAttributesList,
  12174. i, il,
  12175. a, ca, cal, value,
  12176. customAttribute;
  12177. if ( object.sortParticles ) {
  12178. _projScreenMatrixPS.copy( _projScreenMatrix );
  12179. _projScreenMatrixPS.multiply( object.matrixWorld );
  12180. for ( v = 0; v < vl; v ++ ) {
  12181. vertex = vertices[ v ];
  12182. _vector3.copy( vertex );
  12183. _vector3.applyProjection( _projScreenMatrixPS );
  12184. sortArray[ v ] = [ _vector3.z, v ];
  12185. }
  12186. sortArray.sort( numericalSort );
  12187. for ( v = 0; v < vl; v ++ ) {
  12188. vertex = vertices[ sortArray[v][1] ];
  12189. offset = v * 3;
  12190. vertexArray[ offset ] = vertex.x;
  12191. vertexArray[ offset + 1 ] = vertex.y;
  12192. vertexArray[ offset + 2 ] = vertex.z;
  12193. }
  12194. for ( c = 0; c < cl; c ++ ) {
  12195. offset = c * 3;
  12196. color = colors[ sortArray[c][1] ];
  12197. colorArray[ offset ] = color.r;
  12198. colorArray[ offset + 1 ] = color.g;
  12199. colorArray[ offset + 2 ] = color.b;
  12200. }
  12201. if ( customAttributes ) {
  12202. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12203. customAttribute = customAttributes[ i ];
  12204. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12205. offset = 0;
  12206. cal = customAttribute.value.length;
  12207. if ( customAttribute.size === 1 ) {
  12208. for ( ca = 0; ca < cal; ca ++ ) {
  12209. index = sortArray[ ca ][ 1 ];
  12210. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12211. }
  12212. } else if ( customAttribute.size === 2 ) {
  12213. for ( ca = 0; ca < cal; ca ++ ) {
  12214. index = sortArray[ ca ][ 1 ];
  12215. value = customAttribute.value[ index ];
  12216. customAttribute.array[ offset ] = value.x;
  12217. customAttribute.array[ offset + 1 ] = value.y;
  12218. offset += 2;
  12219. }
  12220. } else if ( customAttribute.size === 3 ) {
  12221. if ( customAttribute.type === "c" ) {
  12222. for ( ca = 0; ca < cal; ca ++ ) {
  12223. index = sortArray[ ca ][ 1 ];
  12224. value = customAttribute.value[ index ];
  12225. customAttribute.array[ offset ] = value.r;
  12226. customAttribute.array[ offset + 1 ] = value.g;
  12227. customAttribute.array[ offset + 2 ] = value.b;
  12228. offset += 3;
  12229. }
  12230. } else {
  12231. for ( ca = 0; ca < cal; ca ++ ) {
  12232. index = sortArray[ ca ][ 1 ];
  12233. value = customAttribute.value[ index ];
  12234. customAttribute.array[ offset ] = value.x;
  12235. customAttribute.array[ offset + 1 ] = value.y;
  12236. customAttribute.array[ offset + 2 ] = value.z;
  12237. offset += 3;
  12238. }
  12239. }
  12240. } else if ( customAttribute.size === 4 ) {
  12241. for ( ca = 0; ca < cal; ca ++ ) {
  12242. index = sortArray[ ca ][ 1 ];
  12243. value = customAttribute.value[ index ];
  12244. customAttribute.array[ offset ] = value.x;
  12245. customAttribute.array[ offset + 1 ] = value.y;
  12246. customAttribute.array[ offset + 2 ] = value.z;
  12247. customAttribute.array[ offset + 3 ] = value.w;
  12248. offset += 4;
  12249. }
  12250. }
  12251. }
  12252. }
  12253. } else {
  12254. if ( dirtyVertices ) {
  12255. for ( v = 0; v < vl; v ++ ) {
  12256. vertex = vertices[ v ];
  12257. offset = v * 3;
  12258. vertexArray[ offset ] = vertex.x;
  12259. vertexArray[ offset + 1 ] = vertex.y;
  12260. vertexArray[ offset + 2 ] = vertex.z;
  12261. }
  12262. }
  12263. if ( dirtyColors ) {
  12264. for ( c = 0; c < cl; c ++ ) {
  12265. color = colors[ c ];
  12266. offset = c * 3;
  12267. colorArray[ offset ] = color.r;
  12268. colorArray[ offset + 1 ] = color.g;
  12269. colorArray[ offset + 2 ] = color.b;
  12270. }
  12271. }
  12272. if ( customAttributes ) {
  12273. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12274. customAttribute = customAttributes[ i ];
  12275. if ( customAttribute.needsUpdate &&
  12276. ( customAttribute.boundTo === undefined ||
  12277. customAttribute.boundTo === "vertices") ) {
  12278. cal = customAttribute.value.length;
  12279. offset = 0;
  12280. if ( customAttribute.size === 1 ) {
  12281. for ( ca = 0; ca < cal; ca ++ ) {
  12282. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12283. }
  12284. } else if ( customAttribute.size === 2 ) {
  12285. for ( ca = 0; ca < cal; ca ++ ) {
  12286. value = customAttribute.value[ ca ];
  12287. customAttribute.array[ offset ] = value.x;
  12288. customAttribute.array[ offset + 1 ] = value.y;
  12289. offset += 2;
  12290. }
  12291. } else if ( customAttribute.size === 3 ) {
  12292. if ( customAttribute.type === "c" ) {
  12293. for ( ca = 0; ca < cal; ca ++ ) {
  12294. value = customAttribute.value[ ca ];
  12295. customAttribute.array[ offset ] = value.r;
  12296. customAttribute.array[ offset + 1 ] = value.g;
  12297. customAttribute.array[ offset + 2 ] = value.b;
  12298. offset += 3;
  12299. }
  12300. } else {
  12301. for ( ca = 0; ca < cal; ca ++ ) {
  12302. value = customAttribute.value[ ca ];
  12303. customAttribute.array[ offset ] = value.x;
  12304. customAttribute.array[ offset + 1 ] = value.y;
  12305. customAttribute.array[ offset + 2 ] = value.z;
  12306. offset += 3;
  12307. }
  12308. }
  12309. } else if ( customAttribute.size === 4 ) {
  12310. for ( ca = 0; ca < cal; ca ++ ) {
  12311. value = customAttribute.value[ ca ];
  12312. customAttribute.array[ offset ] = value.x;
  12313. customAttribute.array[ offset + 1 ] = value.y;
  12314. customAttribute.array[ offset + 2 ] = value.z;
  12315. customAttribute.array[ offset + 3 ] = value.w;
  12316. offset += 4;
  12317. }
  12318. }
  12319. }
  12320. }
  12321. }
  12322. }
  12323. if ( dirtyVertices || object.sortParticles ) {
  12324. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12325. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12326. }
  12327. if ( dirtyColors || object.sortParticles ) {
  12328. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12329. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12330. }
  12331. if ( customAttributes ) {
  12332. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12333. customAttribute = customAttributes[ i ];
  12334. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12335. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12336. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12337. }
  12338. }
  12339. }
  12340. };
  12341. function setLineBuffers ( geometry, hint ) {
  12342. var v, c, d, vertex, offset, color,
  12343. vertices = geometry.vertices,
  12344. colors = geometry.colors,
  12345. lineDistances = geometry.lineDistances,
  12346. vl = vertices.length,
  12347. cl = colors.length,
  12348. dl = lineDistances.length,
  12349. vertexArray = geometry.__vertexArray,
  12350. colorArray = geometry.__colorArray,
  12351. lineDistanceArray = geometry.__lineDistanceArray,
  12352. dirtyVertices = geometry.verticesNeedUpdate,
  12353. dirtyColors = geometry.colorsNeedUpdate,
  12354. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12355. customAttributes = geometry.__webglCustomAttributesList,
  12356. i, il,
  12357. a, ca, cal, value,
  12358. customAttribute;
  12359. if ( dirtyVertices ) {
  12360. for ( v = 0; v < vl; v ++ ) {
  12361. vertex = vertices[ v ];
  12362. offset = v * 3;
  12363. vertexArray[ offset ] = vertex.x;
  12364. vertexArray[ offset + 1 ] = vertex.y;
  12365. vertexArray[ offset + 2 ] = vertex.z;
  12366. }
  12367. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12368. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12369. }
  12370. if ( dirtyColors ) {
  12371. for ( c = 0; c < cl; c ++ ) {
  12372. color = colors[ c ];
  12373. offset = c * 3;
  12374. colorArray[ offset ] = color.r;
  12375. colorArray[ offset + 1 ] = color.g;
  12376. colorArray[ offset + 2 ] = color.b;
  12377. }
  12378. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12379. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12380. }
  12381. if ( dirtyLineDistances ) {
  12382. for ( d = 0; d < dl; d ++ ) {
  12383. lineDistanceArray[ d ] = lineDistances[ d ];
  12384. }
  12385. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12386. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12387. }
  12388. if ( customAttributes ) {
  12389. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12390. customAttribute = customAttributes[ i ];
  12391. if ( customAttribute.needsUpdate &&
  12392. ( customAttribute.boundTo === undefined ||
  12393. customAttribute.boundTo === "vertices" ) ) {
  12394. offset = 0;
  12395. cal = customAttribute.value.length;
  12396. if ( customAttribute.size === 1 ) {
  12397. for ( ca = 0; ca < cal; ca ++ ) {
  12398. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12399. }
  12400. } else if ( customAttribute.size === 2 ) {
  12401. for ( ca = 0; ca < cal; ca ++ ) {
  12402. value = customAttribute.value[ ca ];
  12403. customAttribute.array[ offset ] = value.x;
  12404. customAttribute.array[ offset + 1 ] = value.y;
  12405. offset += 2;
  12406. }
  12407. } else if ( customAttribute.size === 3 ) {
  12408. if ( customAttribute.type === "c" ) {
  12409. for ( ca = 0; ca < cal; ca ++ ) {
  12410. value = customAttribute.value[ ca ];
  12411. customAttribute.array[ offset ] = value.r;
  12412. customAttribute.array[ offset + 1 ] = value.g;
  12413. customAttribute.array[ offset + 2 ] = value.b;
  12414. offset += 3;
  12415. }
  12416. } else {
  12417. for ( ca = 0; ca < cal; ca ++ ) {
  12418. value = customAttribute.value[ ca ];
  12419. customAttribute.array[ offset ] = value.x;
  12420. customAttribute.array[ offset + 1 ] = value.y;
  12421. customAttribute.array[ offset + 2 ] = value.z;
  12422. offset += 3;
  12423. }
  12424. }
  12425. } else if ( customAttribute.size === 4 ) {
  12426. for ( ca = 0; ca < cal; ca ++ ) {
  12427. value = customAttribute.value[ ca ];
  12428. customAttribute.array[ offset ] = value.x;
  12429. customAttribute.array[ offset + 1 ] = value.y;
  12430. customAttribute.array[ offset + 2 ] = value.z;
  12431. customAttribute.array[ offset + 3 ] = value.w;
  12432. offset += 4;
  12433. }
  12434. }
  12435. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12436. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12437. }
  12438. }
  12439. }
  12440. };
  12441. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12442. if ( ! geometryGroup.__inittedArrays ) {
  12443. return;
  12444. }
  12445. var normalType = bufferGuessNormalType( material ),
  12446. vertexColorType = bufferGuessVertexColorType( material ),
  12447. uvType = bufferGuessUVType( material ),
  12448. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12449. var f, fl, fi, face,
  12450. vertexNormals, faceNormal, normal,
  12451. vertexColors, faceColor,
  12452. vertexTangents,
  12453. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12454. c1, c2, c3, c4,
  12455. sw1, sw2, sw3, sw4,
  12456. si1, si2, si3, si4,
  12457. sa1, sa2, sa3, sa4,
  12458. sb1, sb2, sb3, sb4,
  12459. m, ml, i, il,
  12460. vn, uvi, uv2i,
  12461. vk, vkl, vka,
  12462. nka, chf, faceVertexNormals,
  12463. a,
  12464. vertexIndex = 0,
  12465. offset = 0,
  12466. offset_uv = 0,
  12467. offset_uv2 = 0,
  12468. offset_face = 0,
  12469. offset_normal = 0,
  12470. offset_tangent = 0,
  12471. offset_line = 0,
  12472. offset_color = 0,
  12473. offset_skin = 0,
  12474. offset_morphTarget = 0,
  12475. offset_custom = 0,
  12476. offset_customSrc = 0,
  12477. value,
  12478. vertexArray = geometryGroup.__vertexArray,
  12479. uvArray = geometryGroup.__uvArray,
  12480. uv2Array = geometryGroup.__uv2Array,
  12481. normalArray = geometryGroup.__normalArray,
  12482. tangentArray = geometryGroup.__tangentArray,
  12483. colorArray = geometryGroup.__colorArray,
  12484. skinIndexArray = geometryGroup.__skinIndexArray,
  12485. skinWeightArray = geometryGroup.__skinWeightArray,
  12486. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12487. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12488. customAttributes = geometryGroup.__webglCustomAttributesList,
  12489. customAttribute,
  12490. faceArray = geometryGroup.__faceArray,
  12491. lineArray = geometryGroup.__lineArray,
  12492. geometry = object.geometry, // this is shared for all chunks
  12493. dirtyVertices = geometry.verticesNeedUpdate,
  12494. dirtyElements = geometry.elementsNeedUpdate,
  12495. dirtyUvs = geometry.uvsNeedUpdate,
  12496. dirtyNormals = geometry.normalsNeedUpdate,
  12497. dirtyTangents = geometry.tangentsNeedUpdate,
  12498. dirtyColors = geometry.colorsNeedUpdate,
  12499. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12500. vertices = geometry.vertices,
  12501. chunk_faces3 = geometryGroup.faces3,
  12502. obj_faces = geometry.faces,
  12503. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12504. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12505. obj_colors = geometry.colors,
  12506. obj_skinIndices = geometry.skinIndices,
  12507. obj_skinWeights = geometry.skinWeights,
  12508. morphTargets = geometry.morphTargets,
  12509. morphNormals = geometry.morphNormals;
  12510. if ( dirtyVertices ) {
  12511. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12512. face = obj_faces[ chunk_faces3[ f ] ];
  12513. v1 = vertices[ face.a ];
  12514. v2 = vertices[ face.b ];
  12515. v3 = vertices[ face.c ];
  12516. vertexArray[ offset ] = v1.x;
  12517. vertexArray[ offset + 1 ] = v1.y;
  12518. vertexArray[ offset + 2 ] = v1.z;
  12519. vertexArray[ offset + 3 ] = v2.x;
  12520. vertexArray[ offset + 4 ] = v2.y;
  12521. vertexArray[ offset + 5 ] = v2.z;
  12522. vertexArray[ offset + 6 ] = v3.x;
  12523. vertexArray[ offset + 7 ] = v3.y;
  12524. vertexArray[ offset + 8 ] = v3.z;
  12525. offset += 9;
  12526. }
  12527. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12528. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12529. }
  12530. if ( dirtyMorphTargets ) {
  12531. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12532. offset_morphTarget = 0;
  12533. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12534. chf = chunk_faces3[ f ];
  12535. face = obj_faces[ chf ];
  12536. // morph positions
  12537. v1 = morphTargets[ vk ].vertices[ face.a ];
  12538. v2 = morphTargets[ vk ].vertices[ face.b ];
  12539. v3 = morphTargets[ vk ].vertices[ face.c ];
  12540. vka = morphTargetsArrays[ vk ];
  12541. vka[ offset_morphTarget ] = v1.x;
  12542. vka[ offset_morphTarget + 1 ] = v1.y;
  12543. vka[ offset_morphTarget + 2 ] = v1.z;
  12544. vka[ offset_morphTarget + 3 ] = v2.x;
  12545. vka[ offset_morphTarget + 4 ] = v2.y;
  12546. vka[ offset_morphTarget + 5 ] = v2.z;
  12547. vka[ offset_morphTarget + 6 ] = v3.x;
  12548. vka[ offset_morphTarget + 7 ] = v3.y;
  12549. vka[ offset_morphTarget + 8 ] = v3.z;
  12550. // morph normals
  12551. if ( material.morphNormals ) {
  12552. if ( needsSmoothNormals ) {
  12553. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12554. n1 = faceVertexNormals.a;
  12555. n2 = faceVertexNormals.b;
  12556. n3 = faceVertexNormals.c;
  12557. } else {
  12558. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12559. n2 = n1;
  12560. n3 = n1;
  12561. }
  12562. nka = morphNormalsArrays[ vk ];
  12563. nka[ offset_morphTarget ] = n1.x;
  12564. nka[ offset_morphTarget + 1 ] = n1.y;
  12565. nka[ offset_morphTarget + 2 ] = n1.z;
  12566. nka[ offset_morphTarget + 3 ] = n2.x;
  12567. nka[ offset_morphTarget + 4 ] = n2.y;
  12568. nka[ offset_morphTarget + 5 ] = n2.z;
  12569. nka[ offset_morphTarget + 6 ] = n3.x;
  12570. nka[ offset_morphTarget + 7 ] = n3.y;
  12571. nka[ offset_morphTarget + 8 ] = n3.z;
  12572. }
  12573. //
  12574. offset_morphTarget += 9;
  12575. }
  12576. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12577. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12578. if ( material.morphNormals ) {
  12579. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12580. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12581. }
  12582. }
  12583. }
  12584. if ( obj_skinWeights.length ) {
  12585. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12586. face = obj_faces[ chunk_faces3[ f ] ];
  12587. // weights
  12588. sw1 = obj_skinWeights[ face.a ];
  12589. sw2 = obj_skinWeights[ face.b ];
  12590. sw3 = obj_skinWeights[ face.c ];
  12591. skinWeightArray[ offset_skin ] = sw1.x;
  12592. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12593. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12594. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12595. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12596. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12597. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12598. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12599. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12600. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12601. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12602. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12603. // indices
  12604. si1 = obj_skinIndices[ face.a ];
  12605. si2 = obj_skinIndices[ face.b ];
  12606. si3 = obj_skinIndices[ face.c ];
  12607. skinIndexArray[ offset_skin ] = si1.x;
  12608. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12609. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12610. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12611. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12612. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12613. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12614. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12615. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12616. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12617. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12618. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12619. offset_skin += 12;
  12620. }
  12621. if ( offset_skin > 0 ) {
  12622. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12623. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12624. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12625. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12626. }
  12627. }
  12628. if ( dirtyColors && vertexColorType ) {
  12629. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12630. face = obj_faces[ chunk_faces3[ f ] ];
  12631. vertexColors = face.vertexColors;
  12632. faceColor = face.color;
  12633. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12634. c1 = vertexColors[ 0 ];
  12635. c2 = vertexColors[ 1 ];
  12636. c3 = vertexColors[ 2 ];
  12637. } else {
  12638. c1 = faceColor;
  12639. c2 = faceColor;
  12640. c3 = faceColor;
  12641. }
  12642. colorArray[ offset_color ] = c1.r;
  12643. colorArray[ offset_color + 1 ] = c1.g;
  12644. colorArray[ offset_color + 2 ] = c1.b;
  12645. colorArray[ offset_color + 3 ] = c2.r;
  12646. colorArray[ offset_color + 4 ] = c2.g;
  12647. colorArray[ offset_color + 5 ] = c2.b;
  12648. colorArray[ offset_color + 6 ] = c3.r;
  12649. colorArray[ offset_color + 7 ] = c3.g;
  12650. colorArray[ offset_color + 8 ] = c3.b;
  12651. offset_color += 9;
  12652. }
  12653. if ( offset_color > 0 ) {
  12654. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12655. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12656. }
  12657. }
  12658. if ( dirtyTangents && geometry.hasTangents ) {
  12659. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12660. face = obj_faces[ chunk_faces3[ f ] ];
  12661. vertexTangents = face.vertexTangents;
  12662. t1 = vertexTangents[ 0 ];
  12663. t2 = vertexTangents[ 1 ];
  12664. t3 = vertexTangents[ 2 ];
  12665. tangentArray[ offset_tangent ] = t1.x;
  12666. tangentArray[ offset_tangent + 1 ] = t1.y;
  12667. tangentArray[ offset_tangent + 2 ] = t1.z;
  12668. tangentArray[ offset_tangent + 3 ] = t1.w;
  12669. tangentArray[ offset_tangent + 4 ] = t2.x;
  12670. tangentArray[ offset_tangent + 5 ] = t2.y;
  12671. tangentArray[ offset_tangent + 6 ] = t2.z;
  12672. tangentArray[ offset_tangent + 7 ] = t2.w;
  12673. tangentArray[ offset_tangent + 8 ] = t3.x;
  12674. tangentArray[ offset_tangent + 9 ] = t3.y;
  12675. tangentArray[ offset_tangent + 10 ] = t3.z;
  12676. tangentArray[ offset_tangent + 11 ] = t3.w;
  12677. offset_tangent += 12;
  12678. }
  12679. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12680. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12681. }
  12682. if ( dirtyNormals && normalType ) {
  12683. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12684. face = obj_faces[ chunk_faces3[ f ] ];
  12685. vertexNormals = face.vertexNormals;
  12686. faceNormal = face.normal;
  12687. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12688. for ( i = 0; i < 3; i ++ ) {
  12689. vn = vertexNormals[ i ];
  12690. normalArray[ offset_normal ] = vn.x;
  12691. normalArray[ offset_normal + 1 ] = vn.y;
  12692. normalArray[ offset_normal + 2 ] = vn.z;
  12693. offset_normal += 3;
  12694. }
  12695. } else {
  12696. for ( i = 0; i < 3; i ++ ) {
  12697. normalArray[ offset_normal ] = faceNormal.x;
  12698. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12699. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12700. offset_normal += 3;
  12701. }
  12702. }
  12703. }
  12704. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12705. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12706. }
  12707. if ( dirtyUvs && obj_uvs && uvType ) {
  12708. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12709. fi = chunk_faces3[ f ];
  12710. uv = obj_uvs[ fi ];
  12711. if ( uv === undefined ) continue;
  12712. for ( i = 0; i < 3; i ++ ) {
  12713. uvi = uv[ i ];
  12714. uvArray[ offset_uv ] = uvi.x;
  12715. uvArray[ offset_uv + 1 ] = uvi.y;
  12716. offset_uv += 2;
  12717. }
  12718. }
  12719. if ( offset_uv > 0 ) {
  12720. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12721. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12722. }
  12723. }
  12724. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12725. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12726. fi = chunk_faces3[ f ];
  12727. uv2 = obj_uvs2[ fi ];
  12728. if ( uv2 === undefined ) continue;
  12729. for ( i = 0; i < 3; i ++ ) {
  12730. uv2i = uv2[ i ];
  12731. uv2Array[ offset_uv2 ] = uv2i.x;
  12732. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12733. offset_uv2 += 2;
  12734. }
  12735. }
  12736. if ( offset_uv2 > 0 ) {
  12737. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12738. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12739. }
  12740. }
  12741. if ( dirtyElements ) {
  12742. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12743. faceArray[ offset_face ] = vertexIndex;
  12744. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12745. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12746. offset_face += 3;
  12747. lineArray[ offset_line ] = vertexIndex;
  12748. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12749. lineArray[ offset_line + 2 ] = vertexIndex;
  12750. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12751. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12752. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12753. offset_line += 6;
  12754. vertexIndex += 3;
  12755. }
  12756. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12757. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12758. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12759. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12760. }
  12761. if ( customAttributes ) {
  12762. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12763. customAttribute = customAttributes[ i ];
  12764. if ( ! customAttribute.__original.needsUpdate ) continue;
  12765. offset_custom = 0;
  12766. offset_customSrc = 0;
  12767. if ( customAttribute.size === 1 ) {
  12768. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12769. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12770. face = obj_faces[ chunk_faces3[ f ] ];
  12771. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12772. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12773. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12774. offset_custom += 3;
  12775. }
  12776. } else if ( customAttribute.boundTo === "faces" ) {
  12777. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12778. value = customAttribute.value[ chunk_faces3[ f ] ];
  12779. customAttribute.array[ offset_custom ] = value;
  12780. customAttribute.array[ offset_custom + 1 ] = value;
  12781. customAttribute.array[ offset_custom + 2 ] = value;
  12782. offset_custom += 3;
  12783. }
  12784. }
  12785. } else if ( customAttribute.size === 2 ) {
  12786. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12787. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12788. face = obj_faces[ chunk_faces3[ f ] ];
  12789. v1 = customAttribute.value[ face.a ];
  12790. v2 = customAttribute.value[ face.b ];
  12791. v3 = customAttribute.value[ face.c ];
  12792. customAttribute.array[ offset_custom ] = v1.x;
  12793. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12794. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12795. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12796. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12797. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12798. offset_custom += 6;
  12799. }
  12800. } else if ( customAttribute.boundTo === "faces" ) {
  12801. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12802. value = customAttribute.value[ chunk_faces3[ f ] ];
  12803. v1 = value;
  12804. v2 = value;
  12805. v3 = value;
  12806. customAttribute.array[ offset_custom ] = v1.x;
  12807. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12808. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12809. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12810. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12811. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12812. offset_custom += 6;
  12813. }
  12814. }
  12815. } else if ( customAttribute.size === 3 ) {
  12816. var pp;
  12817. if ( customAttribute.type === "c" ) {
  12818. pp = [ "r", "g", "b" ];
  12819. } else {
  12820. pp = [ "x", "y", "z" ];
  12821. }
  12822. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12823. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12824. face = obj_faces[ chunk_faces3[ f ] ];
  12825. v1 = customAttribute.value[ face.a ];
  12826. v2 = customAttribute.value[ face.b ];
  12827. v3 = customAttribute.value[ face.c ];
  12828. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12829. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12830. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12831. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12832. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12833. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12834. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12835. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12836. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12837. offset_custom += 9;
  12838. }
  12839. } else if ( customAttribute.boundTo === "faces" ) {
  12840. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12841. value = customAttribute.value[ chunk_faces3[ f ] ];
  12842. v1 = value;
  12843. v2 = value;
  12844. v3 = value;
  12845. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12846. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12847. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12848. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12849. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12850. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12851. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12852. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12853. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12854. offset_custom += 9;
  12855. }
  12856. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12857. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12858. value = customAttribute.value[ chunk_faces3[ f ] ];
  12859. v1 = value[ 0 ];
  12860. v2 = value[ 1 ];
  12861. v3 = value[ 2 ];
  12862. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12863. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12864. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12865. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12866. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12867. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12868. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12869. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12870. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12871. offset_custom += 9;
  12872. }
  12873. }
  12874. } else if ( customAttribute.size === 4 ) {
  12875. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12876. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12877. face = obj_faces[ chunk_faces3[ f ] ];
  12878. v1 = customAttribute.value[ face.a ];
  12879. v2 = customAttribute.value[ face.b ];
  12880. v3 = customAttribute.value[ face.c ];
  12881. customAttribute.array[ offset_custom ] = v1.x;
  12882. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12883. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12884. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12885. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12886. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12887. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12888. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12889. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12890. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12891. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12892. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12893. offset_custom += 12;
  12894. }
  12895. } else if ( customAttribute.boundTo === "faces" ) {
  12896. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12897. value = customAttribute.value[ chunk_faces3[ f ] ];
  12898. v1 = value;
  12899. v2 = value;
  12900. v3 = value;
  12901. customAttribute.array[ offset_custom ] = v1.x;
  12902. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12903. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12904. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12905. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12906. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12907. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12908. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12909. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12910. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12911. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12912. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12913. offset_custom += 12;
  12914. }
  12915. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12916. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12917. value = customAttribute.value[ chunk_faces3[ f ] ];
  12918. v1 = value[ 0 ];
  12919. v2 = value[ 1 ];
  12920. v3 = value[ 2 ];
  12921. customAttribute.array[ offset_custom ] = v1.x;
  12922. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12923. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12924. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12925. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12926. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12927. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12928. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12929. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12930. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12931. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12932. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12933. offset_custom += 12;
  12934. }
  12935. }
  12936. }
  12937. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12938. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12939. }
  12940. }
  12941. if ( dispose ) {
  12942. delete geometryGroup.__inittedArrays;
  12943. delete geometryGroup.__colorArray;
  12944. delete geometryGroup.__normalArray;
  12945. delete geometryGroup.__tangentArray;
  12946. delete geometryGroup.__uvArray;
  12947. delete geometryGroup.__uv2Array;
  12948. delete geometryGroup.__faceArray;
  12949. delete geometryGroup.__vertexArray;
  12950. delete geometryGroup.__lineArray;
  12951. delete geometryGroup.__skinIndexArray;
  12952. delete geometryGroup.__skinWeightArray;
  12953. }
  12954. };
  12955. function setDirectBuffers ( geometry, hint, dispose ) {
  12956. var attributes = geometry.attributes;
  12957. var attributeName, attributeItem;
  12958. for ( attributeName in attributes ) {
  12959. attributeItem = attributes[ attributeName ];
  12960. if ( attributeItem.needsUpdate ) {
  12961. if ( attributeName === 'index' ) {
  12962. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  12963. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  12964. } else {
  12965. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  12966. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  12967. }
  12968. attributeItem.needsUpdate = false;
  12969. }
  12970. if ( dispose && ! attributeItem.dynamic ) {
  12971. attributeItem.array = null;
  12972. }
  12973. }
  12974. };
  12975. // Buffer rendering
  12976. this.renderBufferImmediate = function ( object, program, material ) {
  12977. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12978. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12979. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12980. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12981. if ( object.hasPositions ) {
  12982. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12983. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12984. _gl.enableVertexAttribArray( program.attributes.position );
  12985. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12986. }
  12987. if ( object.hasNormals ) {
  12988. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12989. if ( material.shading === THREE.FlatShading ) {
  12990. var nx, ny, nz,
  12991. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12992. normalArray,
  12993. i, il = object.count * 3;
  12994. for( i = 0; i < il; i += 9 ) {
  12995. normalArray = object.normalArray;
  12996. nax = normalArray[ i ];
  12997. nay = normalArray[ i + 1 ];
  12998. naz = normalArray[ i + 2 ];
  12999. nbx = normalArray[ i + 3 ];
  13000. nby = normalArray[ i + 4 ];
  13001. nbz = normalArray[ i + 5 ];
  13002. ncx = normalArray[ i + 6 ];
  13003. ncy = normalArray[ i + 7 ];
  13004. ncz = normalArray[ i + 8 ];
  13005. nx = ( nax + nbx + ncx ) / 3;
  13006. ny = ( nay + nby + ncy ) / 3;
  13007. nz = ( naz + nbz + ncz ) / 3;
  13008. normalArray[ i ] = nx;
  13009. normalArray[ i + 1 ] = ny;
  13010. normalArray[ i + 2 ] = nz;
  13011. normalArray[ i + 3 ] = nx;
  13012. normalArray[ i + 4 ] = ny;
  13013. normalArray[ i + 5 ] = nz;
  13014. normalArray[ i + 6 ] = nx;
  13015. normalArray[ i + 7 ] = ny;
  13016. normalArray[ i + 8 ] = nz;
  13017. }
  13018. }
  13019. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13020. _gl.enableVertexAttribArray( program.attributes.normal );
  13021. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13022. }
  13023. if ( object.hasUvs && material.map ) {
  13024. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13025. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13026. _gl.enableVertexAttribArray( program.attributes.uv );
  13027. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13028. }
  13029. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13030. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13031. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13032. _gl.enableVertexAttribArray( program.attributes.color );
  13033. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13034. }
  13035. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13036. object.count = 0;
  13037. };
  13038. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13039. if ( material.visible === false ) return;
  13040. var linewidth, a, attribute;
  13041. var attributeItem, attributeName, attributePointer, attributeSize;
  13042. var program = setProgram( camera, lights, fog, material, object );
  13043. var programAttributes = program.attributes;
  13044. var geometryAttributes = geometry.attributes;
  13045. var updateBuffers = false,
  13046. wireframeBit = material.wireframe ? 1 : 0,
  13047. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13048. if ( geometryHash !== _currentGeometryGroupHash ) {
  13049. _currentGeometryGroupHash = geometryHash;
  13050. updateBuffers = true;
  13051. }
  13052. if ( updateBuffers ) {
  13053. disableAttributes();
  13054. }
  13055. // render mesh
  13056. if ( object instanceof THREE.Mesh ) {
  13057. var index = geometryAttributes[ "index" ];
  13058. // indexed triangles
  13059. if ( index ) {
  13060. var offsets = geometry.offsets;
  13061. // if there is more than 1 chunk
  13062. // must set attribute pointers to use new offsets for each chunk
  13063. // even if geometry and materials didn't change
  13064. if ( offsets.length > 1 ) updateBuffers = true;
  13065. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13066. var startIndex = offsets[ i ].index;
  13067. if ( updateBuffers ) {
  13068. for ( attributeName in programAttributes ) {
  13069. attributePointer = programAttributes[ attributeName ];
  13070. attributeItem = geometryAttributes[ attributeName ];
  13071. if ( attributePointer >= 0 ) {
  13072. if ( attributeItem ) {
  13073. attributeSize = attributeItem.itemSize;
  13074. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13075. enableAttribute( attributePointer );
  13076. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13077. } else if ( material.defaultAttributeValues ) {
  13078. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13079. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13080. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13081. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13082. }
  13083. }
  13084. }
  13085. }
  13086. // indices
  13087. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13088. }
  13089. // render indexed triangles
  13090. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13091. _this.info.render.calls ++;
  13092. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13093. _this.info.render.faces += offsets[ i ].count / 3;
  13094. }
  13095. // non-indexed triangles
  13096. } else {
  13097. if ( updateBuffers ) {
  13098. for ( attributeName in programAttributes ) {
  13099. if ( attributeName === 'index') continue;
  13100. attributePointer = programAttributes[ attributeName ];
  13101. attributeItem = geometryAttributes[ attributeName ];
  13102. if ( attributePointer >= 0 ) {
  13103. if ( attributeItem ) {
  13104. attributeSize = attributeItem.itemSize;
  13105. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13106. enableAttribute( attributePointer );
  13107. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13108. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13109. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13110. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13111. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13112. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13113. }
  13114. }
  13115. }
  13116. }
  13117. }
  13118. var position = geometry.attributes[ "position" ];
  13119. // render non-indexed triangles
  13120. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13121. _this.info.render.calls ++;
  13122. _this.info.render.vertices += position.numItems / 3;
  13123. _this.info.render.faces += position.numItems / 3 / 3;
  13124. }
  13125. // render particles
  13126. } else if ( object instanceof THREE.ParticleSystem ) {
  13127. if ( updateBuffers ) {
  13128. for ( attributeName in programAttributes ) {
  13129. attributePointer = programAttributes[ attributeName ];
  13130. attributeItem = geometryAttributes[ attributeName ];
  13131. if ( attributePointer >= 0 ) {
  13132. if ( attributeItem ) {
  13133. attributeSize = attributeItem.itemSize;
  13134. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13135. enableAttribute( attributePointer );
  13136. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13137. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13138. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13139. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13140. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13141. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13142. }
  13143. }
  13144. }
  13145. }
  13146. var position = geometryAttributes[ "position" ];
  13147. // render particles
  13148. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13149. _this.info.render.calls ++;
  13150. _this.info.render.points += position.numItems / 3;
  13151. }
  13152. } else if ( object instanceof THREE.Line ) {
  13153. if ( updateBuffers ) {
  13154. for ( attributeName in programAttributes ) {
  13155. attributePointer = programAttributes[ attributeName ];
  13156. attributeItem = geometryAttributes[ attributeName ];
  13157. if ( attributePointer >= 0 ) {
  13158. if ( attributeItem ) {
  13159. attributeSize = attributeItem.itemSize;
  13160. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13161. enableAttribute( attributePointer );
  13162. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13163. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13164. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13165. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13166. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13167. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13168. }
  13169. }
  13170. }
  13171. }
  13172. // render lines
  13173. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13174. setLineWidth( material.linewidth );
  13175. var position = geometryAttributes[ "position" ];
  13176. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13177. _this.info.render.calls ++;
  13178. _this.info.render.points += position.numItems;
  13179. }
  13180. }
  13181. };
  13182. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13183. if ( material.visible === false ) return;
  13184. var linewidth, a, attribute, i, il;
  13185. var program = setProgram( camera, lights, fog, material, object );
  13186. var attributes = program.attributes;
  13187. var updateBuffers = false,
  13188. wireframeBit = material.wireframe ? 1 : 0,
  13189. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13190. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13191. _currentGeometryGroupHash = geometryGroupHash;
  13192. updateBuffers = true;
  13193. }
  13194. if ( updateBuffers ) {
  13195. disableAttributes();
  13196. }
  13197. // vertices
  13198. if ( !material.morphTargets && attributes.position >= 0 ) {
  13199. if ( updateBuffers ) {
  13200. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13201. enableAttribute( attributes.position );
  13202. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13203. }
  13204. } else {
  13205. if ( object.morphTargetBase ) {
  13206. setupMorphTargets( material, geometryGroup, object );
  13207. }
  13208. }
  13209. if ( updateBuffers ) {
  13210. // custom attributes
  13211. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13212. if ( geometryGroup.__webglCustomAttributesList ) {
  13213. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13214. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13215. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13216. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13217. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13218. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13219. }
  13220. }
  13221. }
  13222. // colors
  13223. if ( attributes.color >= 0 ) {
  13224. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13225. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13226. enableAttribute( attributes.color );
  13227. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13228. } else if ( material.defaultAttributeValues ) {
  13229. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13230. }
  13231. }
  13232. // normals
  13233. if ( attributes.normal >= 0 ) {
  13234. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13235. enableAttribute( attributes.normal );
  13236. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13237. }
  13238. // tangents
  13239. if ( attributes.tangent >= 0 ) {
  13240. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13241. enableAttribute( attributes.tangent );
  13242. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13243. }
  13244. // uvs
  13245. if ( attributes.uv >= 0 ) {
  13246. if ( object.geometry.faceVertexUvs[0] ) {
  13247. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13248. enableAttribute( attributes.uv );
  13249. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13250. } else if ( material.defaultAttributeValues ) {
  13251. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13252. }
  13253. }
  13254. if ( attributes.uv2 >= 0 ) {
  13255. if ( object.geometry.faceVertexUvs[1] ) {
  13256. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13257. enableAttribute( attributes.uv2 );
  13258. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13259. } else if ( material.defaultAttributeValues ) {
  13260. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13261. }
  13262. }
  13263. if ( material.skinning &&
  13264. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13265. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13266. enableAttribute( attributes.skinIndex );
  13267. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13268. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13269. enableAttribute( attributes.skinWeight );
  13270. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13271. }
  13272. // line distances
  13273. if ( attributes.lineDistance >= 0 ) {
  13274. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13275. enableAttribute( attributes.lineDistance );
  13276. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13277. }
  13278. }
  13279. // render mesh
  13280. if ( object instanceof THREE.Mesh ) {
  13281. // wireframe
  13282. if ( material.wireframe ) {
  13283. setLineWidth( material.wireframeLinewidth );
  13284. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13285. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13286. // triangles
  13287. } else {
  13288. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13289. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13290. }
  13291. _this.info.render.calls ++;
  13292. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13293. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13294. // render lines
  13295. } else if ( object instanceof THREE.Line ) {
  13296. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13297. setLineWidth( material.linewidth );
  13298. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13299. _this.info.render.calls ++;
  13300. // render particles
  13301. } else if ( object instanceof THREE.ParticleSystem ) {
  13302. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13303. _this.info.render.calls ++;
  13304. _this.info.render.points += geometryGroup.__webglParticleCount;
  13305. }
  13306. };
  13307. function enableAttribute( attribute ) {
  13308. if ( ! _enabledAttributes[ attribute ] ) {
  13309. _gl.enableVertexAttribArray( attribute );
  13310. _enabledAttributes[ attribute ] = true;
  13311. }
  13312. };
  13313. function disableAttributes() {
  13314. for ( var attribute in _enabledAttributes ) {
  13315. if ( _enabledAttributes[ attribute ] ) {
  13316. _gl.disableVertexAttribArray( attribute );
  13317. _enabledAttributes[ attribute ] = false;
  13318. }
  13319. }
  13320. };
  13321. function setupMorphTargets ( material, geometryGroup, object ) {
  13322. // set base
  13323. var attributes = material.program.attributes;
  13324. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13325. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13326. enableAttribute( attributes.position );
  13327. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13328. } else if ( attributes.position >= 0 ) {
  13329. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13330. enableAttribute( attributes.position );
  13331. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13332. }
  13333. if ( object.morphTargetForcedOrder.length ) {
  13334. // set forced order
  13335. var m = 0;
  13336. var order = object.morphTargetForcedOrder;
  13337. var influences = object.morphTargetInfluences;
  13338. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13339. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13340. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13341. enableAttribute( attributes[ "morphTarget" + m ] );
  13342. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13343. }
  13344. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13345. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13346. enableAttribute( attributes[ "morphNormal" + m ] );
  13347. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13348. }
  13349. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13350. m ++;
  13351. }
  13352. } else {
  13353. // find the most influencing
  13354. var influence, activeInfluenceIndices = [];
  13355. var influences = object.morphTargetInfluences;
  13356. var i, il = influences.length;
  13357. for ( i = 0; i < il; i ++ ) {
  13358. influence = influences[ i ];
  13359. if ( influence > 0 ) {
  13360. activeInfluenceIndices.push( [ influence, i ] );
  13361. }
  13362. }
  13363. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13364. activeInfluenceIndices.sort( numericalSort );
  13365. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13366. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13367. activeInfluenceIndices.sort( numericalSort );
  13368. } else if ( activeInfluenceIndices.length === 0 ) {
  13369. activeInfluenceIndices.push( [ 0, 0 ] );
  13370. };
  13371. var influenceIndex, m = 0;
  13372. while ( m < material.numSupportedMorphTargets ) {
  13373. if ( activeInfluenceIndices[ m ] ) {
  13374. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13375. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13376. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13377. enableAttribute( attributes[ "morphTarget" + m ] );
  13378. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13379. }
  13380. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13381. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13382. enableAttribute( attributes[ "morphNormal" + m ] );
  13383. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13384. }
  13385. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13386. } else {
  13387. /*
  13388. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13389. if ( material.morphNormals ) {
  13390. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13391. }
  13392. */
  13393. object.__webglMorphTargetInfluences[ m ] = 0;
  13394. }
  13395. m ++;
  13396. }
  13397. }
  13398. // load updated influences uniform
  13399. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13400. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13401. }
  13402. };
  13403. // Sorting
  13404. function painterSortStable ( a, b ) {
  13405. if ( a.z !== b.z ) {
  13406. return b.z - a.z;
  13407. } else {
  13408. return a.id - b.id;
  13409. }
  13410. };
  13411. function numericalSort ( a, b ) {
  13412. return b[ 0 ] - a[ 0 ];
  13413. };
  13414. // Rendering
  13415. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13416. if ( camera instanceof THREE.Camera === false ) {
  13417. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13418. return;
  13419. }
  13420. var i, il,
  13421. webglObject, object,
  13422. renderList,
  13423. lights = scene.__lights,
  13424. fog = scene.fog;
  13425. // reset caching for this frame
  13426. _currentMaterialId = -1;
  13427. _lightsNeedUpdate = true;
  13428. // update scene graph
  13429. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13430. // update camera matrices and frustum
  13431. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13432. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13433. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13434. _frustum.setFromMatrix( _projScreenMatrix );
  13435. // update WebGL objects
  13436. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13437. // custom render plugins (pre pass)
  13438. renderPlugins( this.renderPluginsPre, scene, camera );
  13439. //
  13440. _this.info.render.calls = 0;
  13441. _this.info.render.vertices = 0;
  13442. _this.info.render.faces = 0;
  13443. _this.info.render.points = 0;
  13444. this.setRenderTarget( renderTarget );
  13445. if ( this.autoClear || forceClear ) {
  13446. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13447. }
  13448. // set matrices for regular objects (frustum culled)
  13449. renderList = scene.__webglObjects;
  13450. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13451. webglObject = renderList[ i ];
  13452. object = webglObject.object;
  13453. webglObject.id = i;
  13454. webglObject.render = false;
  13455. if ( object.visible ) {
  13456. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13457. setupMatrices( object, camera );
  13458. unrollBufferMaterial( webglObject );
  13459. webglObject.render = true;
  13460. if ( this.sortObjects === true ) {
  13461. if ( object.renderDepth !== null ) {
  13462. webglObject.z = object.renderDepth;
  13463. } else {
  13464. _vector3.getPositionFromMatrix( object.matrixWorld );
  13465. _vector3.applyProjection( _projScreenMatrix );
  13466. webglObject.z = _vector3.z;
  13467. }
  13468. }
  13469. }
  13470. }
  13471. }
  13472. if ( this.sortObjects ) {
  13473. renderList.sort( painterSortStable );
  13474. }
  13475. // set matrices for immediate objects
  13476. renderList = scene.__webglObjectsImmediate;
  13477. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13478. webglObject = renderList[ i ];
  13479. object = webglObject.object;
  13480. if ( object.visible ) {
  13481. setupMatrices( object, camera );
  13482. unrollImmediateBufferMaterial( webglObject );
  13483. }
  13484. }
  13485. if ( scene.overrideMaterial ) {
  13486. var material = scene.overrideMaterial;
  13487. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13488. this.setDepthTest( material.depthTest );
  13489. this.setDepthWrite( material.depthWrite );
  13490. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13491. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13492. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13493. } else {
  13494. var material = null;
  13495. // opaque pass (front-to-back order)
  13496. this.setBlending( THREE.NoBlending );
  13497. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13498. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13499. // transparent pass (back-to-front order)
  13500. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13501. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13502. }
  13503. // custom render plugins (post pass)
  13504. renderPlugins( this.renderPluginsPost, scene, camera );
  13505. // Generate mipmap if we're using any kind of mipmap filtering
  13506. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13507. updateRenderTargetMipmap( renderTarget );
  13508. }
  13509. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13510. this.setDepthTest( true );
  13511. this.setDepthWrite( true );
  13512. // _gl.finish();
  13513. };
  13514. function renderPlugins( plugins, scene, camera ) {
  13515. if ( ! plugins.length ) return;
  13516. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13517. // reset state for plugin (to start from clean slate)
  13518. _currentProgram = null;
  13519. _currentCamera = null;
  13520. _oldBlending = -1;
  13521. _oldDepthTest = -1;
  13522. _oldDepthWrite = -1;
  13523. _oldDoubleSided = -1;
  13524. _oldFlipSided = -1;
  13525. _currentGeometryGroupHash = -1;
  13526. _currentMaterialId = -1;
  13527. _lightsNeedUpdate = true;
  13528. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13529. // reset state after plugin (anything could have changed)
  13530. _currentProgram = null;
  13531. _currentCamera = null;
  13532. _oldBlending = -1;
  13533. _oldDepthTest = -1;
  13534. _oldDepthWrite = -1;
  13535. _oldDoubleSided = -1;
  13536. _oldFlipSided = -1;
  13537. _currentGeometryGroupHash = -1;
  13538. _currentMaterialId = -1;
  13539. _lightsNeedUpdate = true;
  13540. }
  13541. };
  13542. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13543. var webglObject, object, buffer, material, start, end, delta;
  13544. if ( reverse ) {
  13545. start = renderList.length - 1;
  13546. end = -1;
  13547. delta = -1;
  13548. } else {
  13549. start = 0;
  13550. end = renderList.length;
  13551. delta = 1;
  13552. }
  13553. for ( var i = start; i !== end; i += delta ) {
  13554. webglObject = renderList[ i ];
  13555. if ( webglObject.render ) {
  13556. object = webglObject.object;
  13557. buffer = webglObject.buffer;
  13558. if ( overrideMaterial ) {
  13559. material = overrideMaterial;
  13560. } else {
  13561. material = webglObject[ materialType ];
  13562. if ( ! material ) continue;
  13563. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13564. _this.setDepthTest( material.depthTest );
  13565. _this.setDepthWrite( material.depthWrite );
  13566. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13567. }
  13568. _this.setMaterialFaces( material );
  13569. if ( buffer instanceof THREE.BufferGeometry ) {
  13570. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13571. } else {
  13572. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13573. }
  13574. }
  13575. }
  13576. };
  13577. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13578. var webglObject, object, material, program;
  13579. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13580. webglObject = renderList[ i ];
  13581. object = webglObject.object;
  13582. if ( object.visible ) {
  13583. if ( overrideMaterial ) {
  13584. material = overrideMaterial;
  13585. } else {
  13586. material = webglObject[ materialType ];
  13587. if ( ! material ) continue;
  13588. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13589. _this.setDepthTest( material.depthTest );
  13590. _this.setDepthWrite( material.depthWrite );
  13591. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13592. }
  13593. _this.renderImmediateObject( camera, lights, fog, material, object );
  13594. }
  13595. }
  13596. };
  13597. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13598. var program = setProgram( camera, lights, fog, material, object );
  13599. _currentGeometryGroupHash = -1;
  13600. _this.setMaterialFaces( material );
  13601. if ( object.immediateRenderCallback ) {
  13602. object.immediateRenderCallback( program, _gl, _frustum );
  13603. } else {
  13604. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13605. }
  13606. };
  13607. function unrollImmediateBufferMaterial ( globject ) {
  13608. var object = globject.object,
  13609. material = object.material;
  13610. if ( material.transparent ) {
  13611. globject.transparent = material;
  13612. globject.opaque = null;
  13613. } else {
  13614. globject.opaque = material;
  13615. globject.transparent = null;
  13616. }
  13617. };
  13618. function unrollBufferMaterial ( globject ) {
  13619. var object = globject.object,
  13620. buffer = globject.buffer,
  13621. material, materialIndex, meshMaterial;
  13622. meshMaterial = object.material;
  13623. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13624. materialIndex = buffer.materialIndex;
  13625. material = meshMaterial.materials[ materialIndex ];
  13626. if ( material.transparent ) {
  13627. globject.transparent = material;
  13628. globject.opaque = null;
  13629. } else {
  13630. globject.opaque = material;
  13631. globject.transparent = null;
  13632. }
  13633. } else {
  13634. material = meshMaterial;
  13635. if ( material ) {
  13636. if ( material.transparent ) {
  13637. globject.transparent = material;
  13638. globject.opaque = null;
  13639. } else {
  13640. globject.opaque = material;
  13641. globject.transparent = null;
  13642. }
  13643. }
  13644. }
  13645. };
  13646. // Geometry splitting
  13647. function sortFacesByMaterial ( geometry, material ) {
  13648. var f, fl, face, materialIndex, vertices,
  13649. groupHash, hash_map = {};
  13650. var numMorphTargets = geometry.morphTargets.length;
  13651. var numMorphNormals = geometry.morphNormals.length;
  13652. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13653. geometry.geometryGroups = {};
  13654. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13655. face = geometry.faces[ f ];
  13656. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13657. if ( hash_map[ materialIndex ] === undefined ) {
  13658. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13659. }
  13660. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13661. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13662. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13663. }
  13664. vertices = 3;
  13665. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13666. hash_map[ materialIndex ].counter += 1;
  13667. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13668. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13669. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13670. }
  13671. }
  13672. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13673. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13674. }
  13675. geometry.geometryGroupsList = [];
  13676. for ( var g in geometry.geometryGroups ) {
  13677. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13678. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13679. }
  13680. };
  13681. // Objects refresh
  13682. this.initWebGLObjects = function ( scene ) {
  13683. if ( !scene.__webglObjects ) {
  13684. scene.__webglObjects = [];
  13685. scene.__webglObjectsImmediate = [];
  13686. scene.__webglSprites = [];
  13687. scene.__webglFlares = [];
  13688. }
  13689. while ( scene.__objectsAdded.length ) {
  13690. addObject( scene.__objectsAdded[ 0 ], scene );
  13691. scene.__objectsAdded.splice( 0, 1 );
  13692. }
  13693. while ( scene.__objectsRemoved.length ) {
  13694. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13695. scene.__objectsRemoved.splice( 0, 1 );
  13696. }
  13697. // update must be called after objects adding / removal
  13698. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13699. var object = scene.__webglObjects[ o ].object;
  13700. // TODO: Remove this hack (WebGLRenderer refactoring)
  13701. if ( object.__webglInit === undefined ) {
  13702. if ( object.__webglActive !== undefined ) {
  13703. removeObject( object, scene );
  13704. }
  13705. addObject( object, scene );
  13706. }
  13707. updateObject( object );
  13708. }
  13709. };
  13710. // Objects adding
  13711. function addObject( object, scene ) {
  13712. var g, geometry, material, geometryGroup;
  13713. if ( object.__webglInit === undefined ) {
  13714. object.__webglInit = true;
  13715. object._modelViewMatrix = new THREE.Matrix4();
  13716. object._normalMatrix = new THREE.Matrix3();
  13717. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13718. object.geometry.__webglInit = true;
  13719. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13720. }
  13721. geometry = object.geometry;
  13722. if ( geometry === undefined ) {
  13723. // fail silently for now
  13724. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13725. initDirectBuffers( geometry );
  13726. } else if ( object instanceof THREE.Mesh ) {
  13727. material = object.material;
  13728. if ( geometry.geometryGroups === undefined ) {
  13729. sortFacesByMaterial( geometry, material );
  13730. }
  13731. // create separate VBOs per geometry chunk
  13732. for ( g in geometry.geometryGroups ) {
  13733. geometryGroup = geometry.geometryGroups[ g ];
  13734. // initialise VBO on the first access
  13735. if ( ! geometryGroup.__webglVertexBuffer ) {
  13736. createMeshBuffers( geometryGroup );
  13737. initMeshBuffers( geometryGroup, object );
  13738. geometry.verticesNeedUpdate = true;
  13739. geometry.morphTargetsNeedUpdate = true;
  13740. geometry.elementsNeedUpdate = true;
  13741. geometry.uvsNeedUpdate = true;
  13742. geometry.normalsNeedUpdate = true;
  13743. geometry.tangentsNeedUpdate = true;
  13744. geometry.colorsNeedUpdate = true;
  13745. }
  13746. }
  13747. } else if ( object instanceof THREE.Line ) {
  13748. if ( ! geometry.__webglVertexBuffer ) {
  13749. createLineBuffers( geometry );
  13750. initLineBuffers( geometry, object );
  13751. geometry.verticesNeedUpdate = true;
  13752. geometry.colorsNeedUpdate = true;
  13753. geometry.lineDistancesNeedUpdate = true;
  13754. }
  13755. } else if ( object instanceof THREE.ParticleSystem ) {
  13756. if ( ! geometry.__webglVertexBuffer ) {
  13757. createParticleBuffers( geometry );
  13758. initParticleBuffers( geometry, object );
  13759. geometry.verticesNeedUpdate = true;
  13760. geometry.colorsNeedUpdate = true;
  13761. }
  13762. }
  13763. }
  13764. if ( object.__webglActive === undefined ) {
  13765. if ( object instanceof THREE.Mesh ) {
  13766. geometry = object.geometry;
  13767. if ( geometry instanceof THREE.BufferGeometry ) {
  13768. addBuffer( scene.__webglObjects, geometry, object );
  13769. } else if ( geometry instanceof THREE.Geometry ) {
  13770. for ( g in geometry.geometryGroups ) {
  13771. geometryGroup = geometry.geometryGroups[ g ];
  13772. addBuffer( scene.__webglObjects, geometryGroup, object );
  13773. }
  13774. }
  13775. } else if ( object instanceof THREE.Line ||
  13776. object instanceof THREE.ParticleSystem ) {
  13777. geometry = object.geometry;
  13778. addBuffer( scene.__webglObjects, geometry, object );
  13779. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13780. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13781. } else if ( object instanceof THREE.Sprite ) {
  13782. scene.__webglSprites.push( object );
  13783. } else if ( object instanceof THREE.LensFlare ) {
  13784. scene.__webglFlares.push( object );
  13785. }
  13786. object.__webglActive = true;
  13787. }
  13788. };
  13789. function addBuffer( objlist, buffer, object ) {
  13790. objlist.push(
  13791. {
  13792. id: null,
  13793. buffer: buffer,
  13794. object: object,
  13795. opaque: null,
  13796. transparent: null,
  13797. z: 0
  13798. }
  13799. );
  13800. };
  13801. function addBufferImmediate( objlist, object ) {
  13802. objlist.push(
  13803. {
  13804. id: null,
  13805. object: object,
  13806. opaque: null,
  13807. transparent: null,
  13808. z: 0
  13809. }
  13810. );
  13811. };
  13812. // Objects updates
  13813. function updateObject( object ) {
  13814. var geometry = object.geometry,
  13815. geometryGroup, customAttributesDirty, material;
  13816. if ( geometry instanceof THREE.BufferGeometry ) {
  13817. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13818. } else if ( object instanceof THREE.Mesh ) {
  13819. // check all geometry groups
  13820. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13821. geometryGroup = geometry.geometryGroupsList[ i ];
  13822. material = getBufferMaterial( object, geometryGroup );
  13823. if ( geometry.buffersNeedUpdate ) {
  13824. initMeshBuffers( geometryGroup, object );
  13825. }
  13826. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13827. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13828. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13829. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13830. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13831. }
  13832. }
  13833. geometry.verticesNeedUpdate = false;
  13834. geometry.morphTargetsNeedUpdate = false;
  13835. geometry.elementsNeedUpdate = false;
  13836. geometry.uvsNeedUpdate = false;
  13837. geometry.normalsNeedUpdate = false;
  13838. geometry.colorsNeedUpdate = false;
  13839. geometry.tangentsNeedUpdate = false;
  13840. geometry.buffersNeedUpdate = false;
  13841. material.attributes && clearCustomAttributes( material );
  13842. } else if ( object instanceof THREE.Line ) {
  13843. material = getBufferMaterial( object, geometry );
  13844. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13845. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13846. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13847. }
  13848. geometry.verticesNeedUpdate = false;
  13849. geometry.colorsNeedUpdate = false;
  13850. geometry.lineDistancesNeedUpdate = false;
  13851. material.attributes && clearCustomAttributes( material );
  13852. } else if ( object instanceof THREE.ParticleSystem ) {
  13853. material = getBufferMaterial( object, geometry );
  13854. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13855. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13856. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13857. }
  13858. geometry.verticesNeedUpdate = false;
  13859. geometry.colorsNeedUpdate = false;
  13860. material.attributes && clearCustomAttributes( material );
  13861. }
  13862. };
  13863. // Objects updates - custom attributes check
  13864. function areCustomAttributesDirty( material ) {
  13865. for ( var a in material.attributes ) {
  13866. if ( material.attributes[ a ].needsUpdate ) return true;
  13867. }
  13868. return false;
  13869. };
  13870. function clearCustomAttributes( material ) {
  13871. for ( var a in material.attributes ) {
  13872. material.attributes[ a ].needsUpdate = false;
  13873. }
  13874. };
  13875. // Objects removal
  13876. function removeObject( object, scene ) {
  13877. if ( object instanceof THREE.Mesh ||
  13878. object instanceof THREE.ParticleSystem ||
  13879. object instanceof THREE.Line ) {
  13880. removeInstances( scene.__webglObjects, object );
  13881. } else if ( object instanceof THREE.Sprite ) {
  13882. removeInstancesDirect( scene.__webglSprites, object );
  13883. } else if ( object instanceof THREE.LensFlare ) {
  13884. removeInstancesDirect( scene.__webglFlares, object );
  13885. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13886. removeInstances( scene.__webglObjectsImmediate, object );
  13887. }
  13888. delete object.__webglActive;
  13889. };
  13890. function removeInstances( objlist, object ) {
  13891. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13892. if ( objlist[ o ].object === object ) {
  13893. objlist.splice( o, 1 );
  13894. }
  13895. }
  13896. };
  13897. function removeInstancesDirect( objlist, object ) {
  13898. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13899. if ( objlist[ o ] === object ) {
  13900. objlist.splice( o, 1 );
  13901. }
  13902. }
  13903. };
  13904. // Materials
  13905. this.initMaterial = function ( material, lights, fog, object ) {
  13906. material.addEventListener( 'dispose', onMaterialDispose );
  13907. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13908. if ( material instanceof THREE.MeshDepthMaterial ) {
  13909. shaderID = 'depth';
  13910. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13911. shaderID = 'normal';
  13912. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13913. shaderID = 'basic';
  13914. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13915. shaderID = 'lambert';
  13916. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13917. shaderID = 'phong';
  13918. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13919. shaderID = 'basic';
  13920. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13921. shaderID = 'dashed';
  13922. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  13923. shaderID = 'particle_basic';
  13924. }
  13925. if ( shaderID ) {
  13926. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13927. }
  13928. // heuristics to create shader parameters according to lights in the scene
  13929. // (not to blow over maxLights budget)
  13930. maxLightCount = allocateLights( lights );
  13931. maxShadows = allocateShadows( lights );
  13932. maxBones = allocateBones( object );
  13933. parameters = {
  13934. map: !!material.map,
  13935. envMap: !!material.envMap,
  13936. lightMap: !!material.lightMap,
  13937. bumpMap: !!material.bumpMap,
  13938. normalMap: !!material.normalMap,
  13939. specularMap: !!material.specularMap,
  13940. vertexColors: material.vertexColors,
  13941. fog: fog,
  13942. useFog: material.fog,
  13943. fogExp: fog instanceof THREE.FogExp2,
  13944. sizeAttenuation: material.sizeAttenuation,
  13945. skinning: material.skinning,
  13946. maxBones: maxBones,
  13947. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13948. morphTargets: material.morphTargets,
  13949. morphNormals: material.morphNormals,
  13950. maxMorphTargets: this.maxMorphTargets,
  13951. maxMorphNormals: this.maxMorphNormals,
  13952. maxDirLights: maxLightCount.directional,
  13953. maxPointLights: maxLightCount.point,
  13954. maxSpotLights: maxLightCount.spot,
  13955. maxHemiLights: maxLightCount.hemi,
  13956. maxShadows: maxShadows,
  13957. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13958. shadowMapType: this.shadowMapType,
  13959. shadowMapDebug: this.shadowMapDebug,
  13960. shadowMapCascade: this.shadowMapCascade,
  13961. alphaTest: material.alphaTest,
  13962. metal: material.metal,
  13963. perPixel: material.perPixel,
  13964. wrapAround: material.wrapAround,
  13965. doubleSided: material.side === THREE.DoubleSide,
  13966. flipSided: material.side === THREE.BackSide
  13967. };
  13968. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  13969. var attributes = material.program.attributes;
  13970. if ( material.morphTargets ) {
  13971. material.numSupportedMorphTargets = 0;
  13972. var id, base = "morphTarget";
  13973. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13974. id = base + i;
  13975. if ( attributes[ id ] >= 0 ) {
  13976. material.numSupportedMorphTargets ++;
  13977. }
  13978. }
  13979. }
  13980. if ( material.morphNormals ) {
  13981. material.numSupportedMorphNormals = 0;
  13982. var id, base = "morphNormal";
  13983. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13984. id = base + i;
  13985. if ( attributes[ id ] >= 0 ) {
  13986. material.numSupportedMorphNormals ++;
  13987. }
  13988. }
  13989. }
  13990. material.uniformsList = [];
  13991. for ( u in material.uniforms ) {
  13992. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13993. }
  13994. };
  13995. function setMaterialShaders( material, shaders ) {
  13996. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13997. material.vertexShader = shaders.vertexShader;
  13998. material.fragmentShader = shaders.fragmentShader;
  13999. };
  14000. function setProgram( camera, lights, fog, material, object ) {
  14001. _usedTextureUnits = 0;
  14002. if ( material.needsUpdate ) {
  14003. if ( material.program ) deallocateMaterial( material );
  14004. _this.initMaterial( material, lights, fog, object );
  14005. material.needsUpdate = false;
  14006. }
  14007. if ( material.morphTargets ) {
  14008. if ( ! object.__webglMorphTargetInfluences ) {
  14009. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14010. }
  14011. }
  14012. var refreshMaterial = false;
  14013. var program = material.program,
  14014. p_uniforms = program.uniforms,
  14015. m_uniforms = material.uniforms;
  14016. if ( program !== _currentProgram ) {
  14017. _gl.useProgram( program );
  14018. _currentProgram = program;
  14019. refreshMaterial = true;
  14020. }
  14021. if ( material.id !== _currentMaterialId ) {
  14022. _currentMaterialId = material.id;
  14023. refreshMaterial = true;
  14024. }
  14025. if ( refreshMaterial || camera !== _currentCamera ) {
  14026. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14027. if ( camera !== _currentCamera ) _currentCamera = camera;
  14028. }
  14029. // skinning uniforms must be set even if material didn't change
  14030. // auto-setting of texture unit for bone texture must go before other textures
  14031. // not sure why, but otherwise weird things happen
  14032. if ( material.skinning ) {
  14033. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14034. if ( p_uniforms.boneTexture !== null ) {
  14035. var textureUnit = getTextureUnit();
  14036. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14037. _this.setTexture( object.boneTexture, textureUnit );
  14038. }
  14039. if ( p_uniforms.boneTextureWidth !== null ) {
  14040. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14041. }
  14042. if ( p_uniforms.boneTextureHeight !== null ) {
  14043. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14044. }
  14045. } else {
  14046. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14047. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14048. }
  14049. }
  14050. }
  14051. if ( refreshMaterial ) {
  14052. // refresh uniforms common to several materials
  14053. if ( fog && material.fog ) {
  14054. refreshUniformsFog( m_uniforms, fog );
  14055. }
  14056. if ( material instanceof THREE.MeshPhongMaterial ||
  14057. material instanceof THREE.MeshLambertMaterial ||
  14058. material.lights ) {
  14059. if ( _lightsNeedUpdate ) {
  14060. setupLights( program, lights );
  14061. _lightsNeedUpdate = false;
  14062. }
  14063. refreshUniformsLights( m_uniforms, _lights );
  14064. }
  14065. if ( material instanceof THREE.MeshBasicMaterial ||
  14066. material instanceof THREE.MeshLambertMaterial ||
  14067. material instanceof THREE.MeshPhongMaterial ) {
  14068. refreshUniformsCommon( m_uniforms, material );
  14069. }
  14070. // refresh single material specific uniforms
  14071. if ( material instanceof THREE.LineBasicMaterial ) {
  14072. refreshUniformsLine( m_uniforms, material );
  14073. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14074. refreshUniformsLine( m_uniforms, material );
  14075. refreshUniformsDash( m_uniforms, material );
  14076. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14077. refreshUniformsParticle( m_uniforms, material );
  14078. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14079. refreshUniformsPhong( m_uniforms, material );
  14080. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14081. refreshUniformsLambert( m_uniforms, material );
  14082. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14083. m_uniforms.mNear.value = camera.near;
  14084. m_uniforms.mFar.value = camera.far;
  14085. m_uniforms.opacity.value = material.opacity;
  14086. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14087. m_uniforms.opacity.value = material.opacity;
  14088. }
  14089. if ( object.receiveShadow && ! material._shadowPass ) {
  14090. refreshUniformsShadow( m_uniforms, lights );
  14091. }
  14092. // load common uniforms
  14093. loadUniformsGeneric( program, material.uniformsList );
  14094. // load material specific uniforms
  14095. // (shader material also gets them for the sake of genericity)
  14096. if ( material instanceof THREE.ShaderMaterial ||
  14097. material instanceof THREE.MeshPhongMaterial ||
  14098. material.envMap ) {
  14099. if ( p_uniforms.cameraPosition !== null ) {
  14100. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14101. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14102. }
  14103. }
  14104. if ( material instanceof THREE.MeshPhongMaterial ||
  14105. material instanceof THREE.MeshLambertMaterial ||
  14106. material instanceof THREE.ShaderMaterial ||
  14107. material.skinning ) {
  14108. if ( p_uniforms.viewMatrix !== null ) {
  14109. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14110. }
  14111. }
  14112. }
  14113. loadUniformsMatrices( p_uniforms, object );
  14114. if ( p_uniforms.modelMatrix !== null ) {
  14115. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14116. }
  14117. return program;
  14118. };
  14119. // Uniforms (refresh uniforms objects)
  14120. function refreshUniformsCommon ( uniforms, material ) {
  14121. uniforms.opacity.value = material.opacity;
  14122. if ( _this.gammaInput ) {
  14123. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14124. } else {
  14125. uniforms.diffuse.value = material.color;
  14126. }
  14127. uniforms.map.value = material.map;
  14128. uniforms.lightMap.value = material.lightMap;
  14129. uniforms.specularMap.value = material.specularMap;
  14130. if ( material.bumpMap ) {
  14131. uniforms.bumpMap.value = material.bumpMap;
  14132. uniforms.bumpScale.value = material.bumpScale;
  14133. }
  14134. if ( material.normalMap ) {
  14135. uniforms.normalMap.value = material.normalMap;
  14136. uniforms.normalScale.value.copy( material.normalScale );
  14137. }
  14138. // uv repeat and offset setting priorities
  14139. // 1. color map
  14140. // 2. specular map
  14141. // 3. normal map
  14142. // 4. bump map
  14143. var uvScaleMap;
  14144. if ( material.map ) {
  14145. uvScaleMap = material.map;
  14146. } else if ( material.specularMap ) {
  14147. uvScaleMap = material.specularMap;
  14148. } else if ( material.normalMap ) {
  14149. uvScaleMap = material.normalMap;
  14150. } else if ( material.bumpMap ) {
  14151. uvScaleMap = material.bumpMap;
  14152. }
  14153. if ( uvScaleMap !== undefined ) {
  14154. var offset = uvScaleMap.offset;
  14155. var repeat = uvScaleMap.repeat;
  14156. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14157. }
  14158. uniforms.envMap.value = material.envMap;
  14159. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14160. if ( _this.gammaInput ) {
  14161. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14162. uniforms.reflectivity.value = material.reflectivity;
  14163. } else {
  14164. uniforms.reflectivity.value = material.reflectivity;
  14165. }
  14166. uniforms.refractionRatio.value = material.refractionRatio;
  14167. uniforms.combine.value = material.combine;
  14168. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14169. };
  14170. function refreshUniformsLine ( uniforms, material ) {
  14171. uniforms.diffuse.value = material.color;
  14172. uniforms.opacity.value = material.opacity;
  14173. };
  14174. function refreshUniformsDash ( uniforms, material ) {
  14175. uniforms.dashSize.value = material.dashSize;
  14176. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14177. uniforms.scale.value = material.scale;
  14178. };
  14179. function refreshUniformsParticle ( uniforms, material ) {
  14180. uniforms.psColor.value = material.color;
  14181. uniforms.opacity.value = material.opacity;
  14182. uniforms.size.value = material.size;
  14183. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14184. uniforms.map.value = material.map;
  14185. };
  14186. function refreshUniformsFog ( uniforms, fog ) {
  14187. uniforms.fogColor.value = fog.color;
  14188. if ( fog instanceof THREE.Fog ) {
  14189. uniforms.fogNear.value = fog.near;
  14190. uniforms.fogFar.value = fog.far;
  14191. } else if ( fog instanceof THREE.FogExp2 ) {
  14192. uniforms.fogDensity.value = fog.density;
  14193. }
  14194. };
  14195. function refreshUniformsPhong ( uniforms, material ) {
  14196. uniforms.shininess.value = material.shininess;
  14197. if ( _this.gammaInput ) {
  14198. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14199. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14200. uniforms.specular.value.copyGammaToLinear( material.specular );
  14201. } else {
  14202. uniforms.ambient.value = material.ambient;
  14203. uniforms.emissive.value = material.emissive;
  14204. uniforms.specular.value = material.specular;
  14205. }
  14206. if ( material.wrapAround ) {
  14207. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14208. }
  14209. };
  14210. function refreshUniformsLambert ( uniforms, material ) {
  14211. if ( _this.gammaInput ) {
  14212. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14213. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14214. } else {
  14215. uniforms.ambient.value = material.ambient;
  14216. uniforms.emissive.value = material.emissive;
  14217. }
  14218. if ( material.wrapAround ) {
  14219. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14220. }
  14221. };
  14222. function refreshUniformsLights ( uniforms, lights ) {
  14223. uniforms.ambientLightColor.value = lights.ambient;
  14224. uniforms.directionalLightColor.value = lights.directional.colors;
  14225. uniforms.directionalLightDirection.value = lights.directional.positions;
  14226. uniforms.pointLightColor.value = lights.point.colors;
  14227. uniforms.pointLightPosition.value = lights.point.positions;
  14228. uniforms.pointLightDistance.value = lights.point.distances;
  14229. uniforms.spotLightColor.value = lights.spot.colors;
  14230. uniforms.spotLightPosition.value = lights.spot.positions;
  14231. uniforms.spotLightDistance.value = lights.spot.distances;
  14232. uniforms.spotLightDirection.value = lights.spot.directions;
  14233. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14234. uniforms.spotLightExponent.value = lights.spot.exponents;
  14235. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14236. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14237. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14238. };
  14239. function refreshUniformsShadow ( uniforms, lights ) {
  14240. if ( uniforms.shadowMatrix ) {
  14241. var j = 0;
  14242. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14243. var light = lights[ i ];
  14244. if ( ! light.castShadow ) continue;
  14245. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14246. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14247. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14248. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14249. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14250. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14251. j ++;
  14252. }
  14253. }
  14254. }
  14255. };
  14256. // Uniforms (load to GPU)
  14257. function loadUniformsMatrices ( uniforms, object ) {
  14258. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14259. if ( uniforms.normalMatrix ) {
  14260. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14261. }
  14262. };
  14263. function getTextureUnit() {
  14264. var textureUnit = _usedTextureUnits;
  14265. if ( textureUnit >= _maxTextures ) {
  14266. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14267. }
  14268. _usedTextureUnits += 1;
  14269. return textureUnit;
  14270. };
  14271. function loadUniformsGeneric ( program, uniforms ) {
  14272. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14273. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14274. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14275. if ( !location ) continue;
  14276. uniform = uniforms[ j ][ 0 ];
  14277. type = uniform.type;
  14278. value = uniform.value;
  14279. if ( type === "i" ) { // single integer
  14280. _gl.uniform1i( location, value );
  14281. } else if ( type === "f" ) { // single float
  14282. _gl.uniform1f( location, value );
  14283. } else if ( type === "v2" ) { // single THREE.Vector2
  14284. _gl.uniform2f( location, value.x, value.y );
  14285. } else if ( type === "v3" ) { // single THREE.Vector3
  14286. _gl.uniform3f( location, value.x, value.y, value.z );
  14287. } else if ( type === "v4" ) { // single THREE.Vector4
  14288. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14289. } else if ( type === "c" ) { // single THREE.Color
  14290. _gl.uniform3f( location, value.r, value.g, value.b );
  14291. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14292. _gl.uniform1iv( location, value );
  14293. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14294. _gl.uniform3iv( location, value );
  14295. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14296. _gl.uniform1fv( location, value );
  14297. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14298. _gl.uniform3fv( location, value );
  14299. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14300. if ( uniform._array === undefined ) {
  14301. uniform._array = new Float32Array( 2 * value.length );
  14302. }
  14303. for ( i = 0, il = value.length; i < il; i ++ ) {
  14304. offset = i * 2;
  14305. uniform._array[ offset ] = value[ i ].x;
  14306. uniform._array[ offset + 1 ] = value[ i ].y;
  14307. }
  14308. _gl.uniform2fv( location, uniform._array );
  14309. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14310. if ( uniform._array === undefined ) {
  14311. uniform._array = new Float32Array( 3 * value.length );
  14312. }
  14313. for ( i = 0, il = value.length; i < il; i ++ ) {
  14314. offset = i * 3;
  14315. uniform._array[ offset ] = value[ i ].x;
  14316. uniform._array[ offset + 1 ] = value[ i ].y;
  14317. uniform._array[ offset + 2 ] = value[ i ].z;
  14318. }
  14319. _gl.uniform3fv( location, uniform._array );
  14320. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14321. if ( uniform._array === undefined ) {
  14322. uniform._array = new Float32Array( 4 * value.length );
  14323. }
  14324. for ( i = 0, il = value.length; i < il; i ++ ) {
  14325. offset = i * 4;
  14326. uniform._array[ offset ] = value[ i ].x;
  14327. uniform._array[ offset + 1 ] = value[ i ].y;
  14328. uniform._array[ offset + 2 ] = value[ i ].z;
  14329. uniform._array[ offset + 3 ] = value[ i ].w;
  14330. }
  14331. _gl.uniform4fv( location, uniform._array );
  14332. } else if ( type === "m4") { // single THREE.Matrix4
  14333. if ( uniform._array === undefined ) {
  14334. uniform._array = new Float32Array( 16 );
  14335. }
  14336. value.flattenToArray( uniform._array );
  14337. _gl.uniformMatrix4fv( location, false, uniform._array );
  14338. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14339. if ( uniform._array === undefined ) {
  14340. uniform._array = new Float32Array( 16 * value.length );
  14341. }
  14342. for ( i = 0, il = value.length; i < il; i ++ ) {
  14343. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14344. }
  14345. _gl.uniformMatrix4fv( location, false, uniform._array );
  14346. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14347. texture = value;
  14348. textureUnit = getTextureUnit();
  14349. _gl.uniform1i( location, textureUnit );
  14350. if ( !texture ) continue;
  14351. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14352. setCubeTexture( texture, textureUnit );
  14353. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14354. setCubeTextureDynamic( texture, textureUnit );
  14355. } else {
  14356. _this.setTexture( texture, textureUnit );
  14357. }
  14358. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14359. if ( uniform._array === undefined ) {
  14360. uniform._array = [];
  14361. }
  14362. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14363. uniform._array[ i ] = getTextureUnit();
  14364. }
  14365. _gl.uniform1iv( location, uniform._array );
  14366. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14367. texture = uniform.value[ i ];
  14368. textureUnit = uniform._array[ i ];
  14369. if ( !texture ) continue;
  14370. _this.setTexture( texture, textureUnit );
  14371. }
  14372. } else {
  14373. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14374. }
  14375. }
  14376. };
  14377. function setupMatrices ( object, camera ) {
  14378. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14379. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14380. };
  14381. //
  14382. function setColorGamma( array, offset, color, intensitySq ) {
  14383. array[ offset ] = color.r * color.r * intensitySq;
  14384. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14385. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14386. };
  14387. function setColorLinear( array, offset, color, intensity ) {
  14388. array[ offset ] = color.r * intensity;
  14389. array[ offset + 1 ] = color.g * intensity;
  14390. array[ offset + 2 ] = color.b * intensity;
  14391. };
  14392. function setupLights ( program, lights ) {
  14393. var l, ll, light, n,
  14394. r = 0, g = 0, b = 0,
  14395. color, skyColor, groundColor,
  14396. intensity, intensitySq,
  14397. position,
  14398. distance,
  14399. zlights = _lights,
  14400. dirColors = zlights.directional.colors,
  14401. dirPositions = zlights.directional.positions,
  14402. pointColors = zlights.point.colors,
  14403. pointPositions = zlights.point.positions,
  14404. pointDistances = zlights.point.distances,
  14405. spotColors = zlights.spot.colors,
  14406. spotPositions = zlights.spot.positions,
  14407. spotDistances = zlights.spot.distances,
  14408. spotDirections = zlights.spot.directions,
  14409. spotAnglesCos = zlights.spot.anglesCos,
  14410. spotExponents = zlights.spot.exponents,
  14411. hemiSkyColors = zlights.hemi.skyColors,
  14412. hemiGroundColors = zlights.hemi.groundColors,
  14413. hemiPositions = zlights.hemi.positions,
  14414. dirLength = 0,
  14415. pointLength = 0,
  14416. spotLength = 0,
  14417. hemiLength = 0,
  14418. dirCount = 0,
  14419. pointCount = 0,
  14420. spotCount = 0,
  14421. hemiCount = 0,
  14422. dirOffset = 0,
  14423. pointOffset = 0,
  14424. spotOffset = 0,
  14425. hemiOffset = 0;
  14426. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14427. light = lights[ l ];
  14428. if ( light.onlyShadow ) continue;
  14429. color = light.color;
  14430. intensity = light.intensity;
  14431. distance = light.distance;
  14432. if ( light instanceof THREE.AmbientLight ) {
  14433. if ( ! light.visible ) continue;
  14434. if ( _this.gammaInput ) {
  14435. r += color.r * color.r;
  14436. g += color.g * color.g;
  14437. b += color.b * color.b;
  14438. } else {
  14439. r += color.r;
  14440. g += color.g;
  14441. b += color.b;
  14442. }
  14443. } else if ( light instanceof THREE.DirectionalLight ) {
  14444. dirCount += 1;
  14445. if ( ! light.visible ) continue;
  14446. _direction.getPositionFromMatrix( light.matrixWorld );
  14447. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14448. _direction.sub( _vector3 );
  14449. _direction.normalize();
  14450. // skip lights with undefined direction
  14451. // these create troubles in OpenGL (making pixel black)
  14452. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14453. dirOffset = dirLength * 3;
  14454. dirPositions[ dirOffset ] = _direction.x;
  14455. dirPositions[ dirOffset + 1 ] = _direction.y;
  14456. dirPositions[ dirOffset + 2 ] = _direction.z;
  14457. if ( _this.gammaInput ) {
  14458. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14459. } else {
  14460. setColorLinear( dirColors, dirOffset, color, intensity );
  14461. }
  14462. dirLength += 1;
  14463. } else if ( light instanceof THREE.PointLight ) {
  14464. pointCount += 1;
  14465. if ( ! light.visible ) continue;
  14466. pointOffset = pointLength * 3;
  14467. if ( _this.gammaInput ) {
  14468. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14469. } else {
  14470. setColorLinear( pointColors, pointOffset, color, intensity );
  14471. }
  14472. _vector3.getPositionFromMatrix( light.matrixWorld );
  14473. pointPositions[ pointOffset ] = _vector3.x;
  14474. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14475. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14476. pointDistances[ pointLength ] = distance;
  14477. pointLength += 1;
  14478. } else if ( light instanceof THREE.SpotLight ) {
  14479. spotCount += 1;
  14480. if ( ! light.visible ) continue;
  14481. spotOffset = spotLength * 3;
  14482. if ( _this.gammaInput ) {
  14483. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14484. } else {
  14485. setColorLinear( spotColors, spotOffset, color, intensity );
  14486. }
  14487. _vector3.getPositionFromMatrix( light.matrixWorld );
  14488. spotPositions[ spotOffset ] = _vector3.x;
  14489. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14490. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14491. spotDistances[ spotLength ] = distance;
  14492. _direction.copy( _vector3 );
  14493. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14494. _direction.sub( _vector3 );
  14495. _direction.normalize();
  14496. spotDirections[ spotOffset ] = _direction.x;
  14497. spotDirections[ spotOffset + 1 ] = _direction.y;
  14498. spotDirections[ spotOffset + 2 ] = _direction.z;
  14499. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14500. spotExponents[ spotLength ] = light.exponent;
  14501. spotLength += 1;
  14502. } else if ( light instanceof THREE.HemisphereLight ) {
  14503. hemiCount += 1;
  14504. if ( ! light.visible ) continue;
  14505. _direction.getPositionFromMatrix( light.matrixWorld );
  14506. _direction.normalize();
  14507. // skip lights with undefined direction
  14508. // these create troubles in OpenGL (making pixel black)
  14509. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14510. hemiOffset = hemiLength * 3;
  14511. hemiPositions[ hemiOffset ] = _direction.x;
  14512. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14513. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14514. skyColor = light.color;
  14515. groundColor = light.groundColor;
  14516. if ( _this.gammaInput ) {
  14517. intensitySq = intensity * intensity;
  14518. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14519. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14520. } else {
  14521. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14522. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14523. }
  14524. hemiLength += 1;
  14525. }
  14526. }
  14527. // null eventual remains from removed lights
  14528. // (this is to avoid if in shader)
  14529. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14530. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14531. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14532. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14533. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14534. zlights.directional.length = dirLength;
  14535. zlights.point.length = pointLength;
  14536. zlights.spot.length = spotLength;
  14537. zlights.hemi.length = hemiLength;
  14538. zlights.ambient[ 0 ] = r;
  14539. zlights.ambient[ 1 ] = g;
  14540. zlights.ambient[ 2 ] = b;
  14541. };
  14542. // GL state setting
  14543. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14544. if ( cullFace === THREE.CullFaceNone ) {
  14545. _gl.disable( _gl.CULL_FACE );
  14546. } else {
  14547. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14548. _gl.frontFace( _gl.CW );
  14549. } else {
  14550. _gl.frontFace( _gl.CCW );
  14551. }
  14552. if ( cullFace === THREE.CullFaceBack ) {
  14553. _gl.cullFace( _gl.BACK );
  14554. } else if ( cullFace === THREE.CullFaceFront ) {
  14555. _gl.cullFace( _gl.FRONT );
  14556. } else {
  14557. _gl.cullFace( _gl.FRONT_AND_BACK );
  14558. }
  14559. _gl.enable( _gl.CULL_FACE );
  14560. }
  14561. };
  14562. this.setMaterialFaces = function ( material ) {
  14563. var doubleSided = material.side === THREE.DoubleSide;
  14564. var flipSided = material.side === THREE.BackSide;
  14565. if ( _oldDoubleSided !== doubleSided ) {
  14566. if ( doubleSided ) {
  14567. _gl.disable( _gl.CULL_FACE );
  14568. } else {
  14569. _gl.enable( _gl.CULL_FACE );
  14570. }
  14571. _oldDoubleSided = doubleSided;
  14572. }
  14573. if ( _oldFlipSided !== flipSided ) {
  14574. if ( flipSided ) {
  14575. _gl.frontFace( _gl.CW );
  14576. } else {
  14577. _gl.frontFace( _gl.CCW );
  14578. }
  14579. _oldFlipSided = flipSided;
  14580. }
  14581. };
  14582. this.setDepthTest = function ( depthTest ) {
  14583. if ( _oldDepthTest !== depthTest ) {
  14584. if ( depthTest ) {
  14585. _gl.enable( _gl.DEPTH_TEST );
  14586. } else {
  14587. _gl.disable( _gl.DEPTH_TEST );
  14588. }
  14589. _oldDepthTest = depthTest;
  14590. }
  14591. };
  14592. this.setDepthWrite = function ( depthWrite ) {
  14593. if ( _oldDepthWrite !== depthWrite ) {
  14594. _gl.depthMask( depthWrite );
  14595. _oldDepthWrite = depthWrite;
  14596. }
  14597. };
  14598. function setLineWidth ( width ) {
  14599. if ( width !== _oldLineWidth ) {
  14600. _gl.lineWidth( width );
  14601. _oldLineWidth = width;
  14602. }
  14603. };
  14604. function setPolygonOffset ( polygonoffset, factor, units ) {
  14605. if ( _oldPolygonOffset !== polygonoffset ) {
  14606. if ( polygonoffset ) {
  14607. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14608. } else {
  14609. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14610. }
  14611. _oldPolygonOffset = polygonoffset;
  14612. }
  14613. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14614. _gl.polygonOffset( factor, units );
  14615. _oldPolygonOffsetFactor = factor;
  14616. _oldPolygonOffsetUnits = units;
  14617. }
  14618. };
  14619. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14620. if ( blending !== _oldBlending ) {
  14621. if ( blending === THREE.NoBlending ) {
  14622. _gl.disable( _gl.BLEND );
  14623. } else if ( blending === THREE.AdditiveBlending ) {
  14624. _gl.enable( _gl.BLEND );
  14625. _gl.blendEquation( _gl.FUNC_ADD );
  14626. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14627. } else if ( blending === THREE.SubtractiveBlending ) {
  14628. // TODO: Find blendFuncSeparate() combination
  14629. _gl.enable( _gl.BLEND );
  14630. _gl.blendEquation( _gl.FUNC_ADD );
  14631. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14632. } else if ( blending === THREE.MultiplyBlending ) {
  14633. // TODO: Find blendFuncSeparate() combination
  14634. _gl.enable( _gl.BLEND );
  14635. _gl.blendEquation( _gl.FUNC_ADD );
  14636. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14637. } else if ( blending === THREE.CustomBlending ) {
  14638. _gl.enable( _gl.BLEND );
  14639. } else {
  14640. _gl.enable( _gl.BLEND );
  14641. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14642. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14643. }
  14644. _oldBlending = blending;
  14645. }
  14646. if ( blending === THREE.CustomBlending ) {
  14647. if ( blendEquation !== _oldBlendEquation ) {
  14648. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14649. _oldBlendEquation = blendEquation;
  14650. }
  14651. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14652. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14653. _oldBlendSrc = blendSrc;
  14654. _oldBlendDst = blendDst;
  14655. }
  14656. } else {
  14657. _oldBlendEquation = null;
  14658. _oldBlendSrc = null;
  14659. _oldBlendDst = null;
  14660. }
  14661. };
  14662. // Defines
  14663. function generateDefines ( defines ) {
  14664. var value, chunk, chunks = [];
  14665. for ( var d in defines ) {
  14666. value = defines[ d ];
  14667. if ( value === false ) continue;
  14668. chunk = "#define " + d + " " + value;
  14669. chunks.push( chunk );
  14670. }
  14671. return chunks.join( "\n" );
  14672. };
  14673. // Shaders
  14674. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  14675. var p, pl, d, program, code;
  14676. var chunks = [];
  14677. // Generate code
  14678. if ( shaderID ) {
  14679. chunks.push( shaderID );
  14680. } else {
  14681. chunks.push( fragmentShader );
  14682. chunks.push( vertexShader );
  14683. }
  14684. for ( d in defines ) {
  14685. chunks.push( d );
  14686. chunks.push( defines[ d ] );
  14687. }
  14688. for ( p in parameters ) {
  14689. chunks.push( p );
  14690. chunks.push( parameters[ p ] );
  14691. }
  14692. code = chunks.join();
  14693. // Check if code has been already compiled
  14694. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14695. var programInfo = _programs[ p ];
  14696. if ( programInfo.code === code ) {
  14697. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14698. programInfo.usedTimes ++;
  14699. return programInfo.program;
  14700. }
  14701. }
  14702. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14703. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14704. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14705. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14706. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14707. }
  14708. // console.log( "building new program " );
  14709. //
  14710. var customDefines = generateDefines( defines );
  14711. //
  14712. program = _gl.createProgram();
  14713. var prefix_vertex = [
  14714. "precision " + _precision + " float;",
  14715. "precision " + _precision + " int;",
  14716. customDefines,
  14717. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14718. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14719. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14720. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14721. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14722. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14723. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14724. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14725. "#define MAX_SHADOWS " + parameters.maxShadows,
  14726. "#define MAX_BONES " + parameters.maxBones,
  14727. parameters.map ? "#define USE_MAP" : "",
  14728. parameters.envMap ? "#define USE_ENVMAP" : "",
  14729. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14730. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14731. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14732. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14733. parameters.vertexColors ? "#define USE_COLOR" : "",
  14734. parameters.skinning ? "#define USE_SKINNING" : "",
  14735. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14736. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14737. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14738. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14739. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14740. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14741. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14742. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14743. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14744. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14745. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14746. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14747. "uniform mat4 modelMatrix;",
  14748. "uniform mat4 modelViewMatrix;",
  14749. "uniform mat4 projectionMatrix;",
  14750. "uniform mat4 viewMatrix;",
  14751. "uniform mat3 normalMatrix;",
  14752. "uniform vec3 cameraPosition;",
  14753. "attribute vec3 position;",
  14754. "attribute vec3 normal;",
  14755. "attribute vec2 uv;",
  14756. "attribute vec2 uv2;",
  14757. "#ifdef USE_COLOR",
  14758. "attribute vec3 color;",
  14759. "#endif",
  14760. "#ifdef USE_MORPHTARGETS",
  14761. "attribute vec3 morphTarget0;",
  14762. "attribute vec3 morphTarget1;",
  14763. "attribute vec3 morphTarget2;",
  14764. "attribute vec3 morphTarget3;",
  14765. "#ifdef USE_MORPHNORMALS",
  14766. "attribute vec3 morphNormal0;",
  14767. "attribute vec3 morphNormal1;",
  14768. "attribute vec3 morphNormal2;",
  14769. "attribute vec3 morphNormal3;",
  14770. "#else",
  14771. "attribute vec3 morphTarget4;",
  14772. "attribute vec3 morphTarget5;",
  14773. "attribute vec3 morphTarget6;",
  14774. "attribute vec3 morphTarget7;",
  14775. "#endif",
  14776. "#endif",
  14777. "#ifdef USE_SKINNING",
  14778. "attribute vec4 skinIndex;",
  14779. "attribute vec4 skinWeight;",
  14780. "#endif",
  14781. ""
  14782. ].join("\n");
  14783. var prefix_fragment = [
  14784. "precision " + _precision + " float;",
  14785. "precision " + _precision + " int;",
  14786. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14787. customDefines,
  14788. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14789. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14790. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14791. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14792. "#define MAX_SHADOWS " + parameters.maxShadows,
  14793. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14794. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14795. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14796. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14797. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14798. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14799. parameters.map ? "#define USE_MAP" : "",
  14800. parameters.envMap ? "#define USE_ENVMAP" : "",
  14801. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14802. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14803. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14804. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14805. parameters.vertexColors ? "#define USE_COLOR" : "",
  14806. parameters.metal ? "#define METAL" : "",
  14807. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14808. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14809. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14810. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14811. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14812. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14813. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14814. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14815. "uniform mat4 viewMatrix;",
  14816. "uniform vec3 cameraPosition;",
  14817. ""
  14818. ].join("\n");
  14819. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14820. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14821. _gl.attachShader( program, glVertexShader );
  14822. _gl.attachShader( program, glFragmentShader );
  14823. //Force a particular attribute to index 0.
  14824. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14825. //And, color, for example is often automatically bound to index 0 so disabling it
  14826. if ( index0AttributeName ) {
  14827. _gl.bindAttribLocation( program, 0, index0AttributeName );
  14828. }
  14829. _gl.linkProgram( program );
  14830. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14831. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14832. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  14833. }
  14834. // clean up
  14835. _gl.deleteShader( glFragmentShader );
  14836. _gl.deleteShader( glVertexShader );
  14837. // console.log( prefix_fragment + fragmentShader );
  14838. // console.log( prefix_vertex + vertexShader );
  14839. program.uniforms = {};
  14840. program.attributes = {};
  14841. var identifiers, u, a, i;
  14842. // cache uniform locations
  14843. identifiers = [
  14844. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14845. 'morphTargetInfluences'
  14846. ];
  14847. if ( parameters.useVertexTexture ) {
  14848. identifiers.push( 'boneTexture' );
  14849. identifiers.push( 'boneTextureWidth' );
  14850. identifiers.push( 'boneTextureHeight' );
  14851. } else {
  14852. identifiers.push( 'boneGlobalMatrices' );
  14853. }
  14854. for ( u in uniforms ) {
  14855. identifiers.push( u );
  14856. }
  14857. cacheUniformLocations( program, identifiers );
  14858. // cache attributes locations
  14859. identifiers = [
  14860. "position", "normal", "uv", "uv2", "tangent", "color",
  14861. "skinIndex", "skinWeight", "lineDistance"
  14862. ];
  14863. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14864. identifiers.push( "morphTarget" + i );
  14865. }
  14866. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14867. identifiers.push( "morphNormal" + i );
  14868. }
  14869. for ( a in attributes ) {
  14870. identifiers.push( a );
  14871. }
  14872. cacheAttributeLocations( program, identifiers );
  14873. program.id = _programs_counter ++;
  14874. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14875. _this.info.memory.programs = _programs.length;
  14876. return program;
  14877. };
  14878. // Shader parameters cache
  14879. function cacheUniformLocations ( program, identifiers ) {
  14880. var i, l, id;
  14881. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14882. id = identifiers[ i ];
  14883. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14884. }
  14885. };
  14886. function cacheAttributeLocations ( program, identifiers ) {
  14887. var i, l, id;
  14888. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14889. id = identifiers[ i ];
  14890. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14891. }
  14892. };
  14893. function addLineNumbers ( string ) {
  14894. var chunks = string.split( "\n" );
  14895. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14896. // Chrome reports shader errors on lines
  14897. // starting counting from 1
  14898. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14899. }
  14900. return chunks.join( "\n" );
  14901. };
  14902. function getShader ( type, string ) {
  14903. var shader;
  14904. if ( type === "fragment" ) {
  14905. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14906. } else if ( type === "vertex" ) {
  14907. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14908. }
  14909. _gl.shaderSource( shader, string );
  14910. _gl.compileShader( shader );
  14911. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14912. console.error( _gl.getShaderInfoLog( shader ) );
  14913. console.error( addLineNumbers( string ) );
  14914. return null;
  14915. }
  14916. return shader;
  14917. };
  14918. // Textures
  14919. function isPowerOfTwo ( value ) {
  14920. return ( value & ( value - 1 ) ) === 0;
  14921. };
  14922. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14923. if ( isImagePowerOfTwo ) {
  14924. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14925. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14926. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14927. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14928. } else {
  14929. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14930. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14931. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14932. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14933. }
  14934. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14935. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14936. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14937. texture.__oldAnisotropy = texture.anisotropy;
  14938. }
  14939. }
  14940. };
  14941. this.setTexture = function ( texture, slot ) {
  14942. if ( texture.needsUpdate ) {
  14943. if ( ! texture.__webglInit ) {
  14944. texture.__webglInit = true;
  14945. texture.addEventListener( 'dispose', onTextureDispose );
  14946. texture.__webglTexture = _gl.createTexture();
  14947. _this.info.memory.textures ++;
  14948. }
  14949. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14950. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14951. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14952. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14953. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14954. var image = texture.image,
  14955. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14956. glFormat = paramThreeToGL( texture.format ),
  14957. glType = paramThreeToGL( texture.type );
  14958. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14959. var mipmap, mipmaps = texture.mipmaps;
  14960. if ( texture instanceof THREE.DataTexture ) {
  14961. // use manually created mipmaps if available
  14962. // if there are no manual mipmaps
  14963. // set 0 level mipmap and then use GL to generate other mipmap levels
  14964. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14965. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14966. mipmap = mipmaps[ i ];
  14967. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14968. }
  14969. texture.generateMipmaps = false;
  14970. } else {
  14971. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14972. }
  14973. } else if ( texture instanceof THREE.CompressedTexture ) {
  14974. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14975. mipmap = mipmaps[ i ];
  14976. if ( texture.format!==THREE.RGBAFormat ) {
  14977. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14978. } else {
  14979. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14980. }
  14981. }
  14982. } else { // regular Texture (image, video, canvas)
  14983. // use manually created mipmaps if available
  14984. // if there are no manual mipmaps
  14985. // set 0 level mipmap and then use GL to generate other mipmap levels
  14986. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14987. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14988. mipmap = mipmaps[ i ];
  14989. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14990. }
  14991. texture.generateMipmaps = false;
  14992. } else {
  14993. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14994. }
  14995. }
  14996. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14997. texture.needsUpdate = false;
  14998. if ( texture.onUpdate ) texture.onUpdate();
  14999. } else {
  15000. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15001. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15002. }
  15003. };
  15004. function clampToMaxSize ( image, maxSize ) {
  15005. if ( image.width <= maxSize && image.height <= maxSize ) {
  15006. return image;
  15007. }
  15008. // Warning: Scaling through the canvas will only work with images that use
  15009. // premultiplied alpha.
  15010. var maxDimension = Math.max( image.width, image.height );
  15011. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15012. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15013. var canvas = document.createElement( 'canvas' );
  15014. canvas.width = newWidth;
  15015. canvas.height = newHeight;
  15016. var ctx = canvas.getContext( "2d" );
  15017. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15018. return canvas;
  15019. }
  15020. function setCubeTexture ( texture, slot ) {
  15021. if ( texture.image.length === 6 ) {
  15022. if ( texture.needsUpdate ) {
  15023. if ( ! texture.image.__webglTextureCube ) {
  15024. texture.addEventListener( 'dispose', onTextureDispose );
  15025. texture.image.__webglTextureCube = _gl.createTexture();
  15026. _this.info.memory.textures ++;
  15027. }
  15028. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15029. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15030. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15031. var isCompressed = texture instanceof THREE.CompressedTexture;
  15032. var cubeImage = [];
  15033. for ( var i = 0; i < 6; i ++ ) {
  15034. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15035. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15036. } else {
  15037. cubeImage[ i ] = texture.image[ i ];
  15038. }
  15039. }
  15040. var image = cubeImage[ 0 ],
  15041. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15042. glFormat = paramThreeToGL( texture.format ),
  15043. glType = paramThreeToGL( texture.type );
  15044. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15045. for ( var i = 0; i < 6; i ++ ) {
  15046. if( !isCompressed ) {
  15047. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15048. } else {
  15049. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15050. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15051. mipmap = mipmaps[ j ];
  15052. if ( texture.format!==THREE.RGBAFormat ) {
  15053. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15054. } else {
  15055. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15056. }
  15057. }
  15058. }
  15059. }
  15060. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15061. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15062. }
  15063. texture.needsUpdate = false;
  15064. if ( texture.onUpdate ) texture.onUpdate();
  15065. } else {
  15066. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15067. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15068. }
  15069. }
  15070. };
  15071. function setCubeTextureDynamic ( texture, slot ) {
  15072. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15073. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15074. };
  15075. // Render targets
  15076. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15077. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15078. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15079. };
  15080. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15081. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15082. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15083. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15084. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15085. /* For some reason this is not working. Defaulting to RGBA4.
  15086. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15087. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15088. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15089. */
  15090. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15091. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15092. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15093. } else {
  15094. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15095. }
  15096. };
  15097. this.setRenderTarget = function ( renderTarget ) {
  15098. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15099. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15100. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15101. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15102. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15103. renderTarget.__webglTexture = _gl.createTexture();
  15104. _this.info.memory.textures ++;
  15105. // Setup texture, create render and frame buffers
  15106. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15107. glFormat = paramThreeToGL( renderTarget.format ),
  15108. glType = paramThreeToGL( renderTarget.type );
  15109. if ( isCube ) {
  15110. renderTarget.__webglFramebuffer = [];
  15111. renderTarget.__webglRenderbuffer = [];
  15112. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15113. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15114. for ( var i = 0; i < 6; i ++ ) {
  15115. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15116. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15117. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15118. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15119. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15120. }
  15121. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15122. } else {
  15123. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15124. if ( renderTarget.shareDepthFrom ) {
  15125. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15126. } else {
  15127. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15128. }
  15129. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15130. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15131. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15132. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15133. if ( renderTarget.shareDepthFrom ) {
  15134. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15135. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15136. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15137. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15138. }
  15139. } else {
  15140. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15141. }
  15142. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15143. }
  15144. // Release everything
  15145. if ( isCube ) {
  15146. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15147. } else {
  15148. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15149. }
  15150. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15151. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15152. }
  15153. var framebuffer, width, height, vx, vy;
  15154. if ( renderTarget ) {
  15155. if ( isCube ) {
  15156. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15157. } else {
  15158. framebuffer = renderTarget.__webglFramebuffer;
  15159. }
  15160. width = renderTarget.width;
  15161. height = renderTarget.height;
  15162. vx = 0;
  15163. vy = 0;
  15164. } else {
  15165. framebuffer = null;
  15166. width = _viewportWidth;
  15167. height = _viewportHeight;
  15168. vx = _viewportX;
  15169. vy = _viewportY;
  15170. }
  15171. if ( framebuffer !== _currentFramebuffer ) {
  15172. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15173. _gl.viewport( vx, vy, width, height );
  15174. _currentFramebuffer = framebuffer;
  15175. }
  15176. _currentWidth = width;
  15177. _currentHeight = height;
  15178. };
  15179. function updateRenderTargetMipmap ( renderTarget ) {
  15180. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15181. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15182. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15183. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15184. } else {
  15185. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15186. _gl.generateMipmap( _gl.TEXTURE_2D );
  15187. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15188. }
  15189. };
  15190. // Fallback filters for non-power-of-2 textures
  15191. function filterFallback ( f ) {
  15192. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15193. return _gl.NEAREST;
  15194. }
  15195. return _gl.LINEAR;
  15196. };
  15197. // Map three.js constants to WebGL constants
  15198. function paramThreeToGL ( p ) {
  15199. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15200. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15201. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15202. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15203. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15204. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15205. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15206. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15207. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15208. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15209. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15210. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15211. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15212. if ( p === THREE.ByteType ) return _gl.BYTE;
  15213. if ( p === THREE.ShortType ) return _gl.SHORT;
  15214. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15215. if ( p === THREE.IntType ) return _gl.INT;
  15216. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15217. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15218. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15219. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15220. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15221. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15222. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15223. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15224. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15225. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15226. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15227. if ( p === THREE.OneFactor ) return _gl.ONE;
  15228. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15229. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15230. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15231. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15232. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15233. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15234. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15235. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15236. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15237. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15238. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15239. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15240. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15241. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15242. }
  15243. return 0;
  15244. };
  15245. // Allocations
  15246. function allocateBones ( object ) {
  15247. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15248. return 1024;
  15249. } else {
  15250. // default for when object is not specified
  15251. // ( for example when prebuilding shader
  15252. // to be used with multiple objects )
  15253. //
  15254. // - leave some extra space for other uniforms
  15255. // - limit here is ANGLE's 254 max uniform vectors
  15256. // (up to 54 should be safe)
  15257. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15258. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15259. var maxBones = nVertexMatrices;
  15260. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15261. maxBones = Math.min( object.bones.length, maxBones );
  15262. if ( maxBones < object.bones.length ) {
  15263. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15264. }
  15265. }
  15266. return maxBones;
  15267. }
  15268. };
  15269. function allocateLights( lights ) {
  15270. var dirLights = 0;
  15271. var pointLights = 0;
  15272. var spotLights = 0;
  15273. var hemiLights = 0;
  15274. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15275. var light = lights[ l ];
  15276. if ( light.onlyShadow ) continue;
  15277. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15278. if ( light instanceof THREE.PointLight ) pointLights ++;
  15279. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15280. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15281. }
  15282. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15283. };
  15284. function allocateShadows( lights ) {
  15285. var maxShadows = 0;
  15286. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15287. var light = lights[ l ];
  15288. if ( ! light.castShadow ) continue;
  15289. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15290. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15291. }
  15292. return maxShadows;
  15293. };
  15294. // Initialization
  15295. function initGL() {
  15296. try {
  15297. var attributes = {
  15298. alpha: _alpha,
  15299. premultipliedAlpha: _premultipliedAlpha,
  15300. antialias: _antialias,
  15301. stencil: _stencil,
  15302. preserveDrawingBuffer: _preserveDrawingBuffer
  15303. };
  15304. _gl = _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15305. if ( _gl === null ) {
  15306. throw 'Error creating WebGL context.';
  15307. }
  15308. } catch ( error ) {
  15309. console.error( error );
  15310. }
  15311. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15312. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15313. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15314. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15315. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15316. if ( ! _glExtensionTextureFloat ) {
  15317. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15318. }
  15319. if ( ! _glExtensionStandardDerivatives ) {
  15320. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15321. }
  15322. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15323. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15324. }
  15325. if ( ! _glExtensionCompressedTextureS3TC ) {
  15326. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15327. }
  15328. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15329. _gl.getShaderPrecisionFormat = function() {
  15330. return {
  15331. "rangeMin" : 1,
  15332. "rangeMax" : 1,
  15333. "precision" : 1
  15334. };
  15335. }
  15336. }
  15337. };
  15338. function setDefaultGLState () {
  15339. _gl.clearColor( 0, 0, 0, 1 );
  15340. _gl.clearDepth( 1 );
  15341. _gl.clearStencil( 0 );
  15342. _gl.enable( _gl.DEPTH_TEST );
  15343. _gl.depthFunc( _gl.LEQUAL );
  15344. _gl.frontFace( _gl.CCW );
  15345. _gl.cullFace( _gl.BACK );
  15346. _gl.enable( _gl.CULL_FACE );
  15347. _gl.enable( _gl.BLEND );
  15348. _gl.blendEquation( _gl.FUNC_ADD );
  15349. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15350. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15351. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15352. };
  15353. // default plugins (order is important)
  15354. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15355. this.addPrePlugin( this.shadowMapPlugin );
  15356. this.addPostPlugin( new THREE.SpritePlugin() );
  15357. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15358. };
  15359. /**
  15360. * @author szimek / https://github.com/szimek/
  15361. * @author alteredq / http://alteredqualia.com/
  15362. */
  15363. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15364. this.width = width;
  15365. this.height = height;
  15366. options = options || {};
  15367. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15368. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15369. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15370. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15371. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15372. this.offset = new THREE.Vector2( 0, 0 );
  15373. this.repeat = new THREE.Vector2( 1, 1 );
  15374. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15375. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15376. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15377. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15378. this.generateMipmaps = true;
  15379. this.shareDepthFrom = null;
  15380. };
  15381. THREE.WebGLRenderTarget.prototype = {
  15382. constructor: THREE.WebGLRenderTarget,
  15383. clone: function () {
  15384. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15385. tmp.wrapS = this.wrapS;
  15386. tmp.wrapT = this.wrapT;
  15387. tmp.magFilter = this.magFilter;
  15388. tmp.minFilter = this.minFilter;
  15389. tmp.anisotropy = this.anisotropy;
  15390. tmp.offset.copy( this.offset );
  15391. tmp.repeat.copy( this.repeat );
  15392. tmp.format = this.format;
  15393. tmp.type = this.type;
  15394. tmp.depthBuffer = this.depthBuffer;
  15395. tmp.stencilBuffer = this.stencilBuffer;
  15396. tmp.generateMipmaps = this.generateMipmaps;
  15397. tmp.shareDepthFrom = this.shareDepthFrom;
  15398. return tmp;
  15399. },
  15400. dispose: function () {
  15401. this.dispatchEvent( { type: 'dispose' } );
  15402. }
  15403. };
  15404. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15405. /**
  15406. * @author alteredq / http://alteredqualia.com
  15407. */
  15408. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15409. THREE.WebGLRenderTarget.call( this, width, height, options );
  15410. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15411. };
  15412. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15413. /**
  15414. * @author mrdoob / http://mrdoob.com/
  15415. */
  15416. THREE.RenderableVertex = function () {
  15417. this.positionWorld = new THREE.Vector3();
  15418. this.positionScreen = new THREE.Vector4();
  15419. this.visible = true;
  15420. };
  15421. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15422. this.positionWorld.copy( vertex.positionWorld );
  15423. this.positionScreen.copy( vertex.positionScreen );
  15424. };
  15425. /**
  15426. * @author mrdoob / http://mrdoob.com/
  15427. */
  15428. THREE.RenderableFace3 = function () {
  15429. this.id = 0;
  15430. this.v1 = new THREE.RenderableVertex();
  15431. this.v2 = new THREE.RenderableVertex();
  15432. this.v3 = new THREE.RenderableVertex();
  15433. this.centroidModel = new THREE.Vector3();
  15434. this.normalModel = new THREE.Vector3();
  15435. this.normalModelView = new THREE.Vector3();
  15436. this.vertexNormalsLength = 0;
  15437. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15438. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15439. this.color = null;
  15440. this.material = null;
  15441. this.uvs = [[]];
  15442. this.z = 0;
  15443. };
  15444. /**
  15445. * @author mrdoob / http://mrdoob.com/
  15446. */
  15447. THREE.RenderableObject = function () {
  15448. this.id = 0;
  15449. this.object = null;
  15450. this.z = 0;
  15451. };
  15452. /**
  15453. * @author mrdoob / http://mrdoob.com/
  15454. */
  15455. THREE.RenderableSprite = function () {
  15456. this.id = 0;
  15457. this.object = null;
  15458. this.x = 0;
  15459. this.y = 0;
  15460. this.z = 0;
  15461. this.rotation = 0;
  15462. this.scale = new THREE.Vector2();
  15463. this.material = null;
  15464. };
  15465. /**
  15466. * @author mrdoob / http://mrdoob.com/
  15467. */
  15468. THREE.RenderableLine = function () {
  15469. this.id = 0;
  15470. this.v1 = new THREE.RenderableVertex();
  15471. this.v2 = new THREE.RenderableVertex();
  15472. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15473. this.material = null;
  15474. this.z = 0;
  15475. };
  15476. /**
  15477. * @author mrdoob / http://mrdoob.com/
  15478. * @author alteredq / http://alteredqualia.com/
  15479. */
  15480. THREE.GeometryUtils = {
  15481. // Merge two geometries or geometry and geometry from object (using object's transform)
  15482. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15483. var matrix, normalMatrix,
  15484. vertexOffset = geometry1.vertices.length,
  15485. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15486. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15487. vertices1 = geometry1.vertices,
  15488. vertices2 = geometry2.vertices,
  15489. faces1 = geometry1.faces,
  15490. faces2 = geometry2.faces,
  15491. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15492. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15493. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15494. if ( object2 instanceof THREE.Mesh ) {
  15495. object2.matrixAutoUpdate && object2.updateMatrix();
  15496. matrix = object2.matrix;
  15497. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15498. }
  15499. // vertices
  15500. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15501. var vertex = vertices2[ i ];
  15502. var vertexCopy = vertex.clone();
  15503. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15504. vertices1.push( vertexCopy );
  15505. }
  15506. // faces
  15507. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15508. var face = faces2[ i ], faceCopy, normal, color,
  15509. faceVertexNormals = face.vertexNormals,
  15510. faceVertexColors = face.vertexColors;
  15511. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15512. faceCopy.normal.copy( face.normal );
  15513. if ( normalMatrix ) {
  15514. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15515. }
  15516. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15517. normal = faceVertexNormals[ j ].clone();
  15518. if ( normalMatrix ) {
  15519. normal.applyMatrix3( normalMatrix ).normalize();
  15520. }
  15521. faceCopy.vertexNormals.push( normal );
  15522. }
  15523. faceCopy.color.copy( face.color );
  15524. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15525. color = faceVertexColors[ j ];
  15526. faceCopy.vertexColors.push( color.clone() );
  15527. }
  15528. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15529. faceCopy.centroid.copy( face.centroid );
  15530. if ( matrix ) {
  15531. faceCopy.centroid.applyMatrix4( matrix );
  15532. }
  15533. faces1.push( faceCopy );
  15534. }
  15535. // uvs
  15536. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15537. var uv = uvs2[ i ], uvCopy = [];
  15538. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15539. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15540. }
  15541. uvs1.push( uvCopy );
  15542. }
  15543. },
  15544. // Get random point in triangle (via barycentric coordinates)
  15545. // (uniform distribution)
  15546. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15547. randomPointInTriangle: function () {
  15548. var vector = new THREE.Vector3();
  15549. return function ( vectorA, vectorB, vectorC ) {
  15550. var point = new THREE.Vector3();
  15551. var a = THREE.Math.random16();
  15552. var b = THREE.Math.random16();
  15553. if ( ( a + b ) > 1 ) {
  15554. a = 1 - a;
  15555. b = 1 - b;
  15556. }
  15557. var c = 1 - a - b;
  15558. point.copy( vectorA );
  15559. point.multiplyScalar( a );
  15560. vector.copy( vectorB );
  15561. vector.multiplyScalar( b );
  15562. point.add( vector );
  15563. vector.copy( vectorC );
  15564. vector.multiplyScalar( c );
  15565. point.add( vector );
  15566. return point;
  15567. };
  15568. }(),
  15569. // Get random point in face (triangle / quad)
  15570. // (uniform distribution)
  15571. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15572. var vA, vB, vC, vD;
  15573. vA = geometry.vertices[ face.a ];
  15574. vB = geometry.vertices[ face.b ];
  15575. vC = geometry.vertices[ face.c ];
  15576. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15577. },
  15578. // Get uniformly distributed random points in mesh
  15579. // - create array with cumulative sums of face areas
  15580. // - pick random number from 0 to total area
  15581. // - find corresponding place in area array by binary search
  15582. // - get random point in face
  15583. randomPointsInGeometry: function ( geometry, n ) {
  15584. var face, i,
  15585. faces = geometry.faces,
  15586. vertices = geometry.vertices,
  15587. il = faces.length,
  15588. totalArea = 0,
  15589. cumulativeAreas = [],
  15590. vA, vB, vC, vD;
  15591. // precompute face areas
  15592. for ( i = 0; i < il; i ++ ) {
  15593. face = faces[ i ];
  15594. vA = vertices[ face.a ];
  15595. vB = vertices[ face.b ];
  15596. vC = vertices[ face.c ];
  15597. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15598. totalArea += face._area;
  15599. cumulativeAreas[ i ] = totalArea;
  15600. }
  15601. // binary search cumulative areas array
  15602. function binarySearchIndices( value ) {
  15603. function binarySearch( start, end ) {
  15604. // return closest larger index
  15605. // if exact number is not found
  15606. if ( end < start )
  15607. return start;
  15608. var mid = start + Math.floor( ( end - start ) / 2 );
  15609. if ( cumulativeAreas[ mid ] > value ) {
  15610. return binarySearch( start, mid - 1 );
  15611. } else if ( cumulativeAreas[ mid ] < value ) {
  15612. return binarySearch( mid + 1, end );
  15613. } else {
  15614. return mid;
  15615. }
  15616. }
  15617. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15618. return result;
  15619. }
  15620. // pick random face weighted by face area
  15621. var r, index,
  15622. result = [];
  15623. var stats = {};
  15624. for ( i = 0; i < n; i ++ ) {
  15625. r = THREE.Math.random16() * totalArea;
  15626. index = binarySearchIndices( r );
  15627. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15628. if ( ! stats[ index ] ) {
  15629. stats[ index ] = 1;
  15630. } else {
  15631. stats[ index ] += 1;
  15632. }
  15633. }
  15634. return result;
  15635. },
  15636. // Get triangle area (half of parallelogram)
  15637. // http://mathworld.wolfram.com/TriangleArea.html
  15638. triangleArea: function () {
  15639. var vector1 = new THREE.Vector3();
  15640. var vector2 = new THREE.Vector3();
  15641. return function ( vectorA, vectorB, vectorC ) {
  15642. vector1.subVectors( vectorB, vectorA );
  15643. vector2.subVectors( vectorC, vectorA );
  15644. vector1.cross( vector2 );
  15645. return 0.5 * vector1.length();
  15646. };
  15647. }(),
  15648. // Center geometry so that 0,0,0 is in center of bounding box
  15649. center: function ( geometry ) {
  15650. geometry.computeBoundingBox();
  15651. var bb = geometry.boundingBox;
  15652. var offset = new THREE.Vector3();
  15653. offset.addVectors( bb.min, bb.max );
  15654. offset.multiplyScalar( -0.5 );
  15655. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15656. geometry.computeBoundingBox();
  15657. return offset;
  15658. },
  15659. triangulateQuads: function ( geometry ) {
  15660. var i, il, j, jl;
  15661. var faces = [];
  15662. var faceVertexUvs = [];
  15663. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15664. faceVertexUvs[ i ] = [];
  15665. }
  15666. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15667. var face = geometry.faces[ i ];
  15668. faces.push( face );
  15669. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15670. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15671. }
  15672. }
  15673. geometry.faces = faces;
  15674. geometry.faceVertexUvs = faceVertexUvs;
  15675. geometry.computeCentroids();
  15676. geometry.computeFaceNormals();
  15677. geometry.computeVertexNormals();
  15678. if ( geometry.hasTangents ) geometry.computeTangents();
  15679. }
  15680. };
  15681. /**
  15682. * @author alteredq / http://alteredqualia.com/
  15683. * @author mrdoob / http://mrdoob.com/
  15684. */
  15685. THREE.ImageUtils = {
  15686. crossOrigin: 'anonymous',
  15687. loadTexture: function ( url, mapping, onLoad, onError ) {
  15688. var loader = new THREE.ImageLoader();
  15689. loader.crossOrigin = this.crossOrigin;
  15690. var texture = new THREE.Texture( undefined, mapping );
  15691. var image = loader.load( url, function () {
  15692. texture.needsUpdate = true;
  15693. if ( onLoad ) onLoad( texture );
  15694. } );
  15695. texture.image = image;
  15696. texture.sourceFile = url;
  15697. return texture;
  15698. },
  15699. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15700. var texture = new THREE.CompressedTexture();
  15701. texture.mapping = mapping;
  15702. var request = new XMLHttpRequest();
  15703. request.onload = function () {
  15704. var buffer = request.response;
  15705. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15706. texture.format = dds.format;
  15707. texture.mipmaps = dds.mipmaps;
  15708. texture.image.width = dds.width;
  15709. texture.image.height = dds.height;
  15710. // gl.generateMipmap fails for compressed textures
  15711. // mipmaps must be embedded in the DDS file
  15712. // or texture filters must not use mipmapping
  15713. texture.generateMipmaps = false;
  15714. texture.needsUpdate = true;
  15715. if ( onLoad ) onLoad( texture );
  15716. }
  15717. request.onerror = onError;
  15718. request.open( 'GET', url, true );
  15719. request.responseType = "arraybuffer";
  15720. request.send( null );
  15721. return texture;
  15722. },
  15723. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15724. var images = [];
  15725. images.loadCount = 0;
  15726. var texture = new THREE.Texture();
  15727. texture.image = images;
  15728. if ( mapping !== undefined ) texture.mapping = mapping;
  15729. // no flipping needed for cube textures
  15730. texture.flipY = false;
  15731. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15732. var cubeImage = new Image();
  15733. images[ i ] = cubeImage;
  15734. cubeImage.onload = function () {
  15735. images.loadCount += 1;
  15736. if ( images.loadCount === 6 ) {
  15737. texture.needsUpdate = true;
  15738. if ( onLoad ) onLoad( texture );
  15739. }
  15740. };
  15741. cubeImage.onerror = onError;
  15742. cubeImage.crossOrigin = this.crossOrigin;
  15743. cubeImage.src = array[ i ];
  15744. }
  15745. return texture;
  15746. },
  15747. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15748. var images = [];
  15749. images.loadCount = 0;
  15750. var texture = new THREE.CompressedTexture();
  15751. texture.image = images;
  15752. if ( mapping !== undefined ) texture.mapping = mapping;
  15753. // no flipping for cube textures
  15754. // (also flipping doesn't work for compressed textures )
  15755. texture.flipY = false;
  15756. // can't generate mipmaps for compressed textures
  15757. // mips must be embedded in DDS files
  15758. texture.generateMipmaps = false;
  15759. var generateCubeFaceCallback = function ( rq, img ) {
  15760. return function () {
  15761. var buffer = rq.response;
  15762. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15763. img.format = dds.format;
  15764. img.mipmaps = dds.mipmaps;
  15765. img.width = dds.width;
  15766. img.height = dds.height;
  15767. images.loadCount += 1;
  15768. if ( images.loadCount === 6 ) {
  15769. texture.format = dds.format;
  15770. texture.needsUpdate = true;
  15771. if ( onLoad ) onLoad( texture );
  15772. }
  15773. }
  15774. }
  15775. // compressed cubemap textures as 6 separate DDS files
  15776. if ( array instanceof Array ) {
  15777. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15778. var cubeImage = {};
  15779. images[ i ] = cubeImage;
  15780. var request = new XMLHttpRequest();
  15781. request.onload = generateCubeFaceCallback( request, cubeImage );
  15782. request.onerror = onError;
  15783. var url = array[ i ];
  15784. request.open( 'GET', url, true );
  15785. request.responseType = "arraybuffer";
  15786. request.send( null );
  15787. }
  15788. // compressed cubemap texture stored in a single DDS file
  15789. } else {
  15790. var url = array;
  15791. var request = new XMLHttpRequest();
  15792. request.onload = function( ) {
  15793. var buffer = request.response;
  15794. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15795. if ( dds.isCubemap ) {
  15796. var faces = dds.mipmaps.length / dds.mipmapCount;
  15797. for ( var f = 0; f < faces; f ++ ) {
  15798. images[ f ] = { mipmaps : [] };
  15799. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15800. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15801. images[ f ].format = dds.format;
  15802. images[ f ].width = dds.width;
  15803. images[ f ].height = dds.height;
  15804. }
  15805. }
  15806. texture.format = dds.format;
  15807. texture.needsUpdate = true;
  15808. if ( onLoad ) onLoad( texture );
  15809. }
  15810. }
  15811. request.onerror = onError;
  15812. request.open( 'GET', url, true );
  15813. request.responseType = "arraybuffer";
  15814. request.send( null );
  15815. }
  15816. return texture;
  15817. },
  15818. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  15819. var images = [];
  15820. images.loadCount = 0;
  15821. var texture = new THREE.CompressedTexture();
  15822. texture.image = images;
  15823. if ( mapping !== undefined ) texture.mapping = mapping;
  15824. // no flipping for cube textures
  15825. // (also flipping doesn't work for compressed textures )
  15826. texture.flipY = false;
  15827. // can't generate mipmaps for compressed textures
  15828. // mips must be embedded in DDS files
  15829. texture.generateMipmaps = false;
  15830. {
  15831. var request = new XMLHttpRequest();
  15832. request.onload = function( ) {
  15833. var buffer = request.response;
  15834. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15835. if ( dds.isCubemap ) {
  15836. var faces = dds.mipmaps.length / dds.mipmapCount;
  15837. for ( var f = 0; f < faces; f ++ ) {
  15838. images[ f ] = { mipmaps : [] };
  15839. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15840. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15841. images[ f ].format = dds.format;
  15842. images[ f ].width = dds.width;
  15843. images[ f ].height = dds.height;
  15844. }
  15845. }
  15846. } else {
  15847. texture.image.width = dds.width;
  15848. texture.image.height = dds.height;
  15849. texture.mipmaps = dds.mipmaps;
  15850. }
  15851. texture.format = dds.format;
  15852. texture.needsUpdate = true;
  15853. if ( onLoad ) onLoad( texture );
  15854. }
  15855. request.onerror = onError;
  15856. request.open( 'GET', url, true );
  15857. request.responseType = "arraybuffer";
  15858. request.send( null );
  15859. }
  15860. return texture;
  15861. },
  15862. parseDDS: function ( buffer, loadMipmaps ) {
  15863. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15864. // Adapted from @toji's DDS utils
  15865. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15866. // All values and structures referenced from:
  15867. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15868. var DDS_MAGIC = 0x20534444;
  15869. var DDSD_CAPS = 0x1,
  15870. DDSD_HEIGHT = 0x2,
  15871. DDSD_WIDTH = 0x4,
  15872. DDSD_PITCH = 0x8,
  15873. DDSD_PIXELFORMAT = 0x1000,
  15874. DDSD_MIPMAPCOUNT = 0x20000,
  15875. DDSD_LINEARSIZE = 0x80000,
  15876. DDSD_DEPTH = 0x800000;
  15877. var DDSCAPS_COMPLEX = 0x8,
  15878. DDSCAPS_MIPMAP = 0x400000,
  15879. DDSCAPS_TEXTURE = 0x1000;
  15880. var DDSCAPS2_CUBEMAP = 0x200,
  15881. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15882. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15883. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15884. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15885. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15886. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15887. DDSCAPS2_VOLUME = 0x200000;
  15888. var DDPF_ALPHAPIXELS = 0x1,
  15889. DDPF_ALPHA = 0x2,
  15890. DDPF_FOURCC = 0x4,
  15891. DDPF_RGB = 0x40,
  15892. DDPF_YUV = 0x200,
  15893. DDPF_LUMINANCE = 0x20000;
  15894. function fourCCToInt32( value ) {
  15895. return value.charCodeAt(0) +
  15896. (value.charCodeAt(1) << 8) +
  15897. (value.charCodeAt(2) << 16) +
  15898. (value.charCodeAt(3) << 24);
  15899. }
  15900. function int32ToFourCC( value ) {
  15901. return String.fromCharCode(
  15902. value & 0xff,
  15903. (value >> 8) & 0xff,
  15904. (value >> 16) & 0xff,
  15905. (value >> 24) & 0xff
  15906. );
  15907. }
  15908. function loadARGBMip( buffer, dataOffset, width, height ) {
  15909. var dataLength = width*height*4;
  15910. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  15911. var byteArray = new Uint8Array( dataLength );
  15912. var dst = 0;
  15913. var src = 0;
  15914. for ( var y = 0; y < height; y++ ) {
  15915. for ( var x = 0; x < width; x++ ) {
  15916. var b = srcBuffer[src]; src++;
  15917. var g = srcBuffer[src]; src++;
  15918. var r = srcBuffer[src]; src++;
  15919. var a = srcBuffer[src]; src++;
  15920. byteArray[dst] = r; dst++; //r
  15921. byteArray[dst] = g; dst++; //g
  15922. byteArray[dst] = b; dst++; //b
  15923. byteArray[dst] = a; dst++; //a
  15924. }
  15925. }
  15926. return byteArray;
  15927. }
  15928. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15929. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15930. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15931. var headerLengthInt = 31; // The header length in 32 bit ints
  15932. // Offsets into the header array
  15933. var off_magic = 0;
  15934. var off_size = 1;
  15935. var off_flags = 2;
  15936. var off_height = 3;
  15937. var off_width = 4;
  15938. var off_mipmapCount = 7;
  15939. var off_pfFlags = 20;
  15940. var off_pfFourCC = 21;
  15941. var off_RGBBitCount = 22;
  15942. var off_RBitMask = 23;
  15943. var off_GBitMask = 24;
  15944. var off_BBitMask = 25;
  15945. var off_ABitMask = 26;
  15946. var off_caps = 27;
  15947. var off_caps2 = 28;
  15948. var off_caps3 = 29;
  15949. var off_caps4 = 30;
  15950. // Parse header
  15951. var header = new Int32Array( buffer, 0, headerLengthInt );
  15952. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15953. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15954. return dds;
  15955. }
  15956. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15957. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15958. return dds;
  15959. }
  15960. var blockBytes;
  15961. var fourCC = header[ off_pfFourCC ];
  15962. var isRGBAUncompressed = false;
  15963. switch ( fourCC ) {
  15964. case FOURCC_DXT1:
  15965. blockBytes = 8;
  15966. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15967. break;
  15968. case FOURCC_DXT3:
  15969. blockBytes = 16;
  15970. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15971. break;
  15972. case FOURCC_DXT5:
  15973. blockBytes = 16;
  15974. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15975. break;
  15976. default:
  15977. if( header[off_RGBBitCount] ==32
  15978. && header[off_RBitMask]&0xff0000
  15979. && header[off_GBitMask]&0xff00
  15980. && header[off_BBitMask]&0xff
  15981. && header[off_ABitMask]&0xff000000 ) {
  15982. isRGBAUncompressed = true;
  15983. blockBytes = 64;
  15984. dds.format = THREE.RGBAFormat;
  15985. } else {
  15986. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15987. return dds;
  15988. }
  15989. }
  15990. dds.mipmapCount = 1;
  15991. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15992. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15993. }
  15994. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15995. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15996. dds.width = header[ off_width ];
  15997. dds.height = header[ off_height ];
  15998. var dataOffset = header[ off_size ] + 4;
  15999. // Extract mipmaps buffers
  16000. var width = dds.width;
  16001. var height = dds.height;
  16002. var faces = dds.isCubemap ? 6 : 1;
  16003. for ( var face = 0; face < faces; face ++ ) {
  16004. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16005. if( isRGBAUncompressed ) {
  16006. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16007. var dataLength = byteArray.length;
  16008. } else {
  16009. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16010. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16011. }
  16012. var mipmap = { "data": byteArray, "width": width, "height": height };
  16013. dds.mipmaps.push( mipmap );
  16014. dataOffset += dataLength;
  16015. width = Math.max( width * 0.5, 1 );
  16016. height = Math.max( height * 0.5, 1 );
  16017. }
  16018. width = dds.width;
  16019. height = dds.height;
  16020. }
  16021. return dds;
  16022. },
  16023. getNormalMap: function ( image, depth ) {
  16024. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16025. var cross = function ( a, b ) {
  16026. 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 ] ];
  16027. }
  16028. var subtract = function ( a, b ) {
  16029. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16030. }
  16031. var normalize = function ( a ) {
  16032. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16033. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16034. }
  16035. depth = depth | 1;
  16036. var width = image.width;
  16037. var height = image.height;
  16038. var canvas = document.createElement( 'canvas' );
  16039. canvas.width = width;
  16040. canvas.height = height;
  16041. var context = canvas.getContext( '2d' );
  16042. context.drawImage( image, 0, 0 );
  16043. var data = context.getImageData( 0, 0, width, height ).data;
  16044. var imageData = context.createImageData( width, height );
  16045. var output = imageData.data;
  16046. for ( var x = 0; x < width; x ++ ) {
  16047. for ( var y = 0; y < height; y ++ ) {
  16048. var ly = y - 1 < 0 ? 0 : y - 1;
  16049. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16050. var lx = x - 1 < 0 ? 0 : x - 1;
  16051. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16052. var points = [];
  16053. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16054. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16055. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16056. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16057. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16058. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16059. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16060. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16061. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16062. var normals = [];
  16063. var num_points = points.length;
  16064. for ( var i = 0; i < num_points; i ++ ) {
  16065. var v1 = points[ i ];
  16066. var v2 = points[ ( i + 1 ) % num_points ];
  16067. v1 = subtract( v1, origin );
  16068. v2 = subtract( v2, origin );
  16069. normals.push( normalize( cross( v1, v2 ) ) );
  16070. }
  16071. var normal = [ 0, 0, 0 ];
  16072. for ( var i = 0; i < normals.length; i ++ ) {
  16073. normal[ 0 ] += normals[ i ][ 0 ];
  16074. normal[ 1 ] += normals[ i ][ 1 ];
  16075. normal[ 2 ] += normals[ i ][ 2 ];
  16076. }
  16077. normal[ 0 ] /= normals.length;
  16078. normal[ 1 ] /= normals.length;
  16079. normal[ 2 ] /= normals.length;
  16080. var idx = ( y * width + x ) * 4;
  16081. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16082. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16083. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16084. output[ idx + 3 ] = 255;
  16085. }
  16086. }
  16087. context.putImageData( imageData, 0, 0 );
  16088. return canvas;
  16089. },
  16090. generateDataTexture: function ( width, height, color ) {
  16091. var size = width * height;
  16092. var data = new Uint8Array( 3 * size );
  16093. var r = Math.floor( color.r * 255 );
  16094. var g = Math.floor( color.g * 255 );
  16095. var b = Math.floor( color.b * 255 );
  16096. for ( var i = 0; i < size; i ++ ) {
  16097. data[ i * 3 ] = r;
  16098. data[ i * 3 + 1 ] = g;
  16099. data[ i * 3 + 2 ] = b;
  16100. }
  16101. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16102. texture.needsUpdate = true;
  16103. return texture;
  16104. }
  16105. };
  16106. /**
  16107. * @author alteredq / http://alteredqualia.com/
  16108. */
  16109. THREE.SceneUtils = {
  16110. createMultiMaterialObject: function ( geometry, materials ) {
  16111. var group = new THREE.Object3D();
  16112. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16113. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16114. }
  16115. return group;
  16116. },
  16117. detach : function ( child, parent, scene ) {
  16118. child.applyMatrix( parent.matrixWorld );
  16119. parent.remove( child );
  16120. scene.add( child );
  16121. },
  16122. attach: function ( child, scene, parent ) {
  16123. var matrixWorldInverse = new THREE.Matrix4();
  16124. matrixWorldInverse.getInverse( parent.matrixWorld );
  16125. child.applyMatrix( matrixWorldInverse );
  16126. scene.remove( child );
  16127. parent.add( child );
  16128. }
  16129. };
  16130. /**
  16131. * @author zz85 / http://www.lab4games.net/zz85/blog
  16132. * @author alteredq / http://alteredqualia.com/
  16133. *
  16134. * For Text operations in three.js (See TextGeometry)
  16135. *
  16136. * It uses techniques used in:
  16137. *
  16138. * typeface.js and canvastext
  16139. * For converting fonts and rendering with javascript
  16140. * http://typeface.neocracy.org
  16141. *
  16142. * Triangulation ported from AS3
  16143. * Simple Polygon Triangulation
  16144. * http://actionsnippet.com/?p=1462
  16145. *
  16146. * A Method to triangulate shapes with holes
  16147. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16148. *
  16149. */
  16150. THREE.FontUtils = {
  16151. faces : {},
  16152. // Just for now. face[weight][style]
  16153. face : "helvetiker",
  16154. weight: "normal",
  16155. style : "normal",
  16156. size : 150,
  16157. divisions : 10,
  16158. getFace : function() {
  16159. return this.faces[ this.face ][ this.weight ][ this.style ];
  16160. },
  16161. loadFace : function( data ) {
  16162. var family = data.familyName.toLowerCase();
  16163. var ThreeFont = this;
  16164. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16165. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16166. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16167. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16168. return data;
  16169. },
  16170. drawText : function( text ) {
  16171. var characterPts = [], allPts = [];
  16172. // RenderText
  16173. var i, p,
  16174. face = this.getFace(),
  16175. scale = this.size / face.resolution,
  16176. offset = 0,
  16177. chars = String( text ).split( '' ),
  16178. length = chars.length;
  16179. var fontPaths = [];
  16180. for ( i = 0; i < length; i ++ ) {
  16181. var path = new THREE.Path();
  16182. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16183. offset += ret.offset;
  16184. fontPaths.push( ret.path );
  16185. }
  16186. // get the width
  16187. var width = offset / 2;
  16188. //
  16189. // for ( p = 0; p < allPts.length; p++ ) {
  16190. //
  16191. // allPts[ p ].x -= width;
  16192. //
  16193. // }
  16194. //var extract = this.extractPoints( allPts, characterPts );
  16195. //extract.contour = allPts;
  16196. //extract.paths = fontPaths;
  16197. //extract.offset = width;
  16198. return { paths : fontPaths, offset : width };
  16199. },
  16200. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16201. var pts = [];
  16202. var i, i2, divisions,
  16203. outline, action, length,
  16204. scaleX, scaleY,
  16205. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16206. laste,
  16207. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16208. if ( !glyph ) return;
  16209. if ( glyph.o ) {
  16210. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16211. length = outline.length;
  16212. scaleX = scale;
  16213. scaleY = scale;
  16214. for ( i = 0; i < length; ) {
  16215. action = outline[ i ++ ];
  16216. //console.log( action );
  16217. switch( action ) {
  16218. case 'm':
  16219. // Move To
  16220. x = outline[ i++ ] * scaleX + offset;
  16221. y = outline[ i++ ] * scaleY;
  16222. path.moveTo( x, y );
  16223. break;
  16224. case 'l':
  16225. // Line To
  16226. x = outline[ i++ ] * scaleX + offset;
  16227. y = outline[ i++ ] * scaleY;
  16228. path.lineTo(x,y);
  16229. break;
  16230. case 'q':
  16231. // QuadraticCurveTo
  16232. cpx = outline[ i++ ] * scaleX + offset;
  16233. cpy = outline[ i++ ] * scaleY;
  16234. cpx1 = outline[ i++ ] * scaleX + offset;
  16235. cpy1 = outline[ i++ ] * scaleY;
  16236. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16237. laste = pts[ pts.length - 1 ];
  16238. if ( laste ) {
  16239. cpx0 = laste.x;
  16240. cpy0 = laste.y;
  16241. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16242. var t = i2 / divisions;
  16243. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16244. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16245. }
  16246. }
  16247. break;
  16248. case 'b':
  16249. // Cubic Bezier Curve
  16250. cpx = outline[ i++ ] * scaleX + offset;
  16251. cpy = outline[ i++ ] * scaleY;
  16252. cpx1 = outline[ i++ ] * scaleX + offset;
  16253. cpy1 = outline[ i++ ] * -scaleY;
  16254. cpx2 = outline[ i++ ] * scaleX + offset;
  16255. cpy2 = outline[ i++ ] * -scaleY;
  16256. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16257. laste = pts[ pts.length - 1 ];
  16258. if ( laste ) {
  16259. cpx0 = laste.x;
  16260. cpy0 = laste.y;
  16261. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16262. var t = i2 / divisions;
  16263. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16264. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16265. }
  16266. }
  16267. break;
  16268. }
  16269. }
  16270. }
  16271. return { offset: glyph.ha*scale, path:path};
  16272. }
  16273. };
  16274. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16275. // Parameters
  16276. parameters = parameters || {};
  16277. var size = parameters.size !== undefined ? parameters.size : 100;
  16278. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16279. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16280. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16281. var style = parameters.style !== undefined ? parameters.style : "normal";
  16282. THREE.FontUtils.size = size;
  16283. THREE.FontUtils.divisions = curveSegments;
  16284. THREE.FontUtils.face = font;
  16285. THREE.FontUtils.weight = weight;
  16286. THREE.FontUtils.style = style;
  16287. // Get a Font data json object
  16288. var data = THREE.FontUtils.drawText( text );
  16289. var paths = data.paths;
  16290. var shapes = [];
  16291. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16292. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16293. }
  16294. return shapes;
  16295. };
  16296. /**
  16297. * This code is a quick port of code written in C++ which was submitted to
  16298. * flipcode.com by John W. Ratcliff // July 22, 2000
  16299. * See original code and more information here:
  16300. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16301. *
  16302. * ported to actionscript by Zevan Rosser
  16303. * www.actionsnippet.com
  16304. *
  16305. * ported to javascript by Joshua Koo
  16306. * http://www.lab4games.net/zz85/blog
  16307. *
  16308. */
  16309. ( function( namespace ) {
  16310. var EPSILON = 0.0000000001;
  16311. // takes in an contour array and returns
  16312. var process = function( contour, indices ) {
  16313. var n = contour.length;
  16314. if ( n < 3 ) return null;
  16315. var result = [],
  16316. verts = [],
  16317. vertIndices = [];
  16318. /* we want a counter-clockwise polygon in verts */
  16319. var u, v, w;
  16320. if ( area( contour ) > 0.0 ) {
  16321. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16322. } else {
  16323. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16324. }
  16325. var nv = n;
  16326. /* remove nv - 2 vertices, creating 1 triangle every time */
  16327. var count = 2 * nv; /* error detection */
  16328. for( v = nv - 1; nv > 2; ) {
  16329. /* if we loop, it is probably a non-simple polygon */
  16330. if ( ( count-- ) <= 0 ) {
  16331. //** Triangulate: ERROR - probable bad polygon!
  16332. //throw ( "Warning, unable to triangulate polygon!" );
  16333. //return null;
  16334. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16335. console.log( "Warning, unable to triangulate polygon!" );
  16336. if ( indices ) return vertIndices;
  16337. return result;
  16338. }
  16339. /* three consecutive vertices in current polygon, <u,v,w> */
  16340. u = v; if ( nv <= u ) u = 0; /* previous */
  16341. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16342. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16343. if ( snip( contour, u, v, w, nv, verts ) ) {
  16344. var a, b, c, s, t;
  16345. /* true names of the vertices */
  16346. a = verts[ u ];
  16347. b = verts[ v ];
  16348. c = verts[ w ];
  16349. /* output Triangle */
  16350. result.push( [ contour[ a ],
  16351. contour[ b ],
  16352. contour[ c ] ] );
  16353. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16354. /* remove v from the remaining polygon */
  16355. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16356. verts[ s ] = verts[ t ];
  16357. }
  16358. nv--;
  16359. /* reset error detection counter */
  16360. count = 2 * nv;
  16361. }
  16362. }
  16363. if ( indices ) return vertIndices;
  16364. return result;
  16365. };
  16366. // calculate area of the contour polygon
  16367. var area = function ( contour ) {
  16368. var n = contour.length;
  16369. var a = 0.0;
  16370. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16371. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16372. }
  16373. return a * 0.5;
  16374. };
  16375. var snip = function ( contour, u, v, w, n, verts ) {
  16376. var p;
  16377. var ax, ay, bx, by;
  16378. var cx, cy, px, py;
  16379. ax = contour[ verts[ u ] ].x;
  16380. ay = contour[ verts[ u ] ].y;
  16381. bx = contour[ verts[ v ] ].x;
  16382. by = contour[ verts[ v ] ].y;
  16383. cx = contour[ verts[ w ] ].x;
  16384. cy = contour[ verts[ w ] ].y;
  16385. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16386. var aX, aY, bX, bY, cX, cY;
  16387. var apx, apy, bpx, bpy, cpx, cpy;
  16388. var cCROSSap, bCROSScp, aCROSSbp;
  16389. aX = cx - bx; aY = cy - by;
  16390. bX = ax - cx; bY = ay - cy;
  16391. cX = bx - ax; cY = by - ay;
  16392. for ( p = 0; p < n; p++ ) {
  16393. if( (p === u) || (p === v) || (p === w) ) continue;
  16394. px = contour[ verts[ p ] ].x
  16395. py = contour[ verts[ p ] ].y
  16396. apx = px - ax; apy = py - ay;
  16397. bpx = px - bx; bpy = py - by;
  16398. cpx = px - cx; cpy = py - cy;
  16399. // see if p is inside triangle abc
  16400. aCROSSbp = aX*bpy - aY*bpx;
  16401. cCROSSap = cX*apy - cY*apx;
  16402. bCROSScp = bX*cpy - bY*cpx;
  16403. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16404. }
  16405. return true;
  16406. };
  16407. namespace.Triangulate = process;
  16408. namespace.Triangulate.area = area;
  16409. return namespace;
  16410. })(THREE.FontUtils);
  16411. // To use the typeface.js face files, hook up the API
  16412. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16413. THREE.typeface_js = self._typeface_js;
  16414. /**
  16415. * @author zz85 / http://www.lab4games.net/zz85/blog
  16416. * Extensible curve object
  16417. *
  16418. * Some common of Curve methods
  16419. * .getPoint(t), getTangent(t)
  16420. * .getPointAt(u), getTagentAt(u)
  16421. * .getPoints(), .getSpacedPoints()
  16422. * .getLength()
  16423. * .updateArcLengths()
  16424. *
  16425. * This following classes subclasses THREE.Curve:
  16426. *
  16427. * -- 2d classes --
  16428. * THREE.LineCurve
  16429. * THREE.QuadraticBezierCurve
  16430. * THREE.CubicBezierCurve
  16431. * THREE.SplineCurve
  16432. * THREE.ArcCurve
  16433. * THREE.EllipseCurve
  16434. *
  16435. * -- 3d classes --
  16436. * THREE.LineCurve3
  16437. * THREE.QuadraticBezierCurve3
  16438. * THREE.CubicBezierCurve3
  16439. * THREE.SplineCurve3
  16440. * THREE.ClosedSplineCurve3
  16441. *
  16442. * A series of curves can be represented as a THREE.CurvePath
  16443. *
  16444. **/
  16445. /**************************************************************
  16446. * Abstract Curve base class
  16447. **************************************************************/
  16448. THREE.Curve = function () {
  16449. };
  16450. // Virtual base class method to overwrite and implement in subclasses
  16451. // - t [0 .. 1]
  16452. THREE.Curve.prototype.getPoint = function ( t ) {
  16453. console.log( "Warning, getPoint() not implemented!" );
  16454. return null;
  16455. };
  16456. // Get point at relative position in curve according to arc length
  16457. // - u [0 .. 1]
  16458. THREE.Curve.prototype.getPointAt = function ( u ) {
  16459. var t = this.getUtoTmapping( u );
  16460. return this.getPoint( t );
  16461. };
  16462. // Get sequence of points using getPoint( t )
  16463. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16464. if ( !divisions ) divisions = 5;
  16465. var d, pts = [];
  16466. for ( d = 0; d <= divisions; d ++ ) {
  16467. pts.push( this.getPoint( d / divisions ) );
  16468. }
  16469. return pts;
  16470. };
  16471. // Get sequence of points using getPointAt( u )
  16472. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16473. if ( !divisions ) divisions = 5;
  16474. var d, pts = [];
  16475. for ( d = 0; d <= divisions; d ++ ) {
  16476. pts.push( this.getPointAt( d / divisions ) );
  16477. }
  16478. return pts;
  16479. };
  16480. // Get total curve arc length
  16481. THREE.Curve.prototype.getLength = function () {
  16482. var lengths = this.getLengths();
  16483. return lengths[ lengths.length - 1 ];
  16484. };
  16485. // Get list of cumulative segment lengths
  16486. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16487. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16488. if ( this.cacheArcLengths
  16489. && ( this.cacheArcLengths.length == divisions + 1 )
  16490. && !this.needsUpdate) {
  16491. //console.log( "cached", this.cacheArcLengths );
  16492. return this.cacheArcLengths;
  16493. }
  16494. this.needsUpdate = false;
  16495. var cache = [];
  16496. var current, last = this.getPoint( 0 );
  16497. var p, sum = 0;
  16498. cache.push( 0 );
  16499. for ( p = 1; p <= divisions; p ++ ) {
  16500. current = this.getPoint ( p / divisions );
  16501. sum += current.distanceTo( last );
  16502. cache.push( sum );
  16503. last = current;
  16504. }
  16505. this.cacheArcLengths = cache;
  16506. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16507. };
  16508. THREE.Curve.prototype.updateArcLengths = function() {
  16509. this.needsUpdate = true;
  16510. this.getLengths();
  16511. };
  16512. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16513. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16514. var arcLengths = this.getLengths();
  16515. var i = 0, il = arcLengths.length;
  16516. var targetArcLength; // The targeted u distance value to get
  16517. if ( distance ) {
  16518. targetArcLength = distance;
  16519. } else {
  16520. targetArcLength = u * arcLengths[ il - 1 ];
  16521. }
  16522. //var time = Date.now();
  16523. // binary search for the index with largest value smaller than target u distance
  16524. var low = 0, high = il - 1, comparison;
  16525. while ( low <= high ) {
  16526. 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
  16527. comparison = arcLengths[ i ] - targetArcLength;
  16528. if ( comparison < 0 ) {
  16529. low = i + 1;
  16530. continue;
  16531. } else if ( comparison > 0 ) {
  16532. high = i - 1;
  16533. continue;
  16534. } else {
  16535. high = i;
  16536. break;
  16537. // DONE
  16538. }
  16539. }
  16540. i = high;
  16541. //console.log('b' , i, low, high, Date.now()- time);
  16542. if ( arcLengths[ i ] == targetArcLength ) {
  16543. var t = i / ( il - 1 );
  16544. return t;
  16545. }
  16546. // we could get finer grain at lengths, or use simple interpolatation between two points
  16547. var lengthBefore = arcLengths[ i ];
  16548. var lengthAfter = arcLengths[ i + 1 ];
  16549. var segmentLength = lengthAfter - lengthBefore;
  16550. // determine where we are between the 'before' and 'after' points
  16551. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16552. // add that fractional amount to t
  16553. var t = ( i + segmentFraction ) / ( il -1 );
  16554. return t;
  16555. };
  16556. // Returns a unit vector tangent at t
  16557. // In case any sub curve does not implement its tangent derivation,
  16558. // 2 points a small delta apart will be used to find its gradient
  16559. // which seems to give a reasonable approximation
  16560. THREE.Curve.prototype.getTangent = function( t ) {
  16561. var delta = 0.0001;
  16562. var t1 = t - delta;
  16563. var t2 = t + delta;
  16564. // Capping in case of danger
  16565. if ( t1 < 0 ) t1 = 0;
  16566. if ( t2 > 1 ) t2 = 1;
  16567. var pt1 = this.getPoint( t1 );
  16568. var pt2 = this.getPoint( t2 );
  16569. var vec = pt2.clone().sub(pt1);
  16570. return vec.normalize();
  16571. };
  16572. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16573. var t = this.getUtoTmapping( u );
  16574. return this.getTangent( t );
  16575. };
  16576. /**************************************************************
  16577. * Utils
  16578. **************************************************************/
  16579. THREE.Curve.Utils = {
  16580. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16581. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16582. },
  16583. // Puay Bing, thanks for helping with this derivative!
  16584. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16585. return -3 * p0 * (1 - t) * (1 - t) +
  16586. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16587. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16588. 3 * t * t * p3;
  16589. },
  16590. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16591. // To check if my formulas are correct
  16592. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16593. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16594. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16595. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16596. return h00 + h10 + h01 + h11;
  16597. },
  16598. // Catmull-Rom
  16599. interpolate: function( p0, p1, p2, p3, t ) {
  16600. var v0 = ( p2 - p0 ) * 0.5;
  16601. var v1 = ( p3 - p1 ) * 0.5;
  16602. var t2 = t * t;
  16603. var t3 = t * t2;
  16604. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16605. }
  16606. };
  16607. // TODO: Transformation for Curves?
  16608. /**************************************************************
  16609. * 3D Curves
  16610. **************************************************************/
  16611. // A Factory method for creating new curve subclasses
  16612. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16613. constructor.prototype = Object.create( THREE.Curve.prototype );
  16614. constructor.prototype.getPoint = getPointFunc;
  16615. return constructor;
  16616. };
  16617. /**
  16618. * @author zz85 / http://www.lab4games.net/zz85/blog
  16619. *
  16620. **/
  16621. /**************************************************************
  16622. * Curved Path - a curve path is simply a array of connected
  16623. * curves, but retains the api of a curve
  16624. **************************************************************/
  16625. THREE.CurvePath = function () {
  16626. this.curves = [];
  16627. this.bends = [];
  16628. this.autoClose = false; // Automatically closes the path
  16629. };
  16630. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16631. THREE.CurvePath.prototype.add = function ( curve ) {
  16632. this.curves.push( curve );
  16633. };
  16634. THREE.CurvePath.prototype.checkConnection = function() {
  16635. // TODO
  16636. // If the ending of curve is not connected to the starting
  16637. // or the next curve, then, this is not a real path
  16638. };
  16639. THREE.CurvePath.prototype.closePath = function() {
  16640. // TODO Test
  16641. // and verify for vector3 (needs to implement equals)
  16642. // Add a line curve if start and end of lines are not connected
  16643. var startPoint = this.curves[0].getPoint(0);
  16644. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16645. if (!startPoint.equals(endPoint)) {
  16646. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16647. }
  16648. };
  16649. // To get accurate point with reference to
  16650. // entire path distance at time t,
  16651. // following has to be done:
  16652. // 1. Length of each sub path have to be known
  16653. // 2. Locate and identify type of curve
  16654. // 3. Get t for the curve
  16655. // 4. Return curve.getPointAt(t')
  16656. THREE.CurvePath.prototype.getPoint = function( t ) {
  16657. var d = t * this.getLength();
  16658. var curveLengths = this.getCurveLengths();
  16659. var i = 0, diff, curve;
  16660. // To think about boundaries points.
  16661. while ( i < curveLengths.length ) {
  16662. if ( curveLengths[ i ] >= d ) {
  16663. diff = curveLengths[ i ] - d;
  16664. curve = this.curves[ i ];
  16665. var u = 1 - diff / curve.getLength();
  16666. return curve.getPointAt( u );
  16667. break;
  16668. }
  16669. i ++;
  16670. }
  16671. return null;
  16672. // loop where sum != 0, sum > d , sum+1 <d
  16673. };
  16674. /*
  16675. THREE.CurvePath.prototype.getTangent = function( t ) {
  16676. };*/
  16677. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16678. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16679. // getPoint() depends on getLength
  16680. THREE.CurvePath.prototype.getLength = function() {
  16681. var lens = this.getCurveLengths();
  16682. return lens[ lens.length - 1 ];
  16683. };
  16684. // Compute lengths and cache them
  16685. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16686. THREE.CurvePath.prototype.getCurveLengths = function() {
  16687. // We use cache values if curves and cache array are same length
  16688. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16689. return this.cacheLengths;
  16690. };
  16691. // Get length of subsurve
  16692. // Push sums into cached array
  16693. var lengths = [], sums = 0;
  16694. var i, il = this.curves.length;
  16695. for ( i = 0; i < il; i ++ ) {
  16696. sums += this.curves[ i ].getLength();
  16697. lengths.push( sums );
  16698. }
  16699. this.cacheLengths = lengths;
  16700. return lengths;
  16701. };
  16702. // Returns min and max coordinates, as well as centroid
  16703. THREE.CurvePath.prototype.getBoundingBox = function () {
  16704. var points = this.getPoints();
  16705. var maxX, maxY, maxZ;
  16706. var minX, minY, minZ;
  16707. maxX = maxY = Number.NEGATIVE_INFINITY;
  16708. minX = minY = Number.POSITIVE_INFINITY;
  16709. var p, i, il, sum;
  16710. var v3 = points[0] instanceof THREE.Vector3;
  16711. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16712. for ( i = 0, il = points.length; i < il; i ++ ) {
  16713. p = points[ i ];
  16714. if ( p.x > maxX ) maxX = p.x;
  16715. else if ( p.x < minX ) minX = p.x;
  16716. if ( p.y > maxY ) maxY = p.y;
  16717. else if ( p.y < minY ) minY = p.y;
  16718. if ( v3 ) {
  16719. if ( p.z > maxZ ) maxZ = p.z;
  16720. else if ( p.z < minZ ) minZ = p.z;
  16721. }
  16722. sum.add( p );
  16723. }
  16724. var ret = {
  16725. minX: minX,
  16726. minY: minY,
  16727. maxX: maxX,
  16728. maxY: maxY,
  16729. centroid: sum.divideScalar( il )
  16730. };
  16731. if ( v3 ) {
  16732. ret.maxZ = maxZ;
  16733. ret.minZ = minZ;
  16734. }
  16735. return ret;
  16736. };
  16737. /**************************************************************
  16738. * Create Geometries Helpers
  16739. **************************************************************/
  16740. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16741. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16742. var pts = this.getPoints( divisions, true );
  16743. return this.createGeometry( pts );
  16744. };
  16745. // Generate geometry from equidistance sampling along the path
  16746. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16747. var pts = this.getSpacedPoints( divisions, true );
  16748. return this.createGeometry( pts );
  16749. };
  16750. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16751. var geometry = new THREE.Geometry();
  16752. for ( var i = 0; i < points.length; i ++ ) {
  16753. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16754. }
  16755. return geometry;
  16756. };
  16757. /**************************************************************
  16758. * Bend / Wrap Helper Methods
  16759. **************************************************************/
  16760. // Wrap path / Bend modifiers?
  16761. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16762. this.bends.push( bendpath );
  16763. };
  16764. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16765. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16766. var i, il;
  16767. if ( !bends ) {
  16768. bends = this.bends;
  16769. }
  16770. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16771. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16772. }
  16773. return oldPts;
  16774. };
  16775. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16776. var oldPts = this.getSpacedPoints( segments );
  16777. var i, il;
  16778. if ( !bends ) {
  16779. bends = this.bends;
  16780. }
  16781. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16782. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16783. }
  16784. return oldPts;
  16785. };
  16786. // This returns getPoints() bend/wrapped around the contour of a path.
  16787. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16788. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16789. var bounds = this.getBoundingBox();
  16790. var i, il, p, oldX, oldY, xNorm;
  16791. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16792. p = oldPts[ i ];
  16793. oldX = p.x;
  16794. oldY = p.y;
  16795. xNorm = oldX / bounds.maxX;
  16796. // If using actual distance, for length > path, requires line extrusions
  16797. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16798. xNorm = path.getUtoTmapping( xNorm, oldX );
  16799. // check for out of bounds?
  16800. var pathPt = path.getPoint( xNorm );
  16801. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16802. p.x = pathPt.x + normal.x;
  16803. p.y = pathPt.y + normal.y;
  16804. }
  16805. return oldPts;
  16806. };
  16807. /**
  16808. * @author alteredq / http://alteredqualia.com/
  16809. */
  16810. THREE.Gyroscope = function () {
  16811. THREE.Object3D.call( this );
  16812. };
  16813. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16814. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16815. this.matrixAutoUpdate && this.updateMatrix();
  16816. // update matrixWorld
  16817. if ( this.matrixWorldNeedsUpdate || force ) {
  16818. if ( this.parent ) {
  16819. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16820. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  16821. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  16822. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  16823. } else {
  16824. this.matrixWorld.copy( this.matrix );
  16825. }
  16826. this.matrixWorldNeedsUpdate = false;
  16827. force = true;
  16828. }
  16829. // update children
  16830. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16831. this.children[ i ].updateMatrixWorld( force );
  16832. }
  16833. };
  16834. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16835. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16836. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  16837. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  16838. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16839. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16840. /**
  16841. * @author zz85 / http://www.lab4games.net/zz85/blog
  16842. * Creates free form 2d path using series of points, lines or curves.
  16843. *
  16844. **/
  16845. THREE.Path = function ( points ) {
  16846. THREE.CurvePath.call(this);
  16847. this.actions = [];
  16848. if ( points ) {
  16849. this.fromPoints( points );
  16850. }
  16851. };
  16852. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16853. THREE.PathActions = {
  16854. MOVE_TO: 'moveTo',
  16855. LINE_TO: 'lineTo',
  16856. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16857. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16858. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16859. ARC: 'arc', // Circle
  16860. ELLIPSE: 'ellipse'
  16861. };
  16862. // TODO Clean up PATH API
  16863. // Create path using straight lines to connect all points
  16864. // - vectors: array of Vector2
  16865. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16866. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16867. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16868. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16869. };
  16870. };
  16871. // startPath() endPath()?
  16872. THREE.Path.prototype.moveTo = function ( x, y ) {
  16873. var args = Array.prototype.slice.call( arguments );
  16874. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16875. };
  16876. THREE.Path.prototype.lineTo = function ( x, y ) {
  16877. var args = Array.prototype.slice.call( arguments );
  16878. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16879. var x0 = lastargs[ lastargs.length - 2 ];
  16880. var y0 = lastargs[ lastargs.length - 1 ];
  16881. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16882. this.curves.push( curve );
  16883. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16884. };
  16885. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16886. var args = Array.prototype.slice.call( arguments );
  16887. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16888. var x0 = lastargs[ lastargs.length - 2 ];
  16889. var y0 = lastargs[ lastargs.length - 1 ];
  16890. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16891. new THREE.Vector2( aCPx, aCPy ),
  16892. new THREE.Vector2( aX, aY ) );
  16893. this.curves.push( curve );
  16894. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16895. };
  16896. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16897. aCP2x, aCP2y,
  16898. aX, aY ) {
  16899. var args = Array.prototype.slice.call( arguments );
  16900. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16901. var x0 = lastargs[ lastargs.length - 2 ];
  16902. var y0 = lastargs[ lastargs.length - 1 ];
  16903. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16904. new THREE.Vector2( aCP1x, aCP1y ),
  16905. new THREE.Vector2( aCP2x, aCP2y ),
  16906. new THREE.Vector2( aX, aY ) );
  16907. this.curves.push( curve );
  16908. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16909. };
  16910. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16911. var args = Array.prototype.slice.call( arguments );
  16912. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16913. var x0 = lastargs[ lastargs.length - 2 ];
  16914. var y0 = lastargs[ lastargs.length - 1 ];
  16915. //---
  16916. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16917. Array.prototype.push.apply( npts, pts );
  16918. var curve = new THREE.SplineCurve( npts );
  16919. this.curves.push( curve );
  16920. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16921. };
  16922. // FUTURE: Change the API or follow canvas API?
  16923. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16924. aStartAngle, aEndAngle, aClockwise ) {
  16925. var lastargs = this.actions[ this.actions.length - 1].args;
  16926. var x0 = lastargs[ lastargs.length - 2 ];
  16927. var y0 = lastargs[ lastargs.length - 1 ];
  16928. this.absarc(aX + x0, aY + y0, aRadius,
  16929. aStartAngle, aEndAngle, aClockwise );
  16930. };
  16931. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16932. aStartAngle, aEndAngle, aClockwise ) {
  16933. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16934. };
  16935. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16936. aStartAngle, aEndAngle, aClockwise ) {
  16937. var lastargs = this.actions[ this.actions.length - 1].args;
  16938. var x0 = lastargs[ lastargs.length - 2 ];
  16939. var y0 = lastargs[ lastargs.length - 1 ];
  16940. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16941. aStartAngle, aEndAngle, aClockwise );
  16942. };
  16943. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16944. aStartAngle, aEndAngle, aClockwise ) {
  16945. var args = Array.prototype.slice.call( arguments );
  16946. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16947. aStartAngle, aEndAngle, aClockwise );
  16948. this.curves.push( curve );
  16949. var lastPoint = curve.getPoint(1);
  16950. args.push(lastPoint.x);
  16951. args.push(lastPoint.y);
  16952. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16953. };
  16954. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16955. if ( ! divisions ) divisions = 40;
  16956. var points = [];
  16957. for ( var i = 0; i < divisions; i ++ ) {
  16958. points.push( this.getPoint( i / divisions ) );
  16959. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16960. }
  16961. // if ( closedPath ) {
  16962. //
  16963. // points.push( points[ 0 ] );
  16964. //
  16965. // }
  16966. return points;
  16967. };
  16968. /* Return an array of vectors based on contour of the path */
  16969. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16970. if (this.useSpacedPoints) {
  16971. console.log('tata');
  16972. return this.getSpacedPoints( divisions, closedPath );
  16973. }
  16974. divisions = divisions || 12;
  16975. var points = [];
  16976. var i, il, item, action, args;
  16977. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16978. laste, j,
  16979. t, tx, ty;
  16980. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16981. item = this.actions[ i ];
  16982. action = item.action;
  16983. args = item.args;
  16984. switch( action ) {
  16985. case THREE.PathActions.MOVE_TO:
  16986. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16987. break;
  16988. case THREE.PathActions.LINE_TO:
  16989. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16990. break;
  16991. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16992. cpx = args[ 2 ];
  16993. cpy = args[ 3 ];
  16994. cpx1 = args[ 0 ];
  16995. cpy1 = args[ 1 ];
  16996. if ( points.length > 0 ) {
  16997. laste = points[ points.length - 1 ];
  16998. cpx0 = laste.x;
  16999. cpy0 = laste.y;
  17000. } else {
  17001. laste = this.actions[ i - 1 ].args;
  17002. cpx0 = laste[ laste.length - 2 ];
  17003. cpy0 = laste[ laste.length - 1 ];
  17004. }
  17005. for ( j = 1; j <= divisions; j ++ ) {
  17006. t = j / divisions;
  17007. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17008. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17009. points.push( new THREE.Vector2( tx, ty ) );
  17010. }
  17011. break;
  17012. case THREE.PathActions.BEZIER_CURVE_TO:
  17013. cpx = args[ 4 ];
  17014. cpy = args[ 5 ];
  17015. cpx1 = args[ 0 ];
  17016. cpy1 = args[ 1 ];
  17017. cpx2 = args[ 2 ];
  17018. cpy2 = args[ 3 ];
  17019. if ( points.length > 0 ) {
  17020. laste = points[ points.length - 1 ];
  17021. cpx0 = laste.x;
  17022. cpy0 = laste.y;
  17023. } else {
  17024. laste = this.actions[ i - 1 ].args;
  17025. cpx0 = laste[ laste.length - 2 ];
  17026. cpy0 = laste[ laste.length - 1 ];
  17027. }
  17028. for ( j = 1; j <= divisions; j ++ ) {
  17029. t = j / divisions;
  17030. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17031. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17032. points.push( new THREE.Vector2( tx, ty ) );
  17033. }
  17034. break;
  17035. case THREE.PathActions.CSPLINE_THRU:
  17036. laste = this.actions[ i - 1 ].args;
  17037. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17038. var spts = [ last ];
  17039. var n = divisions * args[ 0 ].length;
  17040. spts = spts.concat( args[ 0 ] );
  17041. var spline = new THREE.SplineCurve( spts );
  17042. for ( j = 1; j <= n; j ++ ) {
  17043. points.push( spline.getPointAt( j / n ) ) ;
  17044. }
  17045. break;
  17046. case THREE.PathActions.ARC:
  17047. var aX = args[ 0 ], aY = args[ 1 ],
  17048. aRadius = args[ 2 ],
  17049. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17050. aClockwise = !!args[ 5 ];
  17051. var deltaAngle = aEndAngle - aStartAngle;
  17052. var angle;
  17053. var tdivisions = divisions * 2;
  17054. for ( j = 1; j <= tdivisions; j ++ ) {
  17055. t = j / tdivisions;
  17056. if ( ! aClockwise ) {
  17057. t = 1 - t;
  17058. }
  17059. angle = aStartAngle + t * deltaAngle;
  17060. tx = aX + aRadius * Math.cos( angle );
  17061. ty = aY + aRadius * Math.sin( angle );
  17062. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17063. points.push( new THREE.Vector2( tx, ty ) );
  17064. }
  17065. //console.log(points);
  17066. break;
  17067. case THREE.PathActions.ELLIPSE:
  17068. var aX = args[ 0 ], aY = args[ 1 ],
  17069. xRadius = args[ 2 ],
  17070. yRadius = args[ 3 ],
  17071. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17072. aClockwise = !!args[ 6 ];
  17073. var deltaAngle = aEndAngle - aStartAngle;
  17074. var angle;
  17075. var tdivisions = divisions * 2;
  17076. for ( j = 1; j <= tdivisions; j ++ ) {
  17077. t = j / tdivisions;
  17078. if ( ! aClockwise ) {
  17079. t = 1 - t;
  17080. }
  17081. angle = aStartAngle + t * deltaAngle;
  17082. tx = aX + xRadius * Math.cos( angle );
  17083. ty = aY + yRadius * Math.sin( angle );
  17084. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17085. points.push( new THREE.Vector2( tx, ty ) );
  17086. }
  17087. //console.log(points);
  17088. break;
  17089. } // end switch
  17090. }
  17091. // Normalize to remove the closing point by default.
  17092. var lastPoint = points[ points.length - 1];
  17093. var EPSILON = 0.0000000001;
  17094. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17095. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17096. points.splice( points.length - 1, 1);
  17097. if ( closedPath ) {
  17098. points.push( points[ 0 ] );
  17099. }
  17100. return points;
  17101. };
  17102. // Breaks path into shapes
  17103. THREE.Path.prototype.toShapes = function( isCCW ) {
  17104. var i, il, item, action, args;
  17105. var subPaths = [], lastPath = new THREE.Path();
  17106. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17107. item = this.actions[ i ];
  17108. args = item.args;
  17109. action = item.action;
  17110. if ( action == THREE.PathActions.MOVE_TO ) {
  17111. if ( lastPath.actions.length != 0 ) {
  17112. subPaths.push( lastPath );
  17113. lastPath = new THREE.Path();
  17114. }
  17115. }
  17116. lastPath[ action ].apply( lastPath, args );
  17117. }
  17118. if ( lastPath.actions.length != 0 ) {
  17119. subPaths.push( lastPath );
  17120. }
  17121. // console.log(subPaths);
  17122. if ( subPaths.length == 0 ) return [];
  17123. var solid, tmpPath, tmpShape, shapes = [];
  17124. if ( subPaths.length == 1) {
  17125. tmpPath = subPaths[0];
  17126. tmpShape = new THREE.Shape();
  17127. tmpShape.actions = tmpPath.actions;
  17128. tmpShape.curves = tmpPath.curves;
  17129. shapes.push( tmpShape );
  17130. return shapes;
  17131. }
  17132. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17133. holesFirst = isCCW ? !holesFirst : holesFirst;
  17134. // console.log("Holes first", holesFirst);
  17135. if ( holesFirst ) {
  17136. tmpShape = new THREE.Shape();
  17137. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17138. tmpPath = subPaths[ i ];
  17139. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17140. solid = isCCW ? !solid : solid;
  17141. if ( solid ) {
  17142. tmpShape.actions = tmpPath.actions;
  17143. tmpShape.curves = tmpPath.curves;
  17144. shapes.push( tmpShape );
  17145. tmpShape = new THREE.Shape();
  17146. //console.log('cw', i);
  17147. } else {
  17148. tmpShape.holes.push( tmpPath );
  17149. //console.log('ccw', i);
  17150. }
  17151. }
  17152. } else {
  17153. // Shapes first
  17154. tmpShape = undefined;
  17155. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17156. tmpPath = subPaths[ i ];
  17157. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17158. solid = isCCW ? !solid : solid;
  17159. if ( solid ) {
  17160. if ( tmpShape ) shapes.push( tmpShape );
  17161. tmpShape = new THREE.Shape();
  17162. tmpShape.actions = tmpPath.actions;
  17163. tmpShape.curves = tmpPath.curves;
  17164. } else {
  17165. tmpShape.holes.push( tmpPath );
  17166. }
  17167. }
  17168. shapes.push( tmpShape );
  17169. }
  17170. //console.log("shape", shapes);
  17171. return shapes;
  17172. };
  17173. /**
  17174. * @author zz85 / http://www.lab4games.net/zz85/blog
  17175. * Defines a 2d shape plane using paths.
  17176. **/
  17177. // STEP 1 Create a path.
  17178. // STEP 2 Turn path into shape.
  17179. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17180. // STEP 3a - Extract points from each shape, turn to vertices
  17181. // STEP 3b - Triangulate each shape, add faces.
  17182. THREE.Shape = function () {
  17183. THREE.Path.apply( this, arguments );
  17184. this.holes = [];
  17185. };
  17186. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17187. // Convenience method to return ExtrudeGeometry
  17188. THREE.Shape.prototype.extrude = function ( options ) {
  17189. var extruded = new THREE.ExtrudeGeometry( this, options );
  17190. return extruded;
  17191. };
  17192. // Convenience method to return ShapeGeometry
  17193. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17194. var geometry = new THREE.ShapeGeometry( this, options );
  17195. return geometry;
  17196. };
  17197. // Get points of holes
  17198. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17199. var i, il = this.holes.length, holesPts = [];
  17200. for ( i = 0; i < il; i ++ ) {
  17201. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17202. }
  17203. return holesPts;
  17204. };
  17205. // Get points of holes (spaced by regular distance)
  17206. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17207. var i, il = this.holes.length, holesPts = [];
  17208. for ( i = 0; i < il; i ++ ) {
  17209. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17210. }
  17211. return holesPts;
  17212. };
  17213. // Get points of shape and holes (keypoints based on segments parameter)
  17214. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17215. return {
  17216. shape: this.getTransformedPoints( divisions ),
  17217. holes: this.getPointsHoles( divisions )
  17218. };
  17219. };
  17220. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17221. if (this.useSpacedPoints) {
  17222. return this.extractAllSpacedPoints(divisions);
  17223. }
  17224. return this.extractAllPoints(divisions);
  17225. };
  17226. //
  17227. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17228. //
  17229. // return {
  17230. //
  17231. // shape: this.transform( bend, divisions ),
  17232. // holes: this.getPointsHoles( divisions, bend )
  17233. //
  17234. // };
  17235. //
  17236. // };
  17237. // Get points of shape and holes (spaced by regular distance)
  17238. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17239. return {
  17240. shape: this.getTransformedSpacedPoints( divisions ),
  17241. holes: this.getSpacedPointsHoles( divisions )
  17242. };
  17243. };
  17244. /**************************************************************
  17245. * Utils
  17246. **************************************************************/
  17247. THREE.Shape.Utils = {
  17248. /*
  17249. contour - array of vector2 for contour
  17250. holes - array of array of vector2
  17251. */
  17252. removeHoles: function ( contour, holes ) {
  17253. var shape = contour.concat(); // work on this shape
  17254. var allpoints = shape.concat();
  17255. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17256. var prevShapeVert, nextShapeVert,
  17257. prevHoleVert, nextHoleVert,
  17258. holeIndex, shapeIndex,
  17259. shapeId, shapeGroup,
  17260. h, h2,
  17261. hole, shortest, d,
  17262. p, pts1, pts2,
  17263. tmpShape1, tmpShape2,
  17264. tmpHole1, tmpHole2,
  17265. verts = [];
  17266. for ( h = 0; h < holes.length; h ++ ) {
  17267. hole = holes[ h ];
  17268. /*
  17269. shapeholes[ h ].concat(); // preserves original
  17270. holes.push( hole );
  17271. */
  17272. Array.prototype.push.apply( allpoints, hole );
  17273. shortest = Number.POSITIVE_INFINITY;
  17274. // Find the shortest pair of pts between shape and hole
  17275. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17276. // Using distanceToSquared() intead of distanceTo() should speed a little
  17277. // since running square roots operations are reduced.
  17278. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17279. pts1 = hole[ h2 ];
  17280. var dist = [];
  17281. for ( p = 0; p < shape.length; p++ ) {
  17282. pts2 = shape[ p ];
  17283. d = pts1.distanceToSquared( pts2 );
  17284. dist.push( d );
  17285. if ( d < shortest ) {
  17286. shortest = d;
  17287. holeIndex = h2;
  17288. shapeIndex = p;
  17289. }
  17290. }
  17291. }
  17292. //console.log("shortest", shortest, dist);
  17293. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17294. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17295. var areaapts = [
  17296. hole[ holeIndex ],
  17297. shape[ shapeIndex ],
  17298. shape[ prevShapeVert ]
  17299. ];
  17300. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17301. var areabpts = [
  17302. hole[ holeIndex ],
  17303. hole[ prevHoleVert ],
  17304. shape[ shapeIndex ]
  17305. ];
  17306. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17307. var shapeOffset = 1;
  17308. var holeOffset = -1;
  17309. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17310. shapeIndex += shapeOffset;
  17311. holeIndex += holeOffset;
  17312. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17313. shapeIndex %= shape.length;
  17314. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17315. holeIndex %= hole.length;
  17316. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17317. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17318. areaapts = [
  17319. hole[ holeIndex ],
  17320. shape[ shapeIndex ],
  17321. shape[ prevShapeVert ]
  17322. ];
  17323. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17324. areabpts = [
  17325. hole[ holeIndex ],
  17326. hole[ prevHoleVert ],
  17327. shape[ shapeIndex ]
  17328. ];
  17329. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17330. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17331. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17332. // In case areas are not correct.
  17333. //console.log("USE THIS");
  17334. shapeIndex = oldShapeIndex;
  17335. holeIndex = oldHoleIndex ;
  17336. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17337. shapeIndex %= shape.length;
  17338. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17339. holeIndex %= hole.length;
  17340. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17341. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17342. } else {
  17343. //console.log("USE THAT ")
  17344. }
  17345. tmpShape1 = shape.slice( 0, shapeIndex );
  17346. tmpShape2 = shape.slice( shapeIndex );
  17347. tmpHole1 = hole.slice( holeIndex );
  17348. tmpHole2 = hole.slice( 0, holeIndex );
  17349. // Should check orders here again?
  17350. var trianglea = [
  17351. hole[ holeIndex ],
  17352. shape[ shapeIndex ],
  17353. shape[ prevShapeVert ]
  17354. ];
  17355. var triangleb = [
  17356. hole[ holeIndex ] ,
  17357. hole[ prevHoleVert ],
  17358. shape[ shapeIndex ]
  17359. ];
  17360. verts.push( trianglea );
  17361. verts.push( triangleb );
  17362. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17363. }
  17364. return {
  17365. shape:shape, /* shape with no holes */
  17366. isolatedPts: verts, /* isolated faces */
  17367. allpoints: allpoints
  17368. }
  17369. },
  17370. triangulateShape: function ( contour, holes ) {
  17371. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17372. var shape = shapeWithoutHoles.shape,
  17373. allpoints = shapeWithoutHoles.allpoints,
  17374. isolatedPts = shapeWithoutHoles.isolatedPts;
  17375. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17376. // 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.
  17377. //console.log( "triangles",triangles, triangles.length );
  17378. //console.log( "allpoints",allpoints, allpoints.length );
  17379. var i, il, f, face,
  17380. key, index,
  17381. allPointsMap = {},
  17382. isolatedPointsMap = {};
  17383. // prepare all points map
  17384. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17385. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17386. if ( allPointsMap[ key ] !== undefined ) {
  17387. console.log( "Duplicate point", key );
  17388. }
  17389. allPointsMap[ key ] = i;
  17390. }
  17391. // check all face vertices against all points map
  17392. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17393. face = triangles[ i ];
  17394. for ( f = 0; f < 3; f ++ ) {
  17395. key = face[ f ].x + ":" + face[ f ].y;
  17396. index = allPointsMap[ key ];
  17397. if ( index !== undefined ) {
  17398. face[ f ] = index;
  17399. }
  17400. }
  17401. }
  17402. // check isolated points vertices against all points map
  17403. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17404. face = isolatedPts[ i ];
  17405. for ( f = 0; f < 3; f ++ ) {
  17406. key = face[ f ].x + ":" + face[ f ].y;
  17407. index = allPointsMap[ key ];
  17408. if ( index !== undefined ) {
  17409. face[ f ] = index;
  17410. }
  17411. }
  17412. }
  17413. return triangles.concat( isolatedPts );
  17414. }, // end triangulate shapes
  17415. /*
  17416. triangulate2 : function( pts, holes ) {
  17417. // For use with Poly2Tri.js
  17418. var allpts = pts.concat();
  17419. var shape = [];
  17420. for (var p in pts) {
  17421. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17422. }
  17423. var swctx = new js.poly2tri.SweepContext(shape);
  17424. for (var h in holes) {
  17425. var aHole = holes[h];
  17426. var newHole = []
  17427. for (i in aHole) {
  17428. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17429. allpts.push(aHole[i]);
  17430. }
  17431. swctx.AddHole(newHole);
  17432. }
  17433. var find;
  17434. var findIndexForPt = function (pt) {
  17435. find = new THREE.Vector2(pt.x, pt.y);
  17436. var p;
  17437. for (p=0, pl = allpts.length; p<pl; p++) {
  17438. if (allpts[p].equals(find)) return p;
  17439. }
  17440. return -1;
  17441. };
  17442. // triangulate
  17443. js.poly2tri.sweep.Triangulate(swctx);
  17444. var triangles = swctx.GetTriangles();
  17445. var tr ;
  17446. var facesPts = [];
  17447. for (var t in triangles) {
  17448. tr = triangles[t];
  17449. facesPts.push([
  17450. findIndexForPt(tr.GetPoint(0)),
  17451. findIndexForPt(tr.GetPoint(1)),
  17452. findIndexForPt(tr.GetPoint(2))
  17453. ]);
  17454. }
  17455. // console.log(facesPts);
  17456. // console.log("triangles", triangles.length, triangles);
  17457. // Returns array of faces with 3 element each
  17458. return facesPts;
  17459. },
  17460. */
  17461. isClockWise: function ( pts ) {
  17462. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17463. },
  17464. // Bezier Curves formulas obtained from
  17465. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17466. // Quad Bezier Functions
  17467. b2p0: function ( t, p ) {
  17468. var k = 1 - t;
  17469. return k * k * p;
  17470. },
  17471. b2p1: function ( t, p ) {
  17472. return 2 * ( 1 - t ) * t * p;
  17473. },
  17474. b2p2: function ( t, p ) {
  17475. return t * t * p;
  17476. },
  17477. b2: function ( t, p0, p1, p2 ) {
  17478. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17479. },
  17480. // Cubic Bezier Functions
  17481. b3p0: function ( t, p ) {
  17482. var k = 1 - t;
  17483. return k * k * k * p;
  17484. },
  17485. b3p1: function ( t, p ) {
  17486. var k = 1 - t;
  17487. return 3 * k * k * t * p;
  17488. },
  17489. b3p2: function ( t, p ) {
  17490. var k = 1 - t;
  17491. return 3 * k * t * t * p;
  17492. },
  17493. b3p3: function ( t, p ) {
  17494. return t * t * t * p;
  17495. },
  17496. b3: function ( t, p0, p1, p2, p3 ) {
  17497. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17498. }
  17499. };
  17500. /**************************************************************
  17501. * Line
  17502. **************************************************************/
  17503. THREE.LineCurve = function ( v1, v2 ) {
  17504. this.v1 = v1;
  17505. this.v2 = v2;
  17506. };
  17507. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17508. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17509. var point = this.v2.clone().sub(this.v1);
  17510. point.multiplyScalar( t ).add( this.v1 );
  17511. return point;
  17512. };
  17513. // Line curve is linear, so we can overwrite default getPointAt
  17514. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17515. return this.getPoint( u );
  17516. };
  17517. THREE.LineCurve.prototype.getTangent = function( t ) {
  17518. var tangent = this.v2.clone().sub(this.v1);
  17519. return tangent.normalize();
  17520. };
  17521. /**************************************************************
  17522. * Quadratic Bezier curve
  17523. **************************************************************/
  17524. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17525. this.v0 = v0;
  17526. this.v1 = v1;
  17527. this.v2 = v2;
  17528. };
  17529. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17530. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17531. var tx, ty;
  17532. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17533. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17534. return new THREE.Vector2( tx, ty );
  17535. };
  17536. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17537. var tx, ty;
  17538. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17539. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17540. // returns unit vector
  17541. var tangent = new THREE.Vector2( tx, ty );
  17542. tangent.normalize();
  17543. return tangent;
  17544. };
  17545. /**************************************************************
  17546. * Cubic Bezier curve
  17547. **************************************************************/
  17548. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17549. this.v0 = v0;
  17550. this.v1 = v1;
  17551. this.v2 = v2;
  17552. this.v3 = v3;
  17553. };
  17554. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17555. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17556. var tx, ty;
  17557. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17558. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17559. return new THREE.Vector2( tx, ty );
  17560. };
  17561. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17562. var tx, ty;
  17563. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17564. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17565. var tangent = new THREE.Vector2( tx, ty );
  17566. tangent.normalize();
  17567. return tangent;
  17568. };
  17569. /**************************************************************
  17570. * Spline curve
  17571. **************************************************************/
  17572. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17573. this.points = (points == undefined) ? [] : points;
  17574. };
  17575. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17576. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17577. var v = new THREE.Vector2();
  17578. var c = [];
  17579. var points = this.points, point, intPoint, weight;
  17580. point = ( points.length - 1 ) * t;
  17581. intPoint = Math.floor( point );
  17582. weight = point - intPoint;
  17583. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17584. c[ 1 ] = intPoint;
  17585. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17586. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17587. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17588. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17589. return v;
  17590. };
  17591. /**************************************************************
  17592. * Ellipse curve
  17593. **************************************************************/
  17594. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17595. this.aX = aX;
  17596. this.aY = aY;
  17597. this.xRadius = xRadius;
  17598. this.yRadius = yRadius;
  17599. this.aStartAngle = aStartAngle;
  17600. this.aEndAngle = aEndAngle;
  17601. this.aClockwise = aClockwise;
  17602. };
  17603. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17604. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17605. var angle;
  17606. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17607. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17608. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17609. if ( this.aClockwise === true ) {
  17610. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17611. } else {
  17612. angle = this.aStartAngle + t * deltaAngle;
  17613. }
  17614. var tx = this.aX + this.xRadius * Math.cos( angle );
  17615. var ty = this.aY + this.yRadius * Math.sin( angle );
  17616. return new THREE.Vector2( tx, ty );
  17617. };
  17618. /**************************************************************
  17619. * Arc curve
  17620. **************************************************************/
  17621. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17622. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17623. };
  17624. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17625. /**************************************************************
  17626. * Line3D
  17627. **************************************************************/
  17628. THREE.LineCurve3 = THREE.Curve.create(
  17629. function ( v1, v2 ) {
  17630. this.v1 = v1;
  17631. this.v2 = v2;
  17632. },
  17633. function ( t ) {
  17634. var r = new THREE.Vector3();
  17635. r.subVectors( this.v2, this.v1 ); // diff
  17636. r.multiplyScalar( t );
  17637. r.add( this.v1 );
  17638. return r;
  17639. }
  17640. );
  17641. /**************************************************************
  17642. * Quadratic Bezier 3D curve
  17643. **************************************************************/
  17644. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17645. function ( v0, v1, v2 ) {
  17646. this.v0 = v0;
  17647. this.v1 = v1;
  17648. this.v2 = v2;
  17649. },
  17650. function ( t ) {
  17651. var tx, ty, tz;
  17652. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17653. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17654. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17655. return new THREE.Vector3( tx, ty, tz );
  17656. }
  17657. );
  17658. /**************************************************************
  17659. * Cubic Bezier 3D curve
  17660. **************************************************************/
  17661. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17662. function ( v0, v1, v2, v3 ) {
  17663. this.v0 = v0;
  17664. this.v1 = v1;
  17665. this.v2 = v2;
  17666. this.v3 = v3;
  17667. },
  17668. function ( t ) {
  17669. var tx, ty, tz;
  17670. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17671. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17672. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17673. return new THREE.Vector3( tx, ty, tz );
  17674. }
  17675. );
  17676. /**************************************************************
  17677. * Spline 3D curve
  17678. **************************************************************/
  17679. THREE.SplineCurve3 = THREE.Curve.create(
  17680. function ( points /* array of Vector3 */) {
  17681. this.points = (points == undefined) ? [] : points;
  17682. },
  17683. function ( t ) {
  17684. var v = new THREE.Vector3();
  17685. var c = [];
  17686. var points = this.points, point, intPoint, weight;
  17687. point = ( points.length - 1 ) * t;
  17688. intPoint = Math.floor( point );
  17689. weight = point - intPoint;
  17690. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17691. c[ 1 ] = intPoint;
  17692. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17693. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17694. var pt0 = points[ c[0] ],
  17695. pt1 = points[ c[1] ],
  17696. pt2 = points[ c[2] ],
  17697. pt3 = points[ c[3] ];
  17698. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17699. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17700. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17701. return v;
  17702. }
  17703. );
  17704. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17705. // var v = new THREE.Vector3();
  17706. // var c = [];
  17707. // var points = this.points, point, intPoint, weight;
  17708. // point = ( points.length - 1 ) * t;
  17709. // intPoint = Math.floor( point );
  17710. // weight = point - intPoint;
  17711. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17712. // c[ 1 ] = intPoint;
  17713. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17714. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17715. // var pt0 = points[ c[0] ],
  17716. // pt1 = points[ c[1] ],
  17717. // pt2 = points[ c[2] ],
  17718. // pt3 = points[ c[3] ];
  17719. // // t = weight;
  17720. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17721. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17722. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17723. // return v;
  17724. // }
  17725. /**************************************************************
  17726. * Closed Spline 3D curve
  17727. **************************************************************/
  17728. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17729. function ( points /* array of Vector3 */) {
  17730. this.points = (points == undefined) ? [] : points;
  17731. },
  17732. function ( t ) {
  17733. var v = new THREE.Vector3();
  17734. var c = [];
  17735. var points = this.points, point, intPoint, weight;
  17736. point = ( points.length - 0 ) * t;
  17737. // This needs to be from 0-length +1
  17738. intPoint = Math.floor( point );
  17739. weight = point - intPoint;
  17740. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17741. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17742. c[ 1 ] = ( intPoint ) % points.length;
  17743. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17744. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17745. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17746. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17747. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17748. return v;
  17749. }
  17750. );
  17751. /**
  17752. * @author mikael emtinger / http://gomo.se/
  17753. */
  17754. THREE.AnimationHandler = (function() {
  17755. var playing = [];
  17756. var library = {};
  17757. var that = {};
  17758. //--- update ---
  17759. that.update = function( deltaTimeMS ) {
  17760. for( var i = 0; i < playing.length; i ++ )
  17761. playing[ i ].update( deltaTimeMS );
  17762. };
  17763. //--- add ---
  17764. that.addToUpdate = function( animation ) {
  17765. if ( playing.indexOf( animation ) === -1 )
  17766. playing.push( animation );
  17767. };
  17768. //--- remove ---
  17769. that.removeFromUpdate = function( animation ) {
  17770. var index = playing.indexOf( animation );
  17771. if( index !== -1 )
  17772. playing.splice( index, 1 );
  17773. };
  17774. //--- add ---
  17775. that.add = function( data ) {
  17776. if ( library[ data.name ] !== undefined )
  17777. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17778. library[ data.name ] = data;
  17779. initData( data );
  17780. };
  17781. //--- get ---
  17782. that.get = function( name ) {
  17783. if ( typeof name === "string" ) {
  17784. if ( library[ name ] ) {
  17785. return library[ name ];
  17786. } else {
  17787. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17788. return null;
  17789. }
  17790. } else {
  17791. // todo: add simple tween library
  17792. }
  17793. };
  17794. //--- parse ---
  17795. that.parse = function( root ) {
  17796. // setup hierarchy
  17797. var hierarchy = [];
  17798. if ( root instanceof THREE.SkinnedMesh ) {
  17799. for( var b = 0; b < root.bones.length; b++ ) {
  17800. hierarchy.push( root.bones[ b ] );
  17801. }
  17802. } else {
  17803. parseRecurseHierarchy( root, hierarchy );
  17804. }
  17805. return hierarchy;
  17806. };
  17807. var parseRecurseHierarchy = function( root, hierarchy ) {
  17808. hierarchy.push( root );
  17809. for( var c = 0; c < root.children.length; c++ )
  17810. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17811. }
  17812. //--- init data ---
  17813. var initData = function( data ) {
  17814. if( data.initialized === true )
  17815. return;
  17816. // loop through all keys
  17817. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17818. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17819. // remove minus times
  17820. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17821. data.hierarchy[ h ].keys[ k ].time = 0;
  17822. // create quaternions
  17823. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17824. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17825. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17826. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17827. }
  17828. }
  17829. // prepare morph target keys
  17830. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17831. // get all used
  17832. var usedMorphTargets = {};
  17833. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17834. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17835. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17836. usedMorphTargets[ morphTargetName ] = -1;
  17837. }
  17838. }
  17839. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17840. // set all used on all frames
  17841. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17842. var influences = {};
  17843. for ( var morphTargetName in usedMorphTargets ) {
  17844. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17845. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17846. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17847. break;
  17848. }
  17849. }
  17850. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17851. influences[ morphTargetName ] = 0;
  17852. }
  17853. }
  17854. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17855. }
  17856. }
  17857. // remove all keys that are on the same time
  17858. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17859. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17860. data.hierarchy[ h ].keys.splice( k, 1 );
  17861. k --;
  17862. }
  17863. }
  17864. // set index
  17865. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17866. data.hierarchy[ h ].keys[ k ].index = k;
  17867. }
  17868. }
  17869. // JIT
  17870. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17871. data.JIT = {};
  17872. data.JIT.hierarchy = [];
  17873. for( var h = 0; h < data.hierarchy.length; h ++ )
  17874. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17875. // done
  17876. data.initialized = true;
  17877. };
  17878. // interpolation types
  17879. that.LINEAR = 0;
  17880. that.CATMULLROM = 1;
  17881. that.CATMULLROM_FORWARD = 2;
  17882. return that;
  17883. }());
  17884. /**
  17885. * @author mikael emtinger / http://gomo.se/
  17886. * @author mrdoob / http://mrdoob.com/
  17887. * @author alteredq / http://alteredqualia.com/
  17888. */
  17889. THREE.Animation = function ( root, name, interpolationType ) {
  17890. this.root = root;
  17891. this.data = THREE.AnimationHandler.get( name );
  17892. this.hierarchy = THREE.AnimationHandler.parse( root );
  17893. this.currentTime = 0;
  17894. this.timeScale = 1;
  17895. this.isPlaying = false;
  17896. this.isPaused = true;
  17897. this.loop = true;
  17898. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17899. this.points = [];
  17900. this.target = new THREE.Vector3();
  17901. };
  17902. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17903. if ( this.isPlaying === false ) {
  17904. this.isPlaying = true;
  17905. this.loop = loop !== undefined ? loop : true;
  17906. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17907. // reset key cache
  17908. var h, hl = this.hierarchy.length,
  17909. object;
  17910. for ( h = 0; h < hl; h ++ ) {
  17911. object = this.hierarchy[ h ];
  17912. object.matrixAutoUpdate = true;
  17913. if ( object.animationCache === undefined ) {
  17914. object.animationCache = {};
  17915. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17916. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17917. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17918. }
  17919. var prevKey = object.animationCache.prevKey;
  17920. var nextKey = object.animationCache.nextKey;
  17921. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17922. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17923. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17924. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17925. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17926. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17927. }
  17928. this.update( 0 );
  17929. }
  17930. this.isPaused = false;
  17931. THREE.AnimationHandler.addToUpdate( this );
  17932. };
  17933. THREE.Animation.prototype.pause = function() {
  17934. if ( this.isPaused === true ) {
  17935. THREE.AnimationHandler.addToUpdate( this );
  17936. } else {
  17937. THREE.AnimationHandler.removeFromUpdate( this );
  17938. }
  17939. this.isPaused = !this.isPaused;
  17940. };
  17941. THREE.Animation.prototype.stop = function() {
  17942. this.isPlaying = false;
  17943. this.isPaused = false;
  17944. THREE.AnimationHandler.removeFromUpdate( this );
  17945. };
  17946. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17947. // early out
  17948. if ( this.isPlaying === false ) return;
  17949. // vars
  17950. var types = [ "pos", "rot", "scl" ];
  17951. var type;
  17952. var scale;
  17953. var vector;
  17954. var prevXYZ, nextXYZ;
  17955. var prevKey, nextKey;
  17956. var object;
  17957. var animationCache;
  17958. var frame;
  17959. var JIThierarchy = this.data.JIT.hierarchy;
  17960. var currentTime, unloopedCurrentTime;
  17961. var currentPoint, forwardPoint, angle;
  17962. this.currentTime += deltaTimeMS * this.timeScale;
  17963. unloopedCurrentTime = this.currentTime;
  17964. currentTime = this.currentTime = this.currentTime % this.data.length;
  17965. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17966. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17967. object = this.hierarchy[ h ];
  17968. animationCache = object.animationCache;
  17969. // loop through pos/rot/scl
  17970. for ( var t = 0; t < 3; t ++ ) {
  17971. // get keys
  17972. type = types[ t ];
  17973. prevKey = animationCache.prevKey[ type ];
  17974. nextKey = animationCache.nextKey[ type ];
  17975. // switch keys?
  17976. if ( nextKey.time <= unloopedCurrentTime ) {
  17977. // did we loop?
  17978. if ( currentTime < unloopedCurrentTime ) {
  17979. if ( this.loop ) {
  17980. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17981. nextKey = this.getNextKeyWith( type, h, 1 );
  17982. while( nextKey.time < currentTime ) {
  17983. prevKey = nextKey;
  17984. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17985. }
  17986. } else {
  17987. this.stop();
  17988. return;
  17989. }
  17990. } else {
  17991. do {
  17992. prevKey = nextKey;
  17993. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17994. } while( nextKey.time < currentTime )
  17995. }
  17996. animationCache.prevKey[ type ] = prevKey;
  17997. animationCache.nextKey[ type ] = nextKey;
  17998. }
  17999. object.matrixAutoUpdate = true;
  18000. object.matrixWorldNeedsUpdate = true;
  18001. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18002. prevXYZ = prevKey[ type ];
  18003. nextXYZ = nextKey[ type ];
  18004. // check scale error
  18005. if ( scale < 0 || scale > 1 ) {
  18006. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18007. scale = scale < 0 ? 0 : 1;
  18008. }
  18009. // interpolate
  18010. if ( type === "pos" ) {
  18011. vector = object.position;
  18012. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18013. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18014. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18015. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18016. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18017. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18018. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18019. this.points[ 1 ] = prevXYZ;
  18020. this.points[ 2 ] = nextXYZ;
  18021. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18022. scale = scale * 0.33 + 0.33;
  18023. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18024. vector.x = currentPoint[ 0 ];
  18025. vector.y = currentPoint[ 1 ];
  18026. vector.z = currentPoint[ 2 ];
  18027. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18028. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18029. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18030. this.target.sub( vector );
  18031. this.target.y = 0;
  18032. this.target.normalize();
  18033. angle = Math.atan2( this.target.x, this.target.z );
  18034. object.rotation.set( 0, angle, 0 );
  18035. }
  18036. }
  18037. } else if ( type === "rot" ) {
  18038. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18039. } else if ( type === "scl" ) {
  18040. vector = object.scale;
  18041. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18042. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18043. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18044. }
  18045. }
  18046. }
  18047. };
  18048. // Catmull-Rom spline
  18049. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18050. var c = [], v3 = [],
  18051. point, intPoint, weight, w2, w3,
  18052. pa, pb, pc, pd;
  18053. point = ( points.length - 1 ) * scale;
  18054. intPoint = Math.floor( point );
  18055. weight = point - intPoint;
  18056. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18057. c[ 1 ] = intPoint;
  18058. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18059. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18060. pa = points[ c[ 0 ] ];
  18061. pb = points[ c[ 1 ] ];
  18062. pc = points[ c[ 2 ] ];
  18063. pd = points[ c[ 3 ] ];
  18064. w2 = weight * weight;
  18065. w3 = weight * w2;
  18066. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18067. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18068. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18069. return v3;
  18070. };
  18071. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18072. var v0 = ( p2 - p0 ) * 0.5,
  18073. v1 = ( p3 - p1 ) * 0.5;
  18074. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18075. };
  18076. // Get next key with
  18077. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18078. var keys = this.data.hierarchy[ h ].keys;
  18079. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18080. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18081. key = key < keys.length - 1 ? key : keys.length - 1;
  18082. } else {
  18083. key = key % keys.length;
  18084. }
  18085. for ( ; key < keys.length; key++ ) {
  18086. if ( keys[ key ][ type ] !== undefined ) {
  18087. return keys[ key ];
  18088. }
  18089. }
  18090. return this.data.hierarchy[ h ].keys[ 0 ];
  18091. };
  18092. // Get previous key with
  18093. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18094. var keys = this.data.hierarchy[ h ].keys;
  18095. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18096. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18097. key = key > 0 ? key : 0;
  18098. } else {
  18099. key = key >= 0 ? key : key + keys.length;
  18100. }
  18101. for ( ; key >= 0; key -- ) {
  18102. if ( keys[ key ][ type ] !== undefined ) {
  18103. return keys[ key ];
  18104. }
  18105. }
  18106. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18107. };
  18108. /**
  18109. * @author mikael emtinger / http://gomo.se/
  18110. * @author mrdoob / http://mrdoob.com/
  18111. * @author alteredq / http://alteredqualia.com/
  18112. * @author khang duong
  18113. * @author erik kitson
  18114. */
  18115. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18116. this.root = root;
  18117. this.data = THREE.AnimationHandler.get( data );
  18118. this.hierarchy = THREE.AnimationHandler.parse( root );
  18119. this.currentTime = 0;
  18120. this.timeScale = 0.001;
  18121. this.isPlaying = false;
  18122. this.isPaused = true;
  18123. this.loop = true;
  18124. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18125. // initialize to first keyframes
  18126. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18127. var keys = this.data.hierarchy[h].keys,
  18128. sids = this.data.hierarchy[h].sids,
  18129. obj = this.hierarchy[h];
  18130. if ( keys.length && sids ) {
  18131. for ( var s = 0; s < sids.length; s++ ) {
  18132. var sid = sids[ s ],
  18133. next = this.getNextKeyWith( sid, h, 0 );
  18134. if ( next ) {
  18135. next.apply( sid );
  18136. }
  18137. }
  18138. obj.matrixAutoUpdate = false;
  18139. this.data.hierarchy[h].node.updateMatrix();
  18140. obj.matrixWorldNeedsUpdate = true;
  18141. }
  18142. }
  18143. };
  18144. // Play
  18145. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18146. if( !this.isPlaying ) {
  18147. this.isPlaying = true;
  18148. this.loop = loop !== undefined ? loop : true;
  18149. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18150. this.startTimeMs = startTimeMS;
  18151. this.startTime = 10000000;
  18152. this.endTime = -this.startTime;
  18153. // reset key cache
  18154. var h, hl = this.hierarchy.length,
  18155. object,
  18156. node;
  18157. for ( h = 0; h < hl; h++ ) {
  18158. object = this.hierarchy[ h ];
  18159. node = this.data.hierarchy[ h ];
  18160. if ( node.animationCache === undefined ) {
  18161. node.animationCache = {};
  18162. node.animationCache.prevKey = null;
  18163. node.animationCache.nextKey = null;
  18164. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18165. }
  18166. var keys = this.data.hierarchy[h].keys;
  18167. if (keys.length) {
  18168. node.animationCache.prevKey = keys[ 0 ];
  18169. node.animationCache.nextKey = keys[ 1 ];
  18170. this.startTime = Math.min( keys[0].time, this.startTime );
  18171. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18172. }
  18173. }
  18174. this.update( 0 );
  18175. }
  18176. this.isPaused = false;
  18177. THREE.AnimationHandler.addToUpdate( this );
  18178. };
  18179. // Pause
  18180. THREE.KeyFrameAnimation.prototype.pause = function() {
  18181. if( this.isPaused ) {
  18182. THREE.AnimationHandler.addToUpdate( this );
  18183. } else {
  18184. THREE.AnimationHandler.removeFromUpdate( this );
  18185. }
  18186. this.isPaused = !this.isPaused;
  18187. };
  18188. // Stop
  18189. THREE.KeyFrameAnimation.prototype.stop = function() {
  18190. this.isPlaying = false;
  18191. this.isPaused = false;
  18192. THREE.AnimationHandler.removeFromUpdate( this );
  18193. // reset JIT matrix and remove cache
  18194. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18195. var obj = this.hierarchy[ h ];
  18196. var node = this.data.hierarchy[ h ];
  18197. if ( node.animationCache !== undefined ) {
  18198. var original = node.animationCache.originalMatrix;
  18199. if( obj instanceof THREE.Bone ) {
  18200. original.copy( obj.skinMatrix );
  18201. obj.skinMatrix = original;
  18202. } else {
  18203. original.copy( obj.matrix );
  18204. obj.matrix = original;
  18205. }
  18206. delete node.animationCache;
  18207. }
  18208. }
  18209. };
  18210. // Update
  18211. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18212. // early out
  18213. if( !this.isPlaying ) return;
  18214. // vars
  18215. var prevKey, nextKey;
  18216. var object;
  18217. var node;
  18218. var frame;
  18219. var JIThierarchy = this.data.JIT.hierarchy;
  18220. var currentTime, unloopedCurrentTime;
  18221. var looped;
  18222. // update
  18223. this.currentTime += deltaTimeMS * this.timeScale;
  18224. unloopedCurrentTime = this.currentTime;
  18225. currentTime = this.currentTime = this.currentTime % this.data.length;
  18226. // if looped around, the current time should be based on the startTime
  18227. if ( currentTime < this.startTimeMs ) {
  18228. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18229. }
  18230. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18231. looped = currentTime < unloopedCurrentTime;
  18232. if ( looped && !this.loop ) {
  18233. // Set the animation to the last keyframes and stop
  18234. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18235. var keys = this.data.hierarchy[h].keys,
  18236. sids = this.data.hierarchy[h].sids,
  18237. end = keys.length-1,
  18238. obj = this.hierarchy[h];
  18239. if ( keys.length ) {
  18240. for ( var s = 0; s < sids.length; s++ ) {
  18241. var sid = sids[ s ],
  18242. prev = this.getPrevKeyWith( sid, h, end );
  18243. if ( prev ) {
  18244. prev.apply( sid );
  18245. }
  18246. }
  18247. this.data.hierarchy[h].node.updateMatrix();
  18248. obj.matrixWorldNeedsUpdate = true;
  18249. }
  18250. }
  18251. this.stop();
  18252. return;
  18253. }
  18254. // check pre-infinity
  18255. if ( currentTime < this.startTime ) {
  18256. return;
  18257. }
  18258. // update
  18259. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18260. object = this.hierarchy[ h ];
  18261. node = this.data.hierarchy[ h ];
  18262. var keys = node.keys,
  18263. animationCache = node.animationCache;
  18264. // use JIT?
  18265. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18266. if( object instanceof THREE.Bone ) {
  18267. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18268. object.matrixWorldNeedsUpdate = false;
  18269. } else {
  18270. object.matrix = JIThierarchy[ h ][ frame ];
  18271. object.matrixWorldNeedsUpdate = true;
  18272. }
  18273. // use interpolation
  18274. } else if ( keys.length ) {
  18275. // make sure so original matrix and not JIT matrix is set
  18276. if ( this.JITCompile && animationCache ) {
  18277. if( object instanceof THREE.Bone ) {
  18278. object.skinMatrix = animationCache.originalMatrix;
  18279. } else {
  18280. object.matrix = animationCache.originalMatrix;
  18281. }
  18282. }
  18283. prevKey = animationCache.prevKey;
  18284. nextKey = animationCache.nextKey;
  18285. if ( prevKey && nextKey ) {
  18286. // switch keys?
  18287. if ( nextKey.time <= unloopedCurrentTime ) {
  18288. // did we loop?
  18289. if ( looped && this.loop ) {
  18290. prevKey = keys[ 0 ];
  18291. nextKey = keys[ 1 ];
  18292. while ( nextKey.time < currentTime ) {
  18293. prevKey = nextKey;
  18294. nextKey = keys[ prevKey.index + 1 ];
  18295. }
  18296. } else if ( !looped ) {
  18297. var lastIndex = keys.length - 1;
  18298. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18299. prevKey = nextKey;
  18300. nextKey = keys[ prevKey.index + 1 ];
  18301. }
  18302. }
  18303. animationCache.prevKey = prevKey;
  18304. animationCache.nextKey = nextKey;
  18305. }
  18306. if(nextKey.time >= currentTime)
  18307. prevKey.interpolate( nextKey, currentTime );
  18308. else
  18309. prevKey.interpolate( nextKey, nextKey.time);
  18310. }
  18311. this.data.hierarchy[h].node.updateMatrix();
  18312. object.matrixWorldNeedsUpdate = true;
  18313. }
  18314. }
  18315. // update JIT?
  18316. if ( this.JITCompile ) {
  18317. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18318. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18319. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18320. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18321. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18322. } else {
  18323. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18324. }
  18325. }
  18326. }
  18327. }
  18328. };
  18329. // Get next key with
  18330. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18331. var keys = this.data.hierarchy[ h ].keys;
  18332. key = key % keys.length;
  18333. for ( ; key < keys.length; key++ ) {
  18334. if ( keys[ key ].hasTarget( sid ) ) {
  18335. return keys[ key ];
  18336. }
  18337. }
  18338. return keys[ 0 ];
  18339. };
  18340. // Get previous key with
  18341. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18342. var keys = this.data.hierarchy[ h ].keys;
  18343. key = key >= 0 ? key : key + keys.length;
  18344. for ( ; key >= 0; key-- ) {
  18345. if ( keys[ key ].hasTarget( sid ) ) {
  18346. return keys[ key ];
  18347. }
  18348. }
  18349. return keys[ keys.length - 1 ];
  18350. };
  18351. /**
  18352. * Camera for rendering cube maps
  18353. * - renders scene into axis-aligned cube
  18354. *
  18355. * @author alteredq / http://alteredqualia.com/
  18356. */
  18357. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18358. THREE.Object3D.call( this );
  18359. var fov = 90, aspect = 1;
  18360. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18361. cameraPX.up.set( 0, -1, 0 );
  18362. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18363. this.add( cameraPX );
  18364. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18365. cameraNX.up.set( 0, -1, 0 );
  18366. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18367. this.add( cameraNX );
  18368. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18369. cameraPY.up.set( 0, 0, 1 );
  18370. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18371. this.add( cameraPY );
  18372. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18373. cameraNY.up.set( 0, 0, -1 );
  18374. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18375. this.add( cameraNY );
  18376. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18377. cameraPZ.up.set( 0, -1, 0 );
  18378. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18379. this.add( cameraPZ );
  18380. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18381. cameraNZ.up.set( 0, -1, 0 );
  18382. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18383. this.add( cameraNZ );
  18384. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18385. this.updateCubeMap = function ( renderer, scene ) {
  18386. var renderTarget = this.renderTarget;
  18387. var generateMipmaps = renderTarget.generateMipmaps;
  18388. renderTarget.generateMipmaps = false;
  18389. renderTarget.activeCubeFace = 0;
  18390. renderer.render( scene, cameraPX, renderTarget );
  18391. renderTarget.activeCubeFace = 1;
  18392. renderer.render( scene, cameraNX, renderTarget );
  18393. renderTarget.activeCubeFace = 2;
  18394. renderer.render( scene, cameraPY, renderTarget );
  18395. renderTarget.activeCubeFace = 3;
  18396. renderer.render( scene, cameraNY, renderTarget );
  18397. renderTarget.activeCubeFace = 4;
  18398. renderer.render( scene, cameraPZ, renderTarget );
  18399. renderTarget.generateMipmaps = generateMipmaps;
  18400. renderTarget.activeCubeFace = 5;
  18401. renderer.render( scene, cameraNZ, renderTarget );
  18402. };
  18403. };
  18404. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18405. /*
  18406. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18407. *
  18408. * A general perpose camera, for setting FOV, Lens Focal Length,
  18409. * and switching between perspective and orthographic views easily.
  18410. * Use this only if you do not wish to manage
  18411. * both a Orthographic and Perspective Camera
  18412. *
  18413. */
  18414. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18415. THREE.Camera.call( this );
  18416. this.fov = fov;
  18417. this.left = -width / 2;
  18418. this.right = width / 2
  18419. this.top = height / 2;
  18420. this.bottom = -height / 2;
  18421. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18422. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18423. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18424. this.zoom = 1;
  18425. this.toPerspective();
  18426. var aspect = width/height;
  18427. };
  18428. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18429. THREE.CombinedCamera.prototype.toPerspective = function () {
  18430. // Switches to the Perspective Camera
  18431. this.near = this.cameraP.near;
  18432. this.far = this.cameraP.far;
  18433. this.cameraP.fov = this.fov / this.zoom ;
  18434. this.cameraP.updateProjectionMatrix();
  18435. this.projectionMatrix = this.cameraP.projectionMatrix;
  18436. this.inPerspectiveMode = true;
  18437. this.inOrthographicMode = false;
  18438. };
  18439. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18440. // Switches to the Orthographic camera estimating viewport from Perspective
  18441. var fov = this.fov;
  18442. var aspect = this.cameraP.aspect;
  18443. var near = this.cameraP.near;
  18444. var far = this.cameraP.far;
  18445. // The size that we set is the mid plane of the viewing frustum
  18446. var hyperfocus = ( near + far ) / 2;
  18447. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18448. var planeHeight = 2 * halfHeight;
  18449. var planeWidth = planeHeight * aspect;
  18450. var halfWidth = planeWidth / 2;
  18451. halfHeight /= this.zoom;
  18452. halfWidth /= this.zoom;
  18453. this.cameraO.left = -halfWidth;
  18454. this.cameraO.right = halfWidth;
  18455. this.cameraO.top = halfHeight;
  18456. this.cameraO.bottom = -halfHeight;
  18457. // this.cameraO.left = -farHalfWidth;
  18458. // this.cameraO.right = farHalfWidth;
  18459. // this.cameraO.top = farHalfHeight;
  18460. // this.cameraO.bottom = -farHalfHeight;
  18461. // this.cameraO.left = this.left / this.zoom;
  18462. // this.cameraO.right = this.right / this.zoom;
  18463. // this.cameraO.top = this.top / this.zoom;
  18464. // this.cameraO.bottom = this.bottom / this.zoom;
  18465. this.cameraO.updateProjectionMatrix();
  18466. this.near = this.cameraO.near;
  18467. this.far = this.cameraO.far;
  18468. this.projectionMatrix = this.cameraO.projectionMatrix;
  18469. this.inPerspectiveMode = false;
  18470. this.inOrthographicMode = true;
  18471. };
  18472. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18473. this.cameraP.aspect = width / height;
  18474. this.left = -width / 2;
  18475. this.right = width / 2
  18476. this.top = height / 2;
  18477. this.bottom = -height / 2;
  18478. };
  18479. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18480. this.fov = fov;
  18481. if ( this.inPerspectiveMode ) {
  18482. this.toPerspective();
  18483. } else {
  18484. this.toOrthographic();
  18485. }
  18486. };
  18487. // For mantaining similar API with PerspectiveCamera
  18488. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18489. if ( this.inPerspectiveMode ) {
  18490. this.toPerspective();
  18491. } else {
  18492. this.toPerspective();
  18493. this.toOrthographic();
  18494. }
  18495. };
  18496. /*
  18497. * Uses Focal Length (in mm) to estimate and set FOV
  18498. * 35mm (fullframe) camera is used if frame size is not specified;
  18499. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18500. */
  18501. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18502. if ( frameHeight === undefined ) frameHeight = 24;
  18503. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18504. this.setFov( fov );
  18505. return fov;
  18506. };
  18507. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18508. this.zoom = zoom;
  18509. if ( this.inPerspectiveMode ) {
  18510. this.toPerspective();
  18511. } else {
  18512. this.toOrthographic();
  18513. }
  18514. };
  18515. THREE.CombinedCamera.prototype.toFrontView = function() {
  18516. this.rotation.x = 0;
  18517. this.rotation.y = 0;
  18518. this.rotation.z = 0;
  18519. // should we be modifing the matrix instead?
  18520. this.rotationAutoUpdate = false;
  18521. };
  18522. THREE.CombinedCamera.prototype.toBackView = function() {
  18523. this.rotation.x = 0;
  18524. this.rotation.y = Math.PI;
  18525. this.rotation.z = 0;
  18526. this.rotationAutoUpdate = false;
  18527. };
  18528. THREE.CombinedCamera.prototype.toLeftView = function() {
  18529. this.rotation.x = 0;
  18530. this.rotation.y = - Math.PI / 2;
  18531. this.rotation.z = 0;
  18532. this.rotationAutoUpdate = false;
  18533. };
  18534. THREE.CombinedCamera.prototype.toRightView = function() {
  18535. this.rotation.x = 0;
  18536. this.rotation.y = Math.PI / 2;
  18537. this.rotation.z = 0;
  18538. this.rotationAutoUpdate = false;
  18539. };
  18540. THREE.CombinedCamera.prototype.toTopView = function() {
  18541. this.rotation.x = - Math.PI / 2;
  18542. this.rotation.y = 0;
  18543. this.rotation.z = 0;
  18544. this.rotationAutoUpdate = false;
  18545. };
  18546. THREE.CombinedCamera.prototype.toBottomView = function() {
  18547. this.rotation.x = Math.PI / 2;
  18548. this.rotation.y = 0;
  18549. this.rotation.z = 0;
  18550. this.rotationAutoUpdate = false;
  18551. };
  18552. /**
  18553. * @author hughes
  18554. */
  18555. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18556. THREE.Geometry.call( this );
  18557. this.radius = radius = radius || 50;
  18558. this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18559. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18560. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18561. var i, uvs = [],
  18562. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18563. this.vertices.push(center);
  18564. uvs.push( centerUV );
  18565. for ( i = 0; i <= segments; i ++ ) {
  18566. var vertex = new THREE.Vector3();
  18567. var segment = thetaStart + i / segments * thetaLength;
  18568. vertex.x = radius * Math.cos( segment );
  18569. vertex.y = radius * Math.sin( segment );
  18570. this.vertices.push( vertex );
  18571. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18572. }
  18573. var n = new THREE.Vector3( 0, 0, 1 );
  18574. for ( i = 1; i <= segments; i ++ ) {
  18575. var v1 = i;
  18576. var v2 = i + 1 ;
  18577. var v3 = 0;
  18578. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  18579. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18580. }
  18581. this.computeCentroids();
  18582. this.computeFaceNormals();
  18583. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18584. };
  18585. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18586. /**
  18587. * @author mrdoob / http://mrdoob.com/
  18588. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18589. */
  18590. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18591. THREE.Geometry.call( this );
  18592. var scope = this;
  18593. this.width = width;
  18594. this.height = height;
  18595. this.depth = depth;
  18596. this.widthSegments = widthSegments || 1;
  18597. this.heightSegments = heightSegments || 1;
  18598. this.depthSegments = depthSegments || 1;
  18599. var width_half = this.width / 2;
  18600. var height_half = this.height / 2;
  18601. var depth_half = this.depth / 2;
  18602. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18603. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18604. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18605. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18606. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18607. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18608. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18609. var w, ix, iy,
  18610. gridX = scope.widthSegments,
  18611. gridY = scope.heightSegments,
  18612. width_half = width / 2,
  18613. height_half = height / 2,
  18614. offset = scope.vertices.length;
  18615. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18616. w = 'z';
  18617. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18618. w = 'y';
  18619. gridY = scope.depthSegments;
  18620. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18621. w = 'x';
  18622. gridX = scope.depthSegments;
  18623. }
  18624. var gridX1 = gridX + 1,
  18625. gridY1 = gridY + 1,
  18626. segment_width = width / gridX,
  18627. segment_height = height / gridY,
  18628. normal = new THREE.Vector3();
  18629. normal[ w ] = depth > 0 ? 1 : - 1;
  18630. for ( iy = 0; iy < gridY1; iy ++ ) {
  18631. for ( ix = 0; ix < gridX1; ix ++ ) {
  18632. var vector = new THREE.Vector3();
  18633. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18634. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18635. vector[ w ] = depth;
  18636. scope.vertices.push( vector );
  18637. }
  18638. }
  18639. for ( iy = 0; iy < gridY; iy++ ) {
  18640. for ( ix = 0; ix < gridX; ix++ ) {
  18641. var a = ix + gridX1 * iy;
  18642. var b = ix + gridX1 * ( iy + 1 );
  18643. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18644. var d = ( ix + 1 ) + gridX1 * iy;
  18645. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18646. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18647. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18648. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18649. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18650. face.normal.copy( normal );
  18651. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18652. face.materialIndex = materialIndex;
  18653. scope.faces.push( face );
  18654. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18655. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18656. face.normal.copy( normal );
  18657. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18658. face.materialIndex = materialIndex;
  18659. scope.faces.push( face );
  18660. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18661. }
  18662. }
  18663. }
  18664. this.computeCentroids();
  18665. this.mergeVertices();
  18666. };
  18667. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18668. /**
  18669. * @author mrdoob / http://mrdoob.com/
  18670. */
  18671. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18672. THREE.Geometry.call( this );
  18673. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18674. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18675. this.height = height = height !== undefined ? height : 100;
  18676. this.radialSegments = radialSegments = radialSegments || 8;
  18677. this.heightSegments = heightSegments = heightSegments || 1;
  18678. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18679. var heightHalf = height / 2;
  18680. var x, y, vertices = [], uvs = [];
  18681. for ( y = 0; y <= heightSegments; y ++ ) {
  18682. var verticesRow = [];
  18683. var uvsRow = [];
  18684. var v = y / heightSegments;
  18685. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18686. for ( x = 0; x <= radialSegments; x ++ ) {
  18687. var u = x / radialSegments;
  18688. var vertex = new THREE.Vector3();
  18689. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18690. vertex.y = - v * height + heightHalf;
  18691. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18692. this.vertices.push( vertex );
  18693. verticesRow.push( this.vertices.length - 1 );
  18694. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18695. }
  18696. vertices.push( verticesRow );
  18697. uvs.push( uvsRow );
  18698. }
  18699. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18700. var na, nb;
  18701. for ( x = 0; x < radialSegments; x ++ ) {
  18702. if ( radiusTop !== 0 ) {
  18703. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18704. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18705. } else {
  18706. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18707. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18708. }
  18709. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18710. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18711. for ( y = 0; y < heightSegments; y ++ ) {
  18712. var v1 = vertices[ y ][ x ];
  18713. var v2 = vertices[ y + 1 ][ x ];
  18714. var v3 = vertices[ y + 1 ][ x + 1 ];
  18715. var v4 = vertices[ y ][ x + 1 ];
  18716. var n1 = na.clone();
  18717. var n2 = na.clone();
  18718. var n3 = nb.clone();
  18719. var n4 = nb.clone();
  18720. var uv1 = uvs[ y ][ x ].clone();
  18721. var uv2 = uvs[ y + 1 ][ x ].clone();
  18722. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18723. var uv4 = uvs[ y ][ x + 1 ].clone();
  18724. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18725. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18726. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18727. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18728. }
  18729. }
  18730. // top cap
  18731. if ( openEnded === false && radiusTop > 0 ) {
  18732. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18733. for ( x = 0; x < radialSegments; x ++ ) {
  18734. var v1 = vertices[ 0 ][ x ];
  18735. var v2 = vertices[ 0 ][ x + 1 ];
  18736. var v3 = this.vertices.length - 1;
  18737. var n1 = new THREE.Vector3( 0, 1, 0 );
  18738. var n2 = new THREE.Vector3( 0, 1, 0 );
  18739. var n3 = new THREE.Vector3( 0, 1, 0 );
  18740. var uv1 = uvs[ 0 ][ x ].clone();
  18741. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18742. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18743. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18744. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18745. }
  18746. }
  18747. // bottom cap
  18748. if ( openEnded === false && radiusBottom > 0 ) {
  18749. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18750. for ( x = 0; x < radialSegments; x ++ ) {
  18751. var v1 = vertices[ y ][ x + 1 ];
  18752. var v2 = vertices[ y ][ x ];
  18753. var v3 = this.vertices.length - 1;
  18754. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18755. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18756. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18757. var uv1 = uvs[ y ][ x + 1 ].clone();
  18758. var uv2 = uvs[ y ][ x ].clone();
  18759. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18760. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18761. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18762. }
  18763. }
  18764. this.computeCentroids();
  18765. this.computeFaceNormals();
  18766. }
  18767. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18768. /**
  18769. * @author zz85 / http://www.lab4games.net/zz85/blog
  18770. *
  18771. * Creates extruded geometry from a path shape.
  18772. *
  18773. * parameters = {
  18774. *
  18775. * curveSegments: <int>, // number of points on the curves
  18776. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18777. * amount: <int>, // Depth to extrude the shape
  18778. *
  18779. * bevelEnabled: <bool>, // turn on bevel
  18780. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18781. * bevelSize: <float>, // how far from shape outline is bevel
  18782. * bevelSegments: <int>, // number of bevel layers
  18783. *
  18784. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18785. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18786. *
  18787. * material: <int> // material index for front and back faces
  18788. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18789. * uvGenerator: <Object> // object that provides UV generator functions
  18790. *
  18791. * }
  18792. **/
  18793. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18794. if ( typeof( shapes ) === "undefined" ) {
  18795. shapes = [];
  18796. return;
  18797. }
  18798. THREE.Geometry.call( this );
  18799. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18800. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18801. this.addShapeList( shapes, options );
  18802. this.computeCentroids();
  18803. this.computeFaceNormals();
  18804. // can't really use automatic vertex normals
  18805. // as then front and back sides get smoothed too
  18806. // should do separate smoothing just for sides
  18807. //this.computeVertexNormals();
  18808. //console.log( "took", ( Date.now() - startTime ) );
  18809. };
  18810. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18811. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18812. var sl = shapes.length;
  18813. for ( var s = 0; s < sl; s ++ ) {
  18814. var shape = shapes[ s ];
  18815. this.addShape( shape, options );
  18816. }
  18817. };
  18818. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18819. var amount = options.amount !== undefined ? options.amount : 100;
  18820. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18821. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18822. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18823. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18824. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18825. var steps = options.steps !== undefined ? options.steps : 1;
  18826. var extrudePath = options.extrudePath;
  18827. var extrudePts, extrudeByPath = false;
  18828. var material = options.material;
  18829. var extrudeMaterial = options.extrudeMaterial;
  18830. // Use default WorldUVGenerator if no UV generators are specified.
  18831. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18832. var shapebb = this.shapebb;
  18833. //shapebb = shape.getBoundingBox();
  18834. var splineTube, binormal, normal, position2;
  18835. if ( extrudePath ) {
  18836. extrudePts = extrudePath.getSpacedPoints( steps );
  18837. extrudeByPath = true;
  18838. bevelEnabled = false; // bevels not supported for path extrusion
  18839. // SETUP TNB variables
  18840. // Reuse TNB from TubeGeomtry for now.
  18841. // TODO1 - have a .isClosed in spline?
  18842. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18843. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18844. binormal = new THREE.Vector3();
  18845. normal = new THREE.Vector3();
  18846. position2 = new THREE.Vector3();
  18847. }
  18848. // Safeguards if bevels are not enabled
  18849. if ( ! bevelEnabled ) {
  18850. bevelSegments = 0;
  18851. bevelThickness = 0;
  18852. bevelSize = 0;
  18853. }
  18854. // Variables initalization
  18855. var ahole, h, hl; // looping of holes
  18856. var scope = this;
  18857. var bevelPoints = [];
  18858. var shapesOffset = this.vertices.length;
  18859. var shapePoints = shape.extractPoints( curveSegments );
  18860. var vertices = shapePoints.shape;
  18861. var holes = shapePoints.holes;
  18862. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18863. if ( reverse ) {
  18864. vertices = vertices.reverse();
  18865. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18866. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18867. ahole = holes[ h ];
  18868. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18869. holes[ h ] = ahole.reverse();
  18870. }
  18871. }
  18872. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18873. }
  18874. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18875. /* Vertices */
  18876. var contour = vertices; // vertices has all points but contour has only points of circumference
  18877. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18878. ahole = holes[ h ];
  18879. vertices = vertices.concat( ahole );
  18880. }
  18881. function scalePt2 ( pt, vec, size ) {
  18882. if ( !vec ) console.log( "die" );
  18883. return vec.clone().multiplyScalar( size ).add( pt );
  18884. }
  18885. var b, bs, t, z,
  18886. vert, vlen = vertices.length,
  18887. face, flen = faces.length,
  18888. cont, clen = contour.length;
  18889. // Find directions for point movement
  18890. var RAD_TO_DEGREES = 180 / Math.PI;
  18891. function getBevelVec( pt_i, pt_j, pt_k ) {
  18892. // Algorithm 2
  18893. return getBevelVec2( pt_i, pt_j, pt_k );
  18894. }
  18895. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18896. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18897. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18898. if ( anglea > angleb ) {
  18899. angleb += Math.PI * 2;
  18900. }
  18901. var anglec = ( anglea + angleb ) / 2;
  18902. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18903. var x = - Math.cos( anglec );
  18904. var y = - Math.sin( anglec );
  18905. var vec = new THREE.Vector2( x, y ); //.normalize();
  18906. return vec;
  18907. }
  18908. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18909. var a = THREE.ExtrudeGeometry.__v1,
  18910. b = THREE.ExtrudeGeometry.__v2,
  18911. v_hat = THREE.ExtrudeGeometry.__v3,
  18912. w_hat = THREE.ExtrudeGeometry.__v4,
  18913. p = THREE.ExtrudeGeometry.__v5,
  18914. q = THREE.ExtrudeGeometry.__v6,
  18915. v, w,
  18916. v_dot_w_hat, q_sub_p_dot_w_hat,
  18917. s, intersection;
  18918. // good reading for line-line intersection
  18919. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18920. // define a as vector j->i
  18921. // define b as vectot k->i
  18922. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18923. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18924. // get unit vectors
  18925. v = a.normalize();
  18926. w = b.normalize();
  18927. // normals from pt i
  18928. v_hat.set( -v.y, v.x );
  18929. w_hat.set( w.y, -w.x );
  18930. // pts from i
  18931. p.copy( pt_i ).add( v_hat );
  18932. q.copy( pt_i ).add( w_hat );
  18933. if ( p.equals( q ) ) {
  18934. //console.log("Warning: lines are straight");
  18935. return w_hat.clone();
  18936. }
  18937. // Points from j, k. helps prevents points cross overover most of the time
  18938. p.copy( pt_j ).add( v_hat );
  18939. q.copy( pt_k ).add( w_hat );
  18940. v_dot_w_hat = v.dot( w_hat );
  18941. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18942. // We should not reach these conditions
  18943. if ( v_dot_w_hat === 0 ) {
  18944. console.log( "Either infinite or no solutions!" );
  18945. if ( q_sub_p_dot_w_hat === 0 ) {
  18946. console.log( "Its finite solutions." );
  18947. } else {
  18948. console.log( "Too bad, no solutions." );
  18949. }
  18950. }
  18951. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18952. if ( s < 0 ) {
  18953. // in case of emergecy, revert to algorithm 1.
  18954. return getBevelVec1( pt_i, pt_j, pt_k );
  18955. }
  18956. intersection = v.multiplyScalar( s ).add( p );
  18957. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18958. }
  18959. var contourMovements = [];
  18960. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18961. if ( j === il ) j = 0;
  18962. if ( k === il ) k = 0;
  18963. // (j)---(i)---(k)
  18964. // console.log('i,j,k', i, j , k)
  18965. var pt_i = contour[ i ];
  18966. var pt_j = contour[ j ];
  18967. var pt_k = contour[ k ];
  18968. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18969. }
  18970. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18971. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18972. ahole = holes[ h ];
  18973. oneHoleMovements = [];
  18974. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18975. if ( j === il ) j = 0;
  18976. if ( k === il ) k = 0;
  18977. // (j)---(i)---(k)
  18978. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18979. }
  18980. holesMovements.push( oneHoleMovements );
  18981. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18982. }
  18983. // Loop bevelSegments, 1 for the front, 1 for the back
  18984. for ( b = 0; b < bevelSegments; b ++ ) {
  18985. //for ( b = bevelSegments; b > 0; b -- ) {
  18986. t = b / bevelSegments;
  18987. z = bevelThickness * ( 1 - t );
  18988. //z = bevelThickness * t;
  18989. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18990. //bs = bevelSize * t ; // linear
  18991. // contract shape
  18992. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18993. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18994. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18995. v( vert.x, vert.y, - z );
  18996. }
  18997. // expand holes
  18998. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18999. ahole = holes[ h ];
  19000. oneHoleMovements = holesMovements[ h ];
  19001. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19002. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19003. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19004. v( vert.x, vert.y, -z );
  19005. }
  19006. }
  19007. }
  19008. bs = bevelSize;
  19009. // Back facing vertices
  19010. for ( i = 0; i < vlen; i ++ ) {
  19011. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19012. if ( !extrudeByPath ) {
  19013. v( vert.x, vert.y, 0 );
  19014. } else {
  19015. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19016. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19017. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19018. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19019. v( position2.x, position2.y, position2.z );
  19020. }
  19021. }
  19022. // Add stepped vertices...
  19023. // Including front facing vertices
  19024. var s;
  19025. for ( s = 1; s <= steps; s ++ ) {
  19026. for ( i = 0; i < vlen; i ++ ) {
  19027. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19028. if ( !extrudeByPath ) {
  19029. v( vert.x, vert.y, amount / steps * s );
  19030. } else {
  19031. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19032. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19033. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19034. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19035. v( position2.x, position2.y, position2.z );
  19036. }
  19037. }
  19038. }
  19039. // Add bevel segments planes
  19040. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19041. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19042. t = b / bevelSegments;
  19043. z = bevelThickness * ( 1 - t );
  19044. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19045. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19046. // contract shape
  19047. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19048. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19049. v( vert.x, vert.y, amount + z );
  19050. }
  19051. // expand holes
  19052. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19053. ahole = holes[ h ];
  19054. oneHoleMovements = holesMovements[ h ];
  19055. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19056. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19057. if ( !extrudeByPath ) {
  19058. v( vert.x, vert.y, amount + z );
  19059. } else {
  19060. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19061. }
  19062. }
  19063. }
  19064. }
  19065. /* Faces */
  19066. // Top and bottom faces
  19067. buildLidFaces();
  19068. // Sides faces
  19069. buildSideFaces();
  19070. ///// Internal functions
  19071. function buildLidFaces() {
  19072. if ( bevelEnabled ) {
  19073. var layer = 0 ; // steps + 1
  19074. var offset = vlen * layer;
  19075. // Bottom faces
  19076. for ( i = 0; i < flen; i ++ ) {
  19077. face = faces[ i ];
  19078. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19079. }
  19080. layer = steps + bevelSegments * 2;
  19081. offset = vlen * layer;
  19082. // Top faces
  19083. for ( i = 0; i < flen; i ++ ) {
  19084. face = faces[ i ];
  19085. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19086. }
  19087. } else {
  19088. // Bottom faces
  19089. for ( i = 0; i < flen; i++ ) {
  19090. face = faces[ i ];
  19091. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19092. }
  19093. // Top faces
  19094. for ( i = 0; i < flen; i ++ ) {
  19095. face = faces[ i ];
  19096. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19097. }
  19098. }
  19099. }
  19100. // Create faces for the z-sides of the shape
  19101. function buildSideFaces() {
  19102. var layeroffset = 0;
  19103. sidewalls( contour, layeroffset );
  19104. layeroffset += contour.length;
  19105. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19106. ahole = holes[ h ];
  19107. sidewalls( ahole, layeroffset );
  19108. //, true
  19109. layeroffset += ahole.length;
  19110. }
  19111. }
  19112. function sidewalls( contour, layeroffset ) {
  19113. var j, k;
  19114. i = contour.length;
  19115. while ( --i >= 0 ) {
  19116. j = i;
  19117. k = i - 1;
  19118. if ( k < 0 ) k = contour.length - 1;
  19119. //console.log('b', i,j, i-1, k,vertices.length);
  19120. var s = 0, sl = steps + bevelSegments * 2;
  19121. for ( s = 0; s < sl; s ++ ) {
  19122. var slen1 = vlen * s;
  19123. var slen2 = vlen * ( s + 1 );
  19124. var a = layeroffset + j + slen1,
  19125. b = layeroffset + k + slen1,
  19126. c = layeroffset + k + slen2,
  19127. d = layeroffset + j + slen2;
  19128. f4( a, b, c, d, contour, s, sl, j, k );
  19129. }
  19130. }
  19131. }
  19132. function v( x, y, z ) {
  19133. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19134. }
  19135. function f3( a, b, c, isBottom ) {
  19136. a += shapesOffset;
  19137. b += shapesOffset;
  19138. c += shapesOffset;
  19139. // normal, color, material
  19140. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19141. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19142. scope.faceVertexUvs[ 0 ].push( uvs );
  19143. }
  19144. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19145. a += shapesOffset;
  19146. b += shapesOffset;
  19147. c += shapesOffset;
  19148. d += shapesOffset;
  19149. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19150. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19151. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19152. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19153. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19154. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19155. }
  19156. };
  19157. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19158. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19159. var ax = geometry.vertices[ indexA ].x,
  19160. ay = geometry.vertices[ indexA ].y,
  19161. bx = geometry.vertices[ indexB ].x,
  19162. by = geometry.vertices[ indexB ].y,
  19163. cx = geometry.vertices[ indexC ].x,
  19164. cy = geometry.vertices[ indexC ].y;
  19165. return [
  19166. new THREE.Vector2( ax, ay ),
  19167. new THREE.Vector2( bx, by ),
  19168. new THREE.Vector2( cx, cy )
  19169. ];
  19170. },
  19171. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19172. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19173. },
  19174. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19175. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19176. contourIndex1, contourIndex2 ) {
  19177. var ax = geometry.vertices[ indexA ].x,
  19178. ay = geometry.vertices[ indexA ].y,
  19179. az = geometry.vertices[ indexA ].z,
  19180. bx = geometry.vertices[ indexB ].x,
  19181. by = geometry.vertices[ indexB ].y,
  19182. bz = geometry.vertices[ indexB ].z,
  19183. cx = geometry.vertices[ indexC ].x,
  19184. cy = geometry.vertices[ indexC ].y,
  19185. cz = geometry.vertices[ indexC ].z,
  19186. dx = geometry.vertices[ indexD ].x,
  19187. dy = geometry.vertices[ indexD ].y,
  19188. dz = geometry.vertices[ indexD ].z;
  19189. if ( Math.abs( ay - by ) < 0.01 ) {
  19190. return [
  19191. new THREE.Vector2( ax, 1 - az ),
  19192. new THREE.Vector2( bx, 1 - bz ),
  19193. new THREE.Vector2( cx, 1 - cz ),
  19194. new THREE.Vector2( dx, 1 - dz )
  19195. ];
  19196. } else {
  19197. return [
  19198. new THREE.Vector2( ay, 1 - az ),
  19199. new THREE.Vector2( by, 1 - bz ),
  19200. new THREE.Vector2( cy, 1 - cz ),
  19201. new THREE.Vector2( dy, 1 - dz )
  19202. ];
  19203. }
  19204. }
  19205. };
  19206. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19207. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19208. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19209. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19210. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19211. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19212. /**
  19213. * @author jonobr1 / http://jonobr1.com
  19214. *
  19215. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19216. * ExtrudeGeometry.
  19217. *
  19218. * parameters = {
  19219. *
  19220. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19221. *
  19222. * material: <int> // material index for front and back faces
  19223. * uvGenerator: <Object> // object that provides UV generator functions
  19224. *
  19225. * }
  19226. **/
  19227. THREE.ShapeGeometry = function ( shapes, options ) {
  19228. THREE.Geometry.call( this );
  19229. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19230. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19231. this.addShapeList( shapes, options );
  19232. this.computeCentroids();
  19233. this.computeFaceNormals();
  19234. };
  19235. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19236. /**
  19237. * Add an array of shapes to THREE.ShapeGeometry.
  19238. */
  19239. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19240. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19241. this.addShape( shapes[ i ], options );
  19242. }
  19243. return this;
  19244. };
  19245. /**
  19246. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19247. */
  19248. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19249. if ( options === undefined ) options = {};
  19250. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19251. var material = options.material;
  19252. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19253. var shapebb = this.shapebb;
  19254. //
  19255. var i, l, hole, s;
  19256. var shapesOffset = this.vertices.length;
  19257. var shapePoints = shape.extractPoints( curveSegments );
  19258. var vertices = shapePoints.shape;
  19259. var holes = shapePoints.holes;
  19260. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19261. if ( reverse ) {
  19262. vertices = vertices.reverse();
  19263. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19264. for ( i = 0, l = holes.length; i < l; i++ ) {
  19265. hole = holes[ i ];
  19266. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19267. holes[ i ] = hole.reverse();
  19268. }
  19269. }
  19270. reverse = false;
  19271. }
  19272. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19273. // Vertices
  19274. var contour = vertices;
  19275. for ( i = 0, l = holes.length; i < l; i++ ) {
  19276. hole = holes[ i ];
  19277. vertices = vertices.concat( hole );
  19278. }
  19279. //
  19280. var vert, vlen = vertices.length;
  19281. var face, flen = faces.length;
  19282. var cont, clen = contour.length;
  19283. for ( i = 0; i < vlen; i++ ) {
  19284. vert = vertices[ i ];
  19285. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19286. }
  19287. for ( i = 0; i < flen; i++ ) {
  19288. face = faces[ i ];
  19289. var a = face[ 0 ] + shapesOffset;
  19290. var b = face[ 1 ] + shapesOffset;
  19291. var c = face[ 2 ] + shapesOffset;
  19292. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19293. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19294. }
  19295. };
  19296. /**
  19297. * @author astrodud / http://astrodud.isgreat.org/
  19298. * @author zz85 / https://github.com/zz85
  19299. * @author bhouston / http://exocortex.com
  19300. */
  19301. // points - to create a closed torus, one must use a set of points
  19302. // like so: [ a, b, c, d, a ], see first is the same as last.
  19303. // segments - the number of circumference segments to create
  19304. // phiStart - the starting radian
  19305. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19306. // 2*pi is a closed lathe, less than 2PI is a portion.
  19307. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19308. THREE.Geometry.call( this );
  19309. segments = segments || 12;
  19310. phiStart = phiStart || 0;
  19311. phiLength = phiLength || 2 * Math.PI;
  19312. var inversePointLength = 1.0 / ( points.length - 1 );
  19313. var inverseSegments = 1.0 / segments;
  19314. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19315. var phi = phiStart + i * inverseSegments * phiLength;
  19316. var c = Math.cos( phi ),
  19317. s = Math.sin( phi );
  19318. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19319. var pt = points[ j ];
  19320. var vertex = new THREE.Vector3();
  19321. vertex.x = c * pt.x - s * pt.y;
  19322. vertex.y = s * pt.x + c * pt.y;
  19323. vertex.z = pt.z;
  19324. this.vertices.push( vertex );
  19325. }
  19326. }
  19327. var np = points.length;
  19328. for ( var i = 0, il = segments; i < il; i ++ ) {
  19329. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19330. var base = j + np * i;
  19331. var a = base;
  19332. var b = base + np;
  19333. var c = base + 1 + np;
  19334. var d = base + 1;
  19335. var u0 = i * inverseSegments;
  19336. var v0 = j * inversePointLength;
  19337. var u1 = u0 + inverseSegments;
  19338. var v1 = v0 + inversePointLength;
  19339. this.faces.push( new THREE.Face3( a, b, d ) );
  19340. this.faceVertexUvs[ 0 ].push( [
  19341. new THREE.Vector2( u0, v0 ),
  19342. new THREE.Vector2( u1, v0 ),
  19343. new THREE.Vector2( u0, v1 )
  19344. ] );
  19345. this.faces.push( new THREE.Face3( b, c, d ) );
  19346. this.faceVertexUvs[ 0 ].push( [
  19347. new THREE.Vector2( u1, v0 ),
  19348. new THREE.Vector2( u1, v1 ),
  19349. new THREE.Vector2( u0, v1 )
  19350. ] );
  19351. }
  19352. }
  19353. this.mergeVertices();
  19354. this.computeCentroids();
  19355. this.computeFaceNormals();
  19356. this.computeVertexNormals();
  19357. };
  19358. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19359. /**
  19360. * @author mrdoob / http://mrdoob.com/
  19361. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19362. */
  19363. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19364. THREE.Geometry.call( this );
  19365. this.width = width;
  19366. this.height = height;
  19367. this.widthSegments = widthSegments || 1;
  19368. this.heightSegments = heightSegments || 1;
  19369. var ix, iz;
  19370. var width_half = width / 2;
  19371. var height_half = height / 2;
  19372. var gridX = this.widthSegments;
  19373. var gridZ = this.heightSegments;
  19374. var gridX1 = gridX + 1;
  19375. var gridZ1 = gridZ + 1;
  19376. var segment_width = this.width / gridX;
  19377. var segment_height = this.height / gridZ;
  19378. var normal = new THREE.Vector3( 0, 0, 1 );
  19379. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19380. for ( ix = 0; ix < gridX1; ix ++ ) {
  19381. var x = ix * segment_width - width_half;
  19382. var y = iz * segment_height - height_half;
  19383. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19384. }
  19385. }
  19386. for ( iz = 0; iz < gridZ; iz ++ ) {
  19387. for ( ix = 0; ix < gridX; ix ++ ) {
  19388. var a = ix + gridX1 * iz;
  19389. var b = ix + gridX1 * ( iz + 1 );
  19390. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19391. var d = ( ix + 1 ) + gridX1 * iz;
  19392. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19393. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19394. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19395. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19396. var face = new THREE.Face3( a, b, d );
  19397. face.normal.copy( normal );
  19398. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19399. this.faces.push( face );
  19400. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19401. face = new THREE.Face3( b, c, d );
  19402. face.normal.copy( normal );
  19403. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19404. this.faces.push( face );
  19405. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19406. }
  19407. }
  19408. this.computeCentroids();
  19409. };
  19410. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19411. /**
  19412. * @author Kaleb Murphy
  19413. */
  19414. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19415. THREE.Geometry.call( this );
  19416. innerRadius = innerRadius || 0;
  19417. outerRadius = outerRadius || 50;
  19418. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19419. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19420. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19421. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19422. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19423. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19424. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19425. var vertex = new THREE.Vector3();
  19426. var segment = thetaStart + o / thetaSegments * thetaLength;
  19427. vertex.x = radius * Math.cos( segment );
  19428. vertex.y = radius * Math.sin( segment );
  19429. this.vertices.push( vertex );
  19430. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19431. }
  19432. radius += radiusStep;
  19433. }
  19434. var n = new THREE.Vector3( 0, 0, 1 );
  19435. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19436. var thetaSegment = i * thetaSegments;
  19437. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19438. var segment = o + thetaSegment;
  19439. var v1 = segment + i;
  19440. var v2 = segment + thetaSegments + i;
  19441. var v3 = segment + thetaSegments + 1 + i;
  19442. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19443. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19444. v1 = segment + i;
  19445. v2 = segment + thetaSegments + 1 + i;
  19446. v3 = segment + 1 + i;
  19447. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19448. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19449. }
  19450. }
  19451. this.computeCentroids();
  19452. this.computeFaceNormals();
  19453. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19454. };
  19455. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19456. /**
  19457. * @author mrdoob / http://mrdoob.com/
  19458. */
  19459. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19460. THREE.Geometry.call( this );
  19461. this.radius = radius = radius || 50;
  19462. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19463. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19464. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19465. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19466. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19467. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19468. var x, y, vertices = [], uvs = [];
  19469. for ( y = 0; y <= heightSegments; y ++ ) {
  19470. var verticesRow = [];
  19471. var uvsRow = [];
  19472. for ( x = 0; x <= widthSegments; x ++ ) {
  19473. var u = x / widthSegments;
  19474. var v = y / heightSegments;
  19475. var vertex = new THREE.Vector3();
  19476. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19477. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19478. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19479. this.vertices.push( vertex );
  19480. verticesRow.push( this.vertices.length - 1 );
  19481. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19482. }
  19483. vertices.push( verticesRow );
  19484. uvs.push( uvsRow );
  19485. }
  19486. for ( y = 0; y < this.heightSegments; y ++ ) {
  19487. for ( x = 0; x < this.widthSegments; x ++ ) {
  19488. var v1 = vertices[ y ][ x + 1 ];
  19489. var v2 = vertices[ y ][ x ];
  19490. var v3 = vertices[ y + 1 ][ x ];
  19491. var v4 = vertices[ y + 1 ][ x + 1 ];
  19492. var n1 = this.vertices[ v1 ].clone().normalize();
  19493. var n2 = this.vertices[ v2 ].clone().normalize();
  19494. var n3 = this.vertices[ v3 ].clone().normalize();
  19495. var n4 = this.vertices[ v4 ].clone().normalize();
  19496. var uv1 = uvs[ y ][ x + 1 ].clone();
  19497. var uv2 = uvs[ y ][ x ].clone();
  19498. var uv3 = uvs[ y + 1 ][ x ].clone();
  19499. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19500. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19501. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19502. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19503. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19504. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19505. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19506. } else {
  19507. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19508. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19509. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19510. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19511. }
  19512. }
  19513. }
  19514. this.computeCentroids();
  19515. this.computeFaceNormals();
  19516. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19517. };
  19518. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19519. /**
  19520. * @author zz85 / http://www.lab4games.net/zz85/blog
  19521. * @author alteredq / http://alteredqualia.com/
  19522. *
  19523. * For creating 3D text geometry in three.js
  19524. *
  19525. * Text = 3D Text
  19526. *
  19527. * parameters = {
  19528. * size: <float>, // size of the text
  19529. * height: <float>, // thickness to extrude text
  19530. * curveSegments: <int>, // number of points on the curves
  19531. *
  19532. * font: <string>, // font name
  19533. * weight: <string>, // font weight (normal, bold)
  19534. * style: <string>, // font style (normal, italics)
  19535. *
  19536. * bevelEnabled: <bool>, // turn on bevel
  19537. * bevelThickness: <float>, // how deep into text bevel goes
  19538. * bevelSize: <float>, // how far from text outline is bevel
  19539. * }
  19540. *
  19541. */
  19542. /* Usage Examples
  19543. // TextGeometry wrapper
  19544. var text3d = new TextGeometry( text, options );
  19545. // Complete manner
  19546. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19547. var text3d = new ExtrudeGeometry( textShapes, options );
  19548. */
  19549. THREE.TextGeometry = function ( text, parameters ) {
  19550. parameters = parameters || {};
  19551. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19552. // translate parameters to ExtrudeGeometry API
  19553. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19554. // defaults
  19555. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19556. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19557. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19558. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19559. };
  19560. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19561. /**
  19562. * @author oosmoxiecode
  19563. * @author mrdoob / http://mrdoob.com/
  19564. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19565. */
  19566. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19567. THREE.Geometry.call( this );
  19568. var scope = this;
  19569. this.radius = radius || 100;
  19570. this.tube = tube || 40;
  19571. this.radialSegments = radialSegments || 8;
  19572. this.tubularSegments = tubularSegments || 6;
  19573. this.arc = arc || Math.PI * 2;
  19574. var center = new THREE.Vector3(), uvs = [], normals = [];
  19575. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19576. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19577. var u = i / this.tubularSegments * this.arc;
  19578. var v = j / this.radialSegments * Math.PI * 2;
  19579. center.x = this.radius * Math.cos( u );
  19580. center.y = this.radius * Math.sin( u );
  19581. var vertex = new THREE.Vector3();
  19582. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19583. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19584. vertex.z = this.tube * Math.sin( v );
  19585. this.vertices.push( vertex );
  19586. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19587. normals.push( vertex.clone().sub( center ).normalize() );
  19588. }
  19589. }
  19590. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19591. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19592. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19593. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19594. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19595. var d = ( this.tubularSegments + 1 ) * j + i;
  19596. var face = new THREE.Face3( a, b, d, [ normals[ a ], normals[ b ], normals[ d ] ] );
  19597. face.normal.add( normals[ a ] );
  19598. face.normal.add( normals[ b ] );
  19599. face.normal.add( normals[ d ] );
  19600. face.normal.normalize();
  19601. this.faces.push( face );
  19602. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19603. face = new THREE.Face3( b, c, d, [ normals[ b ], normals[ c ], normals[ d ] ] );
  19604. face.normal.add( normals[ b ] );
  19605. face.normal.add( normals[ c ] );
  19606. face.normal.add( normals[ d ] );
  19607. face.normal.normalize();
  19608. this.faces.push( face );
  19609. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19610. }
  19611. }
  19612. this.computeCentroids();
  19613. };
  19614. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19615. /**
  19616. * @author oosmoxiecode
  19617. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19618. */
  19619. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19620. THREE.Geometry.call( this );
  19621. var scope = this;
  19622. this.radius = radius || 100;
  19623. this.tube = tube || 40;
  19624. this.radialSegments = radialSegments || 64;
  19625. this.tubularSegments = tubularSegments || 8;
  19626. this.p = p || 2;
  19627. this.q = q || 3;
  19628. this.heightScale = heightScale || 1;
  19629. this.grid = new Array( this.radialSegments );
  19630. var tang = new THREE.Vector3();
  19631. var n = new THREE.Vector3();
  19632. var bitan = new THREE.Vector3();
  19633. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19634. this.grid[ i ] = new Array( this.tubularSegments );
  19635. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19636. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  19637. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  19638. tang.subVectors( p2, p1 );
  19639. n.addVectors( p2, p1 );
  19640. bitan.crossVectors( tang, n );
  19641. n.crossVectors( bitan, tang );
  19642. bitan.normalize();
  19643. n.normalize();
  19644. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19645. var v = j / this.tubularSegments * 2 * Math.PI;
  19646. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19647. var cy = this.tube * Math.sin( v );
  19648. var pos = new THREE.Vector3();
  19649. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19650. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19651. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19652. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  19653. }
  19654. }
  19655. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19656. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19657. var ip = ( i + 1 ) % this.radialSegments;
  19658. var jp = ( j + 1 ) % this.tubularSegments;
  19659. var a = this.grid[ i ][ j ];
  19660. var b = this.grid[ ip ][ j ];
  19661. var c = this.grid[ ip ][ jp ];
  19662. var d = this.grid[ i ][ jp ];
  19663. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19664. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19665. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19666. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19667. this.faces.push( new THREE.Face3( a, b, d ) );
  19668. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19669. this.faces.push( new THREE.Face3( b, c, d ) );
  19670. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19671. }
  19672. }
  19673. this.computeCentroids();
  19674. this.computeFaceNormals();
  19675. this.computeVertexNormals();
  19676. function getPos( u, in_q, in_p, radius, heightScale ) {
  19677. var cu = Math.cos( u );
  19678. var su = Math.sin( u );
  19679. var quOverP = in_q / in_p * u;
  19680. var cs = Math.cos( quOverP );
  19681. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19682. var ty = radius * ( 2 + cs ) * su * 0.5;
  19683. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19684. return new THREE.Vector3( tx, ty, tz );
  19685. }
  19686. };
  19687. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19688. /**
  19689. * @author WestLangley / https://github.com/WestLangley
  19690. * @author zz85 / https://github.com/zz85
  19691. * @author miningold / https://github.com/miningold
  19692. *
  19693. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19694. *
  19695. * Creates a tube which extrudes along a 3d spline
  19696. *
  19697. * Uses parallel transport frames as described in
  19698. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19699. */
  19700. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  19701. THREE.Geometry.call( this );
  19702. this.path = path;
  19703. this.segments = segments || 64;
  19704. this.radius = radius || 1;
  19705. this.radialSegments = radialSegments || 8;
  19706. this.closed = closed || false;
  19707. this.grid = [];
  19708. var scope = this,
  19709. tangent,
  19710. normal,
  19711. binormal,
  19712. numpoints = this.segments + 1,
  19713. x, y, z,
  19714. tx, ty, tz,
  19715. u, v,
  19716. cx, cy,
  19717. pos, pos2 = new THREE.Vector3(),
  19718. i, j,
  19719. ip, jp,
  19720. a, b, c, d,
  19721. uva, uvb, uvc, uvd;
  19722. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19723. tangents = frames.tangents,
  19724. normals = frames.normals,
  19725. binormals = frames.binormals;
  19726. // proxy internals
  19727. this.tangents = tangents;
  19728. this.normals = normals;
  19729. this.binormals = binormals;
  19730. function vert( x, y, z ) {
  19731. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19732. }
  19733. // consruct the grid
  19734. for ( i = 0; i < numpoints; i++ ) {
  19735. this.grid[ i ] = [];
  19736. u = i / ( numpoints - 1 );
  19737. pos = path.getPointAt( u );
  19738. tangent = tangents[ i ];
  19739. normal = normals[ i ];
  19740. binormal = binormals[ i ];
  19741. for ( j = 0; j < this.radialSegments; j++ ) {
  19742. v = j / this.radialSegments * 2 * Math.PI;
  19743. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19744. cy = this.radius * Math.sin( v );
  19745. pos2.copy( pos );
  19746. pos2.x += cx * normal.x + cy * binormal.x;
  19747. pos2.y += cx * normal.y + cy * binormal.y;
  19748. pos2.z += cx * normal.z + cy * binormal.z;
  19749. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19750. }
  19751. }
  19752. // construct the mesh
  19753. for ( i = 0; i < this.segments; i++ ) {
  19754. for ( j = 0; j < this.radialSegments; j++ ) {
  19755. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19756. jp = (j + 1) % this.radialSegments;
  19757. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19758. b = this.grid[ ip ][ j ];
  19759. c = this.grid[ ip ][ jp ];
  19760. d = this.grid[ i ][ jp ];
  19761. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  19762. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  19763. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  19764. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  19765. this.faces.push( new THREE.Face3( a, b, d ) );
  19766. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19767. this.faces.push( new THREE.Face3( b, c, d ) );
  19768. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19769. }
  19770. }
  19771. this.computeCentroids();
  19772. this.computeFaceNormals();
  19773. this.computeVertexNormals();
  19774. };
  19775. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19776. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19777. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19778. var tangent = new THREE.Vector3(),
  19779. normal = new THREE.Vector3(),
  19780. binormal = new THREE.Vector3(),
  19781. tangents = [],
  19782. normals = [],
  19783. binormals = [],
  19784. vec = new THREE.Vector3(),
  19785. mat = new THREE.Matrix4(),
  19786. numpoints = segments + 1,
  19787. theta,
  19788. epsilon = 0.0001,
  19789. smallest,
  19790. tx, ty, tz,
  19791. i, u, v;
  19792. // expose internals
  19793. this.tangents = tangents;
  19794. this.normals = normals;
  19795. this.binormals = binormals;
  19796. // compute the tangent vectors for each segment on the path
  19797. for ( i = 0; i < numpoints; i++ ) {
  19798. u = i / ( numpoints - 1 );
  19799. tangents[ i ] = path.getTangentAt( u );
  19800. tangents[ i ].normalize();
  19801. }
  19802. initialNormal3();
  19803. function initialNormal1(lastBinormal) {
  19804. // fixed start binormal. Has dangers of 0 vectors
  19805. normals[ 0 ] = new THREE.Vector3();
  19806. binormals[ 0 ] = new THREE.Vector3();
  19807. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19808. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19809. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19810. }
  19811. function initialNormal2() {
  19812. // This uses the Frenet-Serret formula for deriving binormal
  19813. var t2 = path.getTangentAt( epsilon );
  19814. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19815. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19816. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19817. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19818. }
  19819. function initialNormal3() {
  19820. // select an initial normal vector perpenicular to the first tangent vector,
  19821. // and in the direction of the smallest tangent xyz component
  19822. normals[ 0 ] = new THREE.Vector3();
  19823. binormals[ 0 ] = new THREE.Vector3();
  19824. smallest = Number.MAX_VALUE;
  19825. tx = Math.abs( tangents[ 0 ].x );
  19826. ty = Math.abs( tangents[ 0 ].y );
  19827. tz = Math.abs( tangents[ 0 ].z );
  19828. if ( tx <= smallest ) {
  19829. smallest = tx;
  19830. normal.set( 1, 0, 0 );
  19831. }
  19832. if ( ty <= smallest ) {
  19833. smallest = ty;
  19834. normal.set( 0, 1, 0 );
  19835. }
  19836. if ( tz <= smallest ) {
  19837. normal.set( 0, 0, 1 );
  19838. }
  19839. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19840. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19841. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19842. }
  19843. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19844. for ( i = 1; i < numpoints; i++ ) {
  19845. normals[ i ] = normals[ i-1 ].clone();
  19846. binormals[ i ] = binormals[ i-1 ].clone();
  19847. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19848. if ( vec.length() > epsilon ) {
  19849. vec.normalize();
  19850. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  19851. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19852. }
  19853. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19854. }
  19855. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19856. if ( closed ) {
  19857. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  19858. theta /= ( numpoints - 1 );
  19859. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19860. theta = -theta;
  19861. }
  19862. for ( i = 1; i < numpoints; i++ ) {
  19863. // twist a little...
  19864. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19865. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19866. }
  19867. }
  19868. };
  19869. /**
  19870. * @author clockworkgeek / https://github.com/clockworkgeek
  19871. * @author timothypratley / https://github.com/timothypratley
  19872. * @author WestLangley / http://github.com/WestLangley
  19873. */
  19874. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19875. THREE.Geometry.call( this );
  19876. radius = radius || 1;
  19877. detail = detail || 0;
  19878. var that = this;
  19879. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19880. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19881. }
  19882. var midpoints = [], p = this.vertices;
  19883. var f = [];
  19884. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19885. var v1 = p[ faces[ i ][ 0 ] ];
  19886. var v2 = p[ faces[ i ][ 1 ] ];
  19887. var v3 = p[ faces[ i ][ 2 ] ];
  19888. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19889. }
  19890. for ( var i = 0, l = f.length; i < l; i ++ ) {
  19891. subdivide(f[ i ], detail);
  19892. }
  19893. // Handle case when face straddles the seam
  19894. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19895. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19896. var x0 = uvs[ 0 ].x;
  19897. var x1 = uvs[ 1 ].x;
  19898. var x2 = uvs[ 2 ].x;
  19899. var max = Math.max( x0, Math.max( x1, x2 ) );
  19900. var min = Math.min( x0, Math.min( x1, x2 ) );
  19901. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19902. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19903. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19904. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19905. }
  19906. }
  19907. // Apply radius
  19908. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19909. this.vertices[ i ].multiplyScalar( radius );
  19910. }
  19911. // Merge vertices
  19912. this.mergeVertices();
  19913. this.computeCentroids();
  19914. this.computeFaceNormals();
  19915. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19916. // Project vector onto sphere's surface
  19917. function prepare( vector ) {
  19918. var vertex = vector.normalize().clone();
  19919. vertex.index = that.vertices.push( vertex ) - 1;
  19920. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19921. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19922. var v = inclination( vector ) / Math.PI + 0.5;
  19923. vertex.uv = new THREE.Vector2( u, 1 - v );
  19924. return vertex;
  19925. }
  19926. // Approximate a curved face with recursively sub-divided triangles.
  19927. function make( v1, v2, v3 ) {
  19928. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19929. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19930. that.faces.push( face );
  19931. var azi = azimuth( face.centroid );
  19932. that.faceVertexUvs[ 0 ].push( [
  19933. correctUV( v1.uv, v1, azi ),
  19934. correctUV( v2.uv, v2, azi ),
  19935. correctUV( v3.uv, v3, azi )
  19936. ] );
  19937. }
  19938. // Analytically subdivide a face to the required detail level.
  19939. function subdivide(face, detail ) {
  19940. var cols = Math.pow(2, detail);
  19941. var cells = Math.pow(4, detail);
  19942. var a = prepare( that.vertices[ face.a ] );
  19943. var b = prepare( that.vertices[ face.b ] );
  19944. var c = prepare( that.vertices[ face.c ] );
  19945. var v = [];
  19946. // Construct all of the vertices for this subdivision.
  19947. for ( var i = 0 ; i <= cols; i ++ ) {
  19948. v[ i ] = [];
  19949. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19950. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19951. var rows = cols - i;
  19952. for ( var j = 0; j <= rows; j ++) {
  19953. if ( j == 0 && i == cols ) {
  19954. v[ i ][ j ] = aj;
  19955. } else {
  19956. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19957. }
  19958. }
  19959. }
  19960. // Construct all of the faces.
  19961. for ( var i = 0; i < cols ; i ++ ) {
  19962. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19963. var k = Math.floor( j / 2 );
  19964. if ( j % 2 == 0 ) {
  19965. make(
  19966. v[ i ][ k + 1],
  19967. v[ i + 1 ][ k ],
  19968. v[ i ][ k ]
  19969. );
  19970. } else {
  19971. make(
  19972. v[ i ][ k + 1 ],
  19973. v[ i + 1][ k + 1],
  19974. v[ i + 1 ][ k ]
  19975. );
  19976. }
  19977. }
  19978. }
  19979. }
  19980. // Angle around the Y axis, counter-clockwise when looking from above.
  19981. function azimuth( vector ) {
  19982. return Math.atan2( vector.z, -vector.x );
  19983. }
  19984. // Angle above the XZ plane.
  19985. function inclination( vector ) {
  19986. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19987. }
  19988. // Texture fixing helper. Spheres have some odd behaviours.
  19989. function correctUV( uv, vector, azimuth ) {
  19990. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19991. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19992. return uv.clone();
  19993. }
  19994. };
  19995. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19996. /**
  19997. * @author timothypratley / https://github.com/timothypratley
  19998. */
  19999. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20000. this.radius = radius;
  20001. this.detail = detail;
  20002. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20003. var vertices = [
  20004. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20005. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20006. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20007. ];
  20008. var faces = [
  20009. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20010. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20011. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20012. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20013. ];
  20014. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20015. };
  20016. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20017. /**
  20018. * @author timothypratley / https://github.com/timothypratley
  20019. */
  20020. THREE.OctahedronGeometry = function ( radius, detail ) {
  20021. var vertices = [
  20022. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20023. ];
  20024. var faces = [
  20025. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20026. ];
  20027. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20028. };
  20029. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20030. /**
  20031. * @author timothypratley / https://github.com/timothypratley
  20032. */
  20033. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20034. var vertices = [
  20035. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20036. ];
  20037. var faces = [
  20038. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20039. ];
  20040. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20041. };
  20042. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20043. /**
  20044. * @author zz85 / https://github.com/zz85
  20045. * Parametric Surfaces Geometry
  20046. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20047. *
  20048. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20049. *
  20050. */
  20051. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20052. THREE.Geometry.call( this );
  20053. var verts = this.vertices;
  20054. var faces = this.faces;
  20055. var uvs = this.faceVertexUvs[ 0 ];
  20056. var i, il, j, p;
  20057. var u, v;
  20058. var stackCount = stacks + 1;
  20059. var sliceCount = slices + 1;
  20060. for ( i = 0; i <= stacks; i ++ ) {
  20061. v = i / stacks;
  20062. for ( j = 0; j <= slices; j ++ ) {
  20063. u = j / slices;
  20064. p = func( u, v );
  20065. verts.push( p );
  20066. }
  20067. }
  20068. var a, b, c, d;
  20069. var uva, uvb, uvc, uvd;
  20070. for ( i = 0; i < stacks; i ++ ) {
  20071. for ( j = 0; j < slices; j ++ ) {
  20072. a = i * sliceCount + j;
  20073. b = i * sliceCount + j + 1;
  20074. c = (i + 1) * sliceCount + j + 1;
  20075. d = (i + 1) * sliceCount + j;
  20076. uva = new THREE.Vector2( j / slices, i / stacks );
  20077. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20078. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20079. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20080. faces.push( new THREE.Face3( a, b, d ) );
  20081. uvs.push( [ uva, uvb, uvd ] );
  20082. faces.push( new THREE.Face3( b, c, d ) );
  20083. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20084. }
  20085. }
  20086. // console.log(this);
  20087. // magic bullet
  20088. // var diff = this.mergeVertices();
  20089. // console.log('removed ', diff, ' vertices by merging');
  20090. this.computeCentroids();
  20091. this.computeFaceNormals();
  20092. this.computeVertexNormals();
  20093. };
  20094. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20095. /**
  20096. * @author sroucheray / http://sroucheray.org/
  20097. * @author mrdoob / http://mrdoob.com/
  20098. */
  20099. THREE.AxisHelper = function ( size ) {
  20100. size = size || 1;
  20101. var geometry = new THREE.Geometry();
  20102. geometry.vertices.push(
  20103. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20104. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20105. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20106. );
  20107. geometry.colors.push(
  20108. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20109. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20110. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20111. );
  20112. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20113. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20114. };
  20115. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20116. /**
  20117. * @author WestLangley / http://github.com/WestLangley
  20118. * @author zz85 / http://github.com/zz85
  20119. * @author bhouston / http://exocortex.com
  20120. *
  20121. * Creates an arrow for visualizing directions
  20122. *
  20123. * Parameters:
  20124. * dir - Vector3
  20125. * origin - Vector3
  20126. * length - Number
  20127. * hex - color in hex value
  20128. */
  20129. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20130. // dir is assumed to be normalized
  20131. THREE.Object3D.call( this );
  20132. if ( hex === undefined ) hex = 0xffff00;
  20133. if ( length === undefined ) length = 1;
  20134. this.position = origin;
  20135. var lineGeometry = new THREE.Geometry();
  20136. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20137. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20138. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20139. this.line.matrixAutoUpdate = false;
  20140. this.add( this.line );
  20141. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20142. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20143. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20144. this.cone.matrixAutoUpdate = false;
  20145. this.add( this.cone );
  20146. this.setDirection( dir );
  20147. this.setLength( length );
  20148. };
  20149. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20150. THREE.ArrowHelper.prototype.setDirection = function () {
  20151. var axis = new THREE.Vector3();
  20152. var radians;
  20153. return function ( dir ) {
  20154. // dir is assumed to be normalized
  20155. if ( dir.y > 0.99999 ) {
  20156. this.quaternion.set( 0, 0, 0, 1 );
  20157. } else if ( dir.y < - 0.99999 ) {
  20158. this.quaternion.set( 1, 0, 0, 0 );
  20159. } else {
  20160. axis.set( dir.z, 0, - dir.x ).normalize();
  20161. radians = Math.acos( dir.y );
  20162. this.quaternion.setFromAxisAngle( axis, radians );
  20163. }
  20164. };
  20165. }();
  20166. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20167. this.scale.set( length, length, length );
  20168. };
  20169. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20170. this.line.material.color.setHex( hex );
  20171. this.cone.material.color.setHex( hex );
  20172. };
  20173. /**
  20174. * @author mrdoob / http://mrdoob.com/
  20175. */
  20176. THREE.BoxHelper = function ( object ) {
  20177. // 5____4
  20178. // 1/___0/|
  20179. // | 6__|_7
  20180. // 2/___3/
  20181. var vertices = [
  20182. new THREE.Vector3( 1, 1, 1 ),
  20183. new THREE.Vector3( - 1, 1, 1 ),
  20184. new THREE.Vector3( - 1, - 1, 1 ),
  20185. new THREE.Vector3( 1, - 1, 1 ),
  20186. new THREE.Vector3( 1, 1, - 1 ),
  20187. new THREE.Vector3( - 1, 1, - 1 ),
  20188. new THREE.Vector3( - 1, - 1, - 1 ),
  20189. new THREE.Vector3( 1, - 1, - 1 )
  20190. ];
  20191. this.vertices = vertices;
  20192. // TODO: Wouldn't be nice if Line had .segments?
  20193. var geometry = new THREE.Geometry();
  20194. geometry.vertices.push(
  20195. vertices[ 0 ], vertices[ 1 ],
  20196. vertices[ 1 ], vertices[ 2 ],
  20197. vertices[ 2 ], vertices[ 3 ],
  20198. vertices[ 3 ], vertices[ 0 ],
  20199. vertices[ 4 ], vertices[ 5 ],
  20200. vertices[ 5 ], vertices[ 6 ],
  20201. vertices[ 6 ], vertices[ 7 ],
  20202. vertices[ 7 ], vertices[ 4 ],
  20203. vertices[ 0 ], vertices[ 4 ],
  20204. vertices[ 1 ], vertices[ 5 ],
  20205. vertices[ 2 ], vertices[ 6 ],
  20206. vertices[ 3 ], vertices[ 7 ]
  20207. );
  20208. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20209. if ( object !== undefined ) {
  20210. this.update( object );
  20211. }
  20212. };
  20213. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20214. THREE.BoxHelper.prototype.update = function ( object ) {
  20215. var geometry = object.geometry;
  20216. if ( geometry.boundingBox === null ) {
  20217. geometry.computeBoundingBox();
  20218. }
  20219. var min = geometry.boundingBox.min;
  20220. var max = geometry.boundingBox.max;
  20221. var vertices = this.vertices;
  20222. vertices[ 0 ].set( max.x, max.y, max.z );
  20223. vertices[ 1 ].set( min.x, max.y, max.z );
  20224. vertices[ 2 ].set( min.x, min.y, max.z );
  20225. vertices[ 3 ].set( max.x, min.y, max.z );
  20226. vertices[ 4 ].set( max.x, max.y, min.z );
  20227. vertices[ 5 ].set( min.x, max.y, min.z );
  20228. vertices[ 6 ].set( min.x, min.y, min.z );
  20229. vertices[ 7 ].set( max.x, min.y, min.z );
  20230. this.geometry.computeBoundingSphere();
  20231. this.geometry.verticesNeedUpdate = true;
  20232. this.matrixAutoUpdate = false;
  20233. this.matrixWorld = object.matrixWorld;
  20234. };
  20235. /**
  20236. * @author WestLangley / http://github.com/WestLangley
  20237. */
  20238. // a helper to show the world-axis-aligned bounding box for an object
  20239. THREE.BoundingBoxHelper = function ( object, hex ) {
  20240. var color = hex || 0x888888;
  20241. this.object = object;
  20242. this.box = new THREE.Box3();
  20243. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20244. };
  20245. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20246. THREE.BoundingBoxHelper.prototype.update = function () {
  20247. this.box.setFromObject( this.object );
  20248. this.box.size( this.scale );
  20249. this.box.center( this.position );
  20250. };
  20251. /**
  20252. * @author alteredq / http://alteredqualia.com/
  20253. *
  20254. * - shows frustum, line of sight and up of the camera
  20255. * - suitable for fast updates
  20256. * - based on frustum visualization in lightgl.js shadowmap example
  20257. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20258. */
  20259. THREE.CameraHelper = function ( camera ) {
  20260. var geometry = new THREE.Geometry();
  20261. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20262. var pointMap = {};
  20263. // colors
  20264. var hexFrustum = 0xffaa00;
  20265. var hexCone = 0xff0000;
  20266. var hexUp = 0x00aaff;
  20267. var hexTarget = 0xffffff;
  20268. var hexCross = 0x333333;
  20269. // near
  20270. addLine( "n1", "n2", hexFrustum );
  20271. addLine( "n2", "n4", hexFrustum );
  20272. addLine( "n4", "n3", hexFrustum );
  20273. addLine( "n3", "n1", hexFrustum );
  20274. // far
  20275. addLine( "f1", "f2", hexFrustum );
  20276. addLine( "f2", "f4", hexFrustum );
  20277. addLine( "f4", "f3", hexFrustum );
  20278. addLine( "f3", "f1", hexFrustum );
  20279. // sides
  20280. addLine( "n1", "f1", hexFrustum );
  20281. addLine( "n2", "f2", hexFrustum );
  20282. addLine( "n3", "f3", hexFrustum );
  20283. addLine( "n4", "f4", hexFrustum );
  20284. // cone
  20285. addLine( "p", "n1", hexCone );
  20286. addLine( "p", "n2", hexCone );
  20287. addLine( "p", "n3", hexCone );
  20288. addLine( "p", "n4", hexCone );
  20289. // up
  20290. addLine( "u1", "u2", hexUp );
  20291. addLine( "u2", "u3", hexUp );
  20292. addLine( "u3", "u1", hexUp );
  20293. // target
  20294. addLine( "c", "t", hexTarget );
  20295. addLine( "p", "c", hexCross );
  20296. // cross
  20297. addLine( "cn1", "cn2", hexCross );
  20298. addLine( "cn3", "cn4", hexCross );
  20299. addLine( "cf1", "cf2", hexCross );
  20300. addLine( "cf3", "cf4", hexCross );
  20301. function addLine( a, b, hex ) {
  20302. addPoint( a, hex );
  20303. addPoint( b, hex );
  20304. }
  20305. function addPoint( id, hex ) {
  20306. geometry.vertices.push( new THREE.Vector3() );
  20307. geometry.colors.push( new THREE.Color( hex ) );
  20308. if ( pointMap[ id ] === undefined ) {
  20309. pointMap[ id ] = [];
  20310. }
  20311. pointMap[ id ].push( geometry.vertices.length - 1 );
  20312. }
  20313. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20314. this.camera = camera;
  20315. this.matrixWorld = camera.matrixWorld;
  20316. this.matrixAutoUpdate = false;
  20317. this.pointMap = pointMap;
  20318. this.update();
  20319. };
  20320. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20321. THREE.CameraHelper.prototype.update = function () {
  20322. var vector = new THREE.Vector3();
  20323. var camera = new THREE.Camera();
  20324. var projector = new THREE.Projector();
  20325. return function () {
  20326. var scope = this;
  20327. var w = 1, h = 1;
  20328. // we need just camera projection matrix
  20329. // world matrix must be identity
  20330. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20331. // center / target
  20332. setPoint( "c", 0, 0, -1 );
  20333. setPoint( "t", 0, 0, 1 );
  20334. // near
  20335. setPoint( "n1", -w, -h, -1 );
  20336. setPoint( "n2", w, -h, -1 );
  20337. setPoint( "n3", -w, h, -1 );
  20338. setPoint( "n4", w, h, -1 );
  20339. // far
  20340. setPoint( "f1", -w, -h, 1 );
  20341. setPoint( "f2", w, -h, 1 );
  20342. setPoint( "f3", -w, h, 1 );
  20343. setPoint( "f4", w, h, 1 );
  20344. // up
  20345. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20346. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20347. setPoint( "u3", 0, h * 2, -1 );
  20348. // cross
  20349. setPoint( "cf1", -w, 0, 1 );
  20350. setPoint( "cf2", w, 0, 1 );
  20351. setPoint( "cf3", 0, -h, 1 );
  20352. setPoint( "cf4", 0, h, 1 );
  20353. setPoint( "cn1", -w, 0, -1 );
  20354. setPoint( "cn2", w, 0, -1 );
  20355. setPoint( "cn3", 0, -h, -1 );
  20356. setPoint( "cn4", 0, h, -1 );
  20357. function setPoint( point, x, y, z ) {
  20358. vector.set( x, y, z );
  20359. projector.unprojectVector( vector, camera );
  20360. var points = scope.pointMap[ point ];
  20361. if ( points !== undefined ) {
  20362. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20363. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20364. }
  20365. }
  20366. }
  20367. this.geometry.verticesNeedUpdate = true;
  20368. };
  20369. }();
  20370. /**
  20371. * @author alteredq / http://alteredqualia.com/
  20372. * @author mrdoob / http://mrdoob.com/
  20373. */
  20374. THREE.DirectionalLightHelper = function ( light, size ) {
  20375. THREE.Object3D.call( this );
  20376. this.light = light;
  20377. this.light.updateMatrixWorld();
  20378. this.matrixWorld = light.matrixWorld;
  20379. this.matrixAutoUpdate = false;
  20380. var geometry = new THREE.PlaneGeometry( size, size );
  20381. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20382. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20383. this.lightPlane = new THREE.Mesh( geometry, material );
  20384. this.add( this.lightPlane );
  20385. geometry = new THREE.Geometry();
  20386. geometry.vertices.push( new THREE.Vector3() );
  20387. geometry.vertices.push( new THREE.Vector3() );
  20388. geometry.computeLineDistances();
  20389. material = new THREE.LineBasicMaterial( { fog: false } );
  20390. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20391. this.targetLine = new THREE.Line( geometry, material );
  20392. this.add( this.targetLine );
  20393. this.update();
  20394. };
  20395. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20396. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20397. this.lightPlane.geometry.dispose();
  20398. this.lightPlane.material.dispose();
  20399. this.targetLine.geometry.dispose();
  20400. this.targetLine.material.dispose();
  20401. };
  20402. THREE.DirectionalLightHelper.prototype.update = function () {
  20403. var vector = new THREE.Vector3();
  20404. return function () {
  20405. vector.getPositionFromMatrix( this.light.matrixWorld ).negate();
  20406. this.lightPlane.lookAt( vector );
  20407. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20408. this.targetLine.geometry.vertices[ 1 ].copy( vector );
  20409. this.targetLine.geometry.verticesNeedUpdate = true;
  20410. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20411. }
  20412. }();
  20413. /**
  20414. * @author mrdoob / http://mrdoob.com/
  20415. * @author WestLangley / http://github.com/WestLangley
  20416. */
  20417. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20418. this.object = object;
  20419. this.size = size || 1;
  20420. var color = hex || 0xffff00;
  20421. var width = linewidth || 1;
  20422. var geometry = new THREE.Geometry();
  20423. var faces = this.object.geometry.faces;
  20424. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20425. geometry.vertices.push( new THREE.Vector3() );
  20426. geometry.vertices.push( new THREE.Vector3() );
  20427. }
  20428. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20429. this.matrixAutoUpdate = false;
  20430. this.normalMatrix = new THREE.Matrix3();
  20431. this.update();
  20432. };
  20433. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20434. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20435. var v1 = new THREE.Vector3();
  20436. return function ( object ) {
  20437. this.object.updateMatrixWorld( true );
  20438. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20439. var vertices = this.geometry.vertices;
  20440. var faces = this.object.geometry.faces;
  20441. var worldMatrix = this.object.matrixWorld;
  20442. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20443. var face = faces[ i ];
  20444. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20445. var idx = 2 * i;
  20446. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  20447. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20448. }
  20449. this.geometry.verticesNeedUpdate = true;
  20450. return this;
  20451. }
  20452. }());
  20453. /**
  20454. * @author mrdoob / http://mrdoob.com/
  20455. */
  20456. THREE.GridHelper = function ( size, step ) {
  20457. var geometry = new THREE.Geometry();
  20458. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20459. this.color1 = new THREE.Color( 0x444444 );
  20460. this.color2 = new THREE.Color( 0x888888 );
  20461. for ( var i = - size; i <= size; i += step ) {
  20462. geometry.vertices.push(
  20463. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20464. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20465. );
  20466. var color = i === 0 ? this.color1 : this.color2;
  20467. geometry.colors.push( color, color, color, color );
  20468. }
  20469. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20470. };
  20471. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20472. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20473. this.color1.set( colorCenterLine );
  20474. this.color2.set( colorGrid );
  20475. this.geometry.colorsNeedUpdate = true;
  20476. }
  20477. /**
  20478. * @author alteredq / http://alteredqualia.com/
  20479. * @author mrdoob / http://mrdoob.com/
  20480. */
  20481. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20482. THREE.Object3D.call( this );
  20483. this.light = light;
  20484. this.light.updateMatrixWorld();
  20485. this.matrixWorld = light.matrixWorld;
  20486. this.matrixAutoUpdate = false;
  20487. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20488. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20489. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20490. for ( var i = 0, il = 8; i < il; i ++ ) {
  20491. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20492. }
  20493. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20494. this.lightSphere = new THREE.Mesh( geometry, material );
  20495. this.add( this.lightSphere );
  20496. this.update();
  20497. };
  20498. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20499. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20500. this.lightSphere.geometry.dispose();
  20501. this.lightSphere.material.dispose();
  20502. };
  20503. THREE.HemisphereLightHelper.prototype.update = function () {
  20504. var vector = new THREE.Vector3();
  20505. return function () {
  20506. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20507. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20508. this.lightSphere.lookAt( vector.getPositionFromMatrix( this.light.matrixWorld ).negate() );
  20509. this.lightSphere.geometry.colorsNeedUpdate = true;
  20510. }
  20511. }();
  20512. /**
  20513. * @author alteredq / http://alteredqualia.com/
  20514. * @author mrdoob / http://mrdoob.com/
  20515. */
  20516. THREE.PointLightHelper = function ( light, sphereSize ) {
  20517. this.light = light;
  20518. this.light.updateMatrixWorld();
  20519. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20520. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20521. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20522. THREE.Mesh.call( this, geometry, material );
  20523. this.matrixWorld = this.light.matrixWorld;
  20524. this.matrixAutoUpdate = false;
  20525. /*
  20526. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20527. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20528. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20529. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20530. var d = light.distance;
  20531. if ( d === 0.0 ) {
  20532. this.lightDistance.visible = false;
  20533. } else {
  20534. this.lightDistance.scale.set( d, d, d );
  20535. }
  20536. this.add( this.lightDistance );
  20537. */
  20538. };
  20539. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20540. THREE.PointLightHelper.prototype.dispose = function () {
  20541. this.geometry.dispose();
  20542. this.material.dispose();
  20543. };
  20544. THREE.PointLightHelper.prototype.update = function () {
  20545. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20546. /*
  20547. var d = this.light.distance;
  20548. if ( d === 0.0 ) {
  20549. this.lightDistance.visible = false;
  20550. } else {
  20551. this.lightDistance.visible = true;
  20552. this.lightDistance.scale.set( d, d, d );
  20553. }
  20554. */
  20555. };
  20556. /**
  20557. * @author alteredq / http://alteredqualia.com/
  20558. * @author mrdoob / http://mrdoob.com/
  20559. * @author WestLangley / http://github.com/WestLangley
  20560. */
  20561. THREE.SpotLightHelper = function ( light ) {
  20562. THREE.Object3D.call( this );
  20563. this.light = light;
  20564. this.light.updateMatrixWorld();
  20565. this.matrixWorld = light.matrixWorld;
  20566. this.matrixAutoUpdate = false;
  20567. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20568. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20569. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20570. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20571. this.cone = new THREE.Mesh( geometry, material );
  20572. this.add( this.cone );
  20573. this.update();
  20574. };
  20575. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20576. THREE.SpotLightHelper.prototype.dispose = function () {
  20577. this.cone.geometry.dispose();
  20578. this.cone.material.dispose();
  20579. };
  20580. THREE.SpotLightHelper.prototype.update = function () {
  20581. var vector = new THREE.Vector3();
  20582. var vector2 = new THREE.Vector3();
  20583. return function () {
  20584. var coneLength = this.light.distance ? this.light.distance : 10000;
  20585. var coneWidth = coneLength * Math.tan( this.light.angle );
  20586. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20587. vector.getPositionFromMatrix( this.light.matrixWorld );
  20588. vector2.getPositionFromMatrix( this.light.target.matrixWorld );
  20589. this.cone.lookAt( vector2.sub( vector ) );
  20590. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20591. };
  20592. }();
  20593. /**
  20594. * @author mrdoob / http://mrdoob.com/
  20595. * @author WestLangley / http://github.com/WestLangley
  20596. */
  20597. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20598. this.object = object;
  20599. this.size = size || 1;
  20600. var color = hex || 0xff0000;
  20601. var width = linewidth || 1;
  20602. var geometry = new THREE.Geometry();
  20603. var vertices = object.geometry.vertices;
  20604. var faces = object.geometry.faces;
  20605. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20606. var face = faces[ i ];
  20607. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20608. geometry.vertices.push( new THREE.Vector3() );
  20609. geometry.vertices.push( new THREE.Vector3() );
  20610. }
  20611. }
  20612. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20613. this.matrixAutoUpdate = false;
  20614. this.normalMatrix = new THREE.Matrix3();
  20615. this.update();
  20616. };
  20617. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20618. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20619. var v1 = new THREE.Vector3();
  20620. return function( object ) {
  20621. var keys = [ 'a', 'b', 'c', 'd' ];
  20622. this.object.updateMatrixWorld( true );
  20623. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20624. var vertices = this.geometry.vertices;
  20625. var verts = this.object.geometry.vertices;
  20626. var faces = this.object.geometry.faces;
  20627. var worldMatrix = this.object.matrixWorld;
  20628. var idx = 0;
  20629. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20630. var face = faces[ i ];
  20631. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20632. var vertexId = face[ keys[ j ] ];
  20633. var vertex = verts[ vertexId ];
  20634. var normal = face.vertexNormals[ j ];
  20635. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20636. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20637. v1.add( vertices[ idx ] );
  20638. idx = idx + 1;
  20639. vertices[ idx ].copy( v1 );
  20640. idx = idx + 1;
  20641. }
  20642. }
  20643. this.geometry.verticesNeedUpdate = true;
  20644. return this;
  20645. }
  20646. }());
  20647. /**
  20648. * @author mrdoob / http://mrdoob.com/
  20649. * @author WestLangley / http://github.com/WestLangley
  20650. */
  20651. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20652. this.object = object;
  20653. this.size = size || 1;
  20654. var color = hex || 0x0000ff;
  20655. var width = linewidth || 1;
  20656. var geometry = new THREE.Geometry();
  20657. var vertices = object.geometry.vertices;
  20658. var faces = object.geometry.faces;
  20659. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20660. var face = faces[ i ];
  20661. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20662. geometry.vertices.push( new THREE.Vector3() );
  20663. geometry.vertices.push( new THREE.Vector3() );
  20664. }
  20665. }
  20666. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20667. this.matrixAutoUpdate = false;
  20668. this.update();
  20669. };
  20670. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20671. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20672. var v1 = new THREE.Vector3();
  20673. return function( object ) {
  20674. var keys = [ 'a', 'b', 'c', 'd' ];
  20675. this.object.updateMatrixWorld( true );
  20676. var vertices = this.geometry.vertices;
  20677. var verts = this.object.geometry.vertices;
  20678. var faces = this.object.geometry.faces;
  20679. var worldMatrix = this.object.matrixWorld;
  20680. var idx = 0;
  20681. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20682. var face = faces[ i ];
  20683. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20684. var vertexId = face[ keys[ j ] ];
  20685. var vertex = verts[ vertexId ];
  20686. var tangent = face.vertexTangents[ j ];
  20687. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20688. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20689. v1.add( vertices[ idx ] );
  20690. idx = idx + 1;
  20691. vertices[ idx ].copy( v1 );
  20692. idx = idx + 1;
  20693. }
  20694. }
  20695. this.geometry.verticesNeedUpdate = true;
  20696. return this;
  20697. }
  20698. }());
  20699. /**
  20700. * @author mrdoob / http://mrdoob.com/
  20701. */
  20702. THREE.WireframeHelper = function ( object ) {
  20703. var edge = [ 0, 0 ], hash = {};
  20704. var sortFunction = function ( a, b ) { return a - b };
  20705. var keys = [ 'a', 'b', 'c', 'd' ];
  20706. var geometry = new THREE.Geometry();
  20707. var vertices = object.geometry.vertices;
  20708. var faces = object.geometry.faces;
  20709. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20710. var face = faces[ i ];
  20711. for ( var j = 0; j < 3; j ++ ) {
  20712. edge[ 0 ] = face[ keys[ j ] ];
  20713. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20714. edge.sort( sortFunction );
  20715. var key = edge.toString();
  20716. if ( hash[ key ] === undefined ) {
  20717. geometry.vertices.push( vertices[ edge[ 0 ] ] );
  20718. geometry.vertices.push( vertices[ edge[ 1 ] ] );
  20719. hash[ key ] = true;
  20720. }
  20721. }
  20722. }
  20723. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  20724. this.matrixAutoUpdate = false;
  20725. this.matrixWorld = object.matrixWorld;
  20726. };
  20727. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20728. /**
  20729. * @author alteredq / http://alteredqualia.com/
  20730. */
  20731. THREE.ImmediateRenderObject = function () {
  20732. THREE.Object3D.call( this );
  20733. this.render = function ( renderCallback ) { };
  20734. };
  20735. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20736. /**
  20737. * @author mikael emtinger / http://gomo.se/
  20738. * @author alteredq / http://alteredqualia.com/
  20739. */
  20740. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20741. THREE.Object3D.call( this );
  20742. this.lensFlares = [];
  20743. this.positionScreen = new THREE.Vector3();
  20744. this.customUpdateCallback = undefined;
  20745. if( texture !== undefined ) {
  20746. this.add( texture, size, distance, blending, color );
  20747. }
  20748. };
  20749. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20750. /*
  20751. * Add: adds another flare
  20752. */
  20753. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20754. if( size === undefined ) size = -1;
  20755. if( distance === undefined ) distance = 0;
  20756. if( opacity === undefined ) opacity = 1;
  20757. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20758. if( blending === undefined ) blending = THREE.NormalBlending;
  20759. distance = Math.min( distance, Math.max( 0, distance ) );
  20760. this.lensFlares.push( { texture: texture, // THREE.Texture
  20761. size: size, // size in pixels (-1 = use texture.width)
  20762. distance: distance, // distance (0-1) from light source (0=at light source)
  20763. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20764. scale: 1, // scale
  20765. rotation: 1, // rotation
  20766. opacity: opacity, // opacity
  20767. color: color, // color
  20768. blending: blending } ); // blending
  20769. };
  20770. /*
  20771. * Update lens flares update positions on all flares based on the screen position
  20772. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20773. */
  20774. THREE.LensFlare.prototype.updateLensFlares = function () {
  20775. var f, fl = this.lensFlares.length;
  20776. var flare;
  20777. var vecX = -this.positionScreen.x * 2;
  20778. var vecY = -this.positionScreen.y * 2;
  20779. for( f = 0; f < fl; f ++ ) {
  20780. flare = this.lensFlares[ f ];
  20781. flare.x = this.positionScreen.x + vecX * flare.distance;
  20782. flare.y = this.positionScreen.y + vecY * flare.distance;
  20783. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20784. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20785. }
  20786. };
  20787. /**
  20788. * @author alteredq / http://alteredqualia.com/
  20789. */
  20790. THREE.MorphBlendMesh = function( geometry, material ) {
  20791. THREE.Mesh.call( this, geometry, material );
  20792. this.animationsMap = {};
  20793. this.animationsList = [];
  20794. // prepare default animation
  20795. // (all frames played together in 1 second)
  20796. var numFrames = this.geometry.morphTargets.length;
  20797. var name = "__default";
  20798. var startFrame = 0;
  20799. var endFrame = numFrames - 1;
  20800. var fps = numFrames / 1;
  20801. this.createAnimation( name, startFrame, endFrame, fps );
  20802. this.setAnimationWeight( name, 1 );
  20803. };
  20804. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20805. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20806. var animation = {
  20807. startFrame: start,
  20808. endFrame: end,
  20809. length: end - start + 1,
  20810. fps: fps,
  20811. duration: ( end - start ) / fps,
  20812. lastFrame: 0,
  20813. currentFrame: 0,
  20814. active: false,
  20815. time: 0,
  20816. direction: 1,
  20817. weight: 1,
  20818. directionBackwards: false,
  20819. mirroredLoop: false
  20820. };
  20821. this.animationsMap[ name ] = animation;
  20822. this.animationsList.push( animation );
  20823. };
  20824. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20825. var pattern = /([a-z]+)(\d+)/;
  20826. var firstAnimation, frameRanges = {};
  20827. var geometry = this.geometry;
  20828. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20829. var morph = geometry.morphTargets[ i ];
  20830. var chunks = morph.name.match( pattern );
  20831. if ( chunks && chunks.length > 1 ) {
  20832. var name = chunks[ 1 ];
  20833. var num = chunks[ 2 ];
  20834. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20835. var range = frameRanges[ name ];
  20836. if ( i < range.start ) range.start = i;
  20837. if ( i > range.end ) range.end = i;
  20838. if ( ! firstAnimation ) firstAnimation = name;
  20839. }
  20840. }
  20841. for ( var name in frameRanges ) {
  20842. var range = frameRanges[ name ];
  20843. this.createAnimation( name, range.start, range.end, fps );
  20844. }
  20845. this.firstAnimation = firstAnimation;
  20846. };
  20847. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20848. var animation = this.animationsMap[ name ];
  20849. if ( animation ) {
  20850. animation.direction = 1;
  20851. animation.directionBackwards = false;
  20852. }
  20853. };
  20854. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20855. var animation = this.animationsMap[ name ];
  20856. if ( animation ) {
  20857. animation.direction = -1;
  20858. animation.directionBackwards = true;
  20859. }
  20860. };
  20861. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20862. var animation = this.animationsMap[ name ];
  20863. if ( animation ) {
  20864. animation.fps = fps;
  20865. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20866. }
  20867. };
  20868. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20869. var animation = this.animationsMap[ name ];
  20870. if ( animation ) {
  20871. animation.duration = duration;
  20872. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20873. }
  20874. };
  20875. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20876. var animation = this.animationsMap[ name ];
  20877. if ( animation ) {
  20878. animation.weight = weight;
  20879. }
  20880. };
  20881. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20882. var animation = this.animationsMap[ name ];
  20883. if ( animation ) {
  20884. animation.time = time;
  20885. }
  20886. };
  20887. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20888. var time = 0;
  20889. var animation = this.animationsMap[ name ];
  20890. if ( animation ) {
  20891. time = animation.time;
  20892. }
  20893. return time;
  20894. };
  20895. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20896. var duration = -1;
  20897. var animation = this.animationsMap[ name ];
  20898. if ( animation ) {
  20899. duration = animation.duration;
  20900. }
  20901. return duration;
  20902. };
  20903. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20904. var animation = this.animationsMap[ name ];
  20905. if ( animation ) {
  20906. animation.time = 0;
  20907. animation.active = true;
  20908. } else {
  20909. console.warn( "animation[" + name + "] undefined" );
  20910. }
  20911. };
  20912. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20913. var animation = this.animationsMap[ name ];
  20914. if ( animation ) {
  20915. animation.active = false;
  20916. }
  20917. };
  20918. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20919. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20920. var animation = this.animationsList[ i ];
  20921. if ( ! animation.active ) continue;
  20922. var frameTime = animation.duration / animation.length;
  20923. animation.time += animation.direction * delta;
  20924. if ( animation.mirroredLoop ) {
  20925. if ( animation.time > animation.duration || animation.time < 0 ) {
  20926. animation.direction *= -1;
  20927. if ( animation.time > animation.duration ) {
  20928. animation.time = animation.duration;
  20929. animation.directionBackwards = true;
  20930. }
  20931. if ( animation.time < 0 ) {
  20932. animation.time = 0;
  20933. animation.directionBackwards = false;
  20934. }
  20935. }
  20936. } else {
  20937. animation.time = animation.time % animation.duration;
  20938. if ( animation.time < 0 ) animation.time += animation.duration;
  20939. }
  20940. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20941. var weight = animation.weight;
  20942. if ( keyframe !== animation.currentFrame ) {
  20943. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20944. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20945. this.morphTargetInfluences[ keyframe ] = 0;
  20946. animation.lastFrame = animation.currentFrame;
  20947. animation.currentFrame = keyframe;
  20948. }
  20949. var mix = ( animation.time % frameTime ) / frameTime;
  20950. if ( animation.directionBackwards ) mix = 1 - mix;
  20951. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20952. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20953. }
  20954. };
  20955. /**
  20956. * @author mikael emtinger / http://gomo.se/
  20957. * @author alteredq / http://alteredqualia.com/
  20958. */
  20959. THREE.LensFlarePlugin = function () {
  20960. var _gl, _renderer, _precision, _lensFlare = {};
  20961. this.init = function ( renderer ) {
  20962. _gl = renderer.context;
  20963. _renderer = renderer;
  20964. _precision = renderer.getPrecision();
  20965. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20966. _lensFlare.faces = new Uint16Array( 6 );
  20967. var i = 0;
  20968. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20969. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20970. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20971. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20972. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20973. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20974. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20975. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20976. i = 0;
  20977. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20978. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20979. // buffers
  20980. _lensFlare.vertexBuffer = _gl.createBuffer();
  20981. _lensFlare.elementBuffer = _gl.createBuffer();
  20982. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20983. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20984. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20985. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20986. // textures
  20987. _lensFlare.tempTexture = _gl.createTexture();
  20988. _lensFlare.occlusionTexture = _gl.createTexture();
  20989. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20990. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20991. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20992. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20993. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20994. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20995. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20996. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20997. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20998. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20999. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21000. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21001. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21002. _lensFlare.hasVertexTexture = false;
  21003. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21004. } else {
  21005. _lensFlare.hasVertexTexture = true;
  21006. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21007. }
  21008. _lensFlare.attributes = {};
  21009. _lensFlare.uniforms = {};
  21010. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21011. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21012. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21013. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21014. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21015. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21016. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21017. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21018. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21019. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21020. };
  21021. /*
  21022. * Render lens flares
  21023. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21024. * reads these back and calculates occlusion.
  21025. * Then _lensFlare.update_lensFlares() is called to re-position and
  21026. * update transparency of flares. Then they are rendered.
  21027. *
  21028. */
  21029. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21030. var flares = scene.__webglFlares,
  21031. nFlares = flares.length;
  21032. if ( ! nFlares ) return;
  21033. var tempPosition = new THREE.Vector3();
  21034. var invAspect = viewportHeight / viewportWidth,
  21035. halfViewportWidth = viewportWidth * 0.5,
  21036. halfViewportHeight = viewportHeight * 0.5;
  21037. var size = 16 / viewportHeight,
  21038. scale = new THREE.Vector2( size * invAspect, size );
  21039. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21040. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21041. var uniforms = _lensFlare.uniforms,
  21042. attributes = _lensFlare.attributes;
  21043. // set _lensFlare program and reset blending
  21044. _gl.useProgram( _lensFlare.program );
  21045. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21046. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21047. // loop through all lens flares to update their occlusion and positions
  21048. // setup gl and common used attribs/unforms
  21049. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21050. _gl.uniform1i( uniforms.map, 1 );
  21051. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21052. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21053. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21054. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21055. _gl.disable( _gl.CULL_FACE );
  21056. _gl.depthMask( false );
  21057. var i, j, jl, flare, sprite;
  21058. for ( i = 0; i < nFlares; i ++ ) {
  21059. size = 16 / viewportHeight;
  21060. scale.set( size * invAspect, size );
  21061. // calc object screen position
  21062. flare = flares[ i ];
  21063. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21064. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21065. tempPosition.applyProjection( camera.projectionMatrix );
  21066. // setup arrays for gl programs
  21067. screenPosition.copy( tempPosition )
  21068. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21069. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21070. // screen cull
  21071. if ( _lensFlare.hasVertexTexture || (
  21072. screenPositionPixels.x > 0 &&
  21073. screenPositionPixels.x < viewportWidth &&
  21074. screenPositionPixels.y > 0 &&
  21075. screenPositionPixels.y < viewportHeight ) ) {
  21076. // save current RGB to temp texture
  21077. _gl.activeTexture( _gl.TEXTURE1 );
  21078. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21079. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21080. // render pink quad
  21081. _gl.uniform1i( uniforms.renderType, 0 );
  21082. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21083. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21084. _gl.disable( _gl.BLEND );
  21085. _gl.enable( _gl.DEPTH_TEST );
  21086. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21087. // copy result to occlusionMap
  21088. _gl.activeTexture( _gl.TEXTURE0 );
  21089. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21090. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21091. // restore graphics
  21092. _gl.uniform1i( uniforms.renderType, 1 );
  21093. _gl.disable( _gl.DEPTH_TEST );
  21094. _gl.activeTexture( _gl.TEXTURE1 );
  21095. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21096. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21097. // update object positions
  21098. flare.positionScreen.copy( screenPosition )
  21099. if ( flare.customUpdateCallback ) {
  21100. flare.customUpdateCallback( flare );
  21101. } else {
  21102. flare.updateLensFlares();
  21103. }
  21104. // render flares
  21105. _gl.uniform1i( uniforms.renderType, 2 );
  21106. _gl.enable( _gl.BLEND );
  21107. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21108. sprite = flare.lensFlares[ j ];
  21109. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21110. screenPosition.x = sprite.x;
  21111. screenPosition.y = sprite.y;
  21112. screenPosition.z = sprite.z;
  21113. size = sprite.size * sprite.scale / viewportHeight;
  21114. scale.x = size * invAspect;
  21115. scale.y = size;
  21116. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21117. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21118. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21119. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21120. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21121. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21122. _renderer.setTexture( sprite.texture, 1 );
  21123. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21124. }
  21125. }
  21126. }
  21127. }
  21128. // restore gl
  21129. _gl.enable( _gl.CULL_FACE );
  21130. _gl.enable( _gl.DEPTH_TEST );
  21131. _gl.depthMask( true );
  21132. };
  21133. function createProgram ( shader, precision ) {
  21134. var program = _gl.createProgram();
  21135. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21136. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21137. var prefix = "precision " + precision + " float;\n";
  21138. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21139. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21140. _gl.compileShader( fragmentShader );
  21141. _gl.compileShader( vertexShader );
  21142. _gl.attachShader( program, fragmentShader );
  21143. _gl.attachShader( program, vertexShader );
  21144. _gl.linkProgram( program );
  21145. return program;
  21146. };
  21147. };
  21148. /**
  21149. * @author alteredq / http://alteredqualia.com/
  21150. */
  21151. THREE.ShadowMapPlugin = function () {
  21152. var _gl,
  21153. _renderer,
  21154. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21155. _frustum = new THREE.Frustum(),
  21156. _projScreenMatrix = new THREE.Matrix4(),
  21157. _min = new THREE.Vector3(),
  21158. _max = new THREE.Vector3(),
  21159. _matrixPosition = new THREE.Vector3();
  21160. this.init = function ( renderer ) {
  21161. _gl = renderer.context;
  21162. _renderer = renderer;
  21163. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21164. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21165. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21166. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21167. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21168. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21169. _depthMaterial._shadowPass = true;
  21170. _depthMaterialMorph._shadowPass = true;
  21171. _depthMaterialSkin._shadowPass = true;
  21172. _depthMaterialMorphSkin._shadowPass = true;
  21173. };
  21174. this.render = function ( scene, camera ) {
  21175. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21176. this.update( scene, camera );
  21177. };
  21178. this.update = function ( scene, camera ) {
  21179. var i, il, j, jl, n,
  21180. shadowMap, shadowMatrix, shadowCamera,
  21181. program, buffer, material,
  21182. webglObject, object, light,
  21183. renderList,
  21184. lights = [],
  21185. k = 0,
  21186. fog = null;
  21187. // set GL state for depth map
  21188. _gl.clearColor( 1, 1, 1, 1 );
  21189. _gl.disable( _gl.BLEND );
  21190. _gl.enable( _gl.CULL_FACE );
  21191. _gl.frontFace( _gl.CCW );
  21192. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21193. _gl.cullFace( _gl.FRONT );
  21194. } else {
  21195. _gl.cullFace( _gl.BACK );
  21196. }
  21197. _renderer.setDepthTest( true );
  21198. // preprocess lights
  21199. // - skip lights that are not casting shadows
  21200. // - create virtual lights for cascaded shadow maps
  21201. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21202. light = scene.__lights[ i ];
  21203. if ( ! light.castShadow ) continue;
  21204. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21205. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21206. var virtualLight;
  21207. if ( ! light.shadowCascadeArray[ n ] ) {
  21208. virtualLight = createVirtualLight( light, n );
  21209. virtualLight.originalCamera = camera;
  21210. var gyro = new THREE.Gyroscope();
  21211. gyro.position = light.shadowCascadeOffset;
  21212. gyro.add( virtualLight );
  21213. gyro.add( virtualLight.target );
  21214. camera.add( gyro );
  21215. light.shadowCascadeArray[ n ] = virtualLight;
  21216. console.log( "Created virtualLight", virtualLight );
  21217. } else {
  21218. virtualLight = light.shadowCascadeArray[ n ];
  21219. }
  21220. updateVirtualLight( light, n );
  21221. lights[ k ] = virtualLight;
  21222. k ++;
  21223. }
  21224. } else {
  21225. lights[ k ] = light;
  21226. k ++;
  21227. }
  21228. }
  21229. // render depth map
  21230. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21231. light = lights[ i ];
  21232. if ( ! light.shadowMap ) {
  21233. var shadowFilter = THREE.LinearFilter;
  21234. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21235. shadowFilter = THREE.NearestFilter;
  21236. }
  21237. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21238. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21239. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21240. light.shadowMatrix = new THREE.Matrix4();
  21241. }
  21242. if ( ! light.shadowCamera ) {
  21243. if ( light instanceof THREE.SpotLight ) {
  21244. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21245. } else if ( light instanceof THREE.DirectionalLight ) {
  21246. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21247. } else {
  21248. console.error( "Unsupported light type for shadow" );
  21249. continue;
  21250. }
  21251. scene.add( light.shadowCamera );
  21252. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21253. }
  21254. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21255. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21256. light.shadowCamera.add( light.cameraHelper );
  21257. }
  21258. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21259. updateShadowCamera( camera, light );
  21260. }
  21261. shadowMap = light.shadowMap;
  21262. shadowMatrix = light.shadowMatrix;
  21263. shadowCamera = light.shadowCamera;
  21264. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21265. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21266. shadowCamera.lookAt( _matrixPosition );
  21267. shadowCamera.updateMatrixWorld();
  21268. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21269. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21270. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21271. // compute shadow matrix
  21272. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21273. 0.0, 0.5, 0.0, 0.5,
  21274. 0.0, 0.0, 0.5, 0.5,
  21275. 0.0, 0.0, 0.0, 1.0 );
  21276. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21277. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21278. // update camera matrices and frustum
  21279. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21280. _frustum.setFromMatrix( _projScreenMatrix );
  21281. // render shadow map
  21282. _renderer.setRenderTarget( shadowMap );
  21283. _renderer.clear();
  21284. // set object matrices & frustum culling
  21285. renderList = scene.__webglObjects;
  21286. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21287. webglObject = renderList[ j ];
  21288. object = webglObject.object;
  21289. webglObject.render = false;
  21290. if ( object.visible && object.castShadow ) {
  21291. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21292. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21293. webglObject.render = true;
  21294. }
  21295. }
  21296. }
  21297. // render regular objects
  21298. var objectMaterial, useMorphing, useSkinning;
  21299. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21300. webglObject = renderList[ j ];
  21301. if ( webglObject.render ) {
  21302. object = webglObject.object;
  21303. buffer = webglObject.buffer;
  21304. // culling is overriden globally for all objects
  21305. // while rendering depth map
  21306. // need to deal with MeshFaceMaterial somehow
  21307. // in that case just use the first of material.materials for now
  21308. // (proper solution would require to break objects by materials
  21309. // similarly to regular rendering and then set corresponding
  21310. // depth materials per each chunk instead of just once per object)
  21311. objectMaterial = getObjectMaterial( object );
  21312. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21313. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21314. if ( object.customDepthMaterial ) {
  21315. material = object.customDepthMaterial;
  21316. } else if ( useSkinning ) {
  21317. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21318. } else if ( useMorphing ) {
  21319. material = _depthMaterialMorph;
  21320. } else {
  21321. material = _depthMaterial;
  21322. }
  21323. if ( buffer instanceof THREE.BufferGeometry ) {
  21324. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21325. } else {
  21326. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21327. }
  21328. }
  21329. }
  21330. // set matrices and render immediate objects
  21331. renderList = scene.__webglObjectsImmediate;
  21332. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21333. webglObject = renderList[ j ];
  21334. object = webglObject.object;
  21335. if ( object.visible && object.castShadow ) {
  21336. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21337. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21338. }
  21339. }
  21340. }
  21341. // restore GL state
  21342. var clearColor = _renderer.getClearColor(),
  21343. clearAlpha = _renderer.getClearAlpha();
  21344. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21345. _gl.enable( _gl.BLEND );
  21346. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21347. _gl.cullFace( _gl.BACK );
  21348. }
  21349. };
  21350. function createVirtualLight( light, cascade ) {
  21351. var virtualLight = new THREE.DirectionalLight();
  21352. virtualLight.isVirtual = true;
  21353. virtualLight.onlyShadow = true;
  21354. virtualLight.castShadow = true;
  21355. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21356. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21357. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21358. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21359. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21360. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21361. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21362. virtualLight.shadowDarkness = light.shadowDarkness;
  21363. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21364. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21365. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21366. virtualLight.pointsWorld = [];
  21367. virtualLight.pointsFrustum = [];
  21368. var pointsWorld = virtualLight.pointsWorld,
  21369. pointsFrustum = virtualLight.pointsFrustum;
  21370. for ( var i = 0; i < 8; i ++ ) {
  21371. pointsWorld[ i ] = new THREE.Vector3();
  21372. pointsFrustum[ i ] = new THREE.Vector3();
  21373. }
  21374. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21375. var farZ = light.shadowCascadeFarZ[ cascade ];
  21376. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21377. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21378. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21379. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21380. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21381. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21382. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21383. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21384. return virtualLight;
  21385. }
  21386. // Synchronize virtual light with the original light
  21387. function updateVirtualLight( light, cascade ) {
  21388. var virtualLight = light.shadowCascadeArray[ cascade ];
  21389. virtualLight.position.copy( light.position );
  21390. virtualLight.target.position.copy( light.target.position );
  21391. virtualLight.lookAt( virtualLight.target );
  21392. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21393. virtualLight.shadowDarkness = light.shadowDarkness;
  21394. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21395. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21396. var farZ = light.shadowCascadeFarZ[ cascade ];
  21397. var pointsFrustum = virtualLight.pointsFrustum;
  21398. pointsFrustum[ 0 ].z = nearZ;
  21399. pointsFrustum[ 1 ].z = nearZ;
  21400. pointsFrustum[ 2 ].z = nearZ;
  21401. pointsFrustum[ 3 ].z = nearZ;
  21402. pointsFrustum[ 4 ].z = farZ;
  21403. pointsFrustum[ 5 ].z = farZ;
  21404. pointsFrustum[ 6 ].z = farZ;
  21405. pointsFrustum[ 7 ].z = farZ;
  21406. }
  21407. // Fit shadow camera's ortho frustum to camera frustum
  21408. function updateShadowCamera( camera, light ) {
  21409. var shadowCamera = light.shadowCamera,
  21410. pointsFrustum = light.pointsFrustum,
  21411. pointsWorld = light.pointsWorld;
  21412. _min.set( Infinity, Infinity, Infinity );
  21413. _max.set( -Infinity, -Infinity, -Infinity );
  21414. for ( var i = 0; i < 8; i ++ ) {
  21415. var p = pointsWorld[ i ];
  21416. p.copy( pointsFrustum[ i ] );
  21417. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21418. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21419. if ( p.x < _min.x ) _min.x = p.x;
  21420. if ( p.x > _max.x ) _max.x = p.x;
  21421. if ( p.y < _min.y ) _min.y = p.y;
  21422. if ( p.y > _max.y ) _max.y = p.y;
  21423. if ( p.z < _min.z ) _min.z = p.z;
  21424. if ( p.z > _max.z ) _max.z = p.z;
  21425. }
  21426. shadowCamera.left = _min.x;
  21427. shadowCamera.right = _max.x;
  21428. shadowCamera.top = _max.y;
  21429. shadowCamera.bottom = _min.y;
  21430. // can't really fit near/far
  21431. //shadowCamera.near = _min.z;
  21432. //shadowCamera.far = _max.z;
  21433. shadowCamera.updateProjectionMatrix();
  21434. }
  21435. // For the moment just ignore objects that have multiple materials with different animation methods
  21436. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21437. function getObjectMaterial( object ) {
  21438. return object.material instanceof THREE.MeshFaceMaterial
  21439. ? object.material.materials[ 0 ]
  21440. : object.material;
  21441. };
  21442. };
  21443. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21444. /**
  21445. * @author mikael emtinger / http://gomo.se/
  21446. * @author alteredq / http://alteredqualia.com/
  21447. */
  21448. THREE.SpritePlugin = function () {
  21449. var _gl, _renderer, _precision, _sprite = {};
  21450. this.init = function ( renderer ) {
  21451. _gl = renderer.context;
  21452. _renderer = renderer;
  21453. _precision = renderer.getPrecision();
  21454. _sprite.vertices = new Float32Array( 8 + 8 );
  21455. _sprite.faces = new Uint16Array( 6 );
  21456. var i = 0;
  21457. _sprite.vertices[ i++ ] = -0.5; _sprite.vertices[ i++ ] = -0.5; // vertex 0
  21458. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21459. _sprite.vertices[ i++ ] = 0.5; _sprite.vertices[ i++ ] = -0.5; // vertex 1
  21460. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21461. _sprite.vertices[ i++ ] = 0.5; _sprite.vertices[ i++ ] = 0.5; // vertex 2
  21462. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21463. _sprite.vertices[ i++ ] = -0.5; _sprite.vertices[ i++ ] = 0.5; // vertex 3
  21464. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21465. i = 0;
  21466. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21467. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21468. _sprite.vertexBuffer = _gl.createBuffer();
  21469. _sprite.elementBuffer = _gl.createBuffer();
  21470. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21471. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21472. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21473. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21474. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21475. _sprite.attributes = {};
  21476. _sprite.uniforms = {};
  21477. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21478. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21479. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21480. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21481. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21482. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21483. _sprite.uniforms.halfViewport = _gl.getUniformLocation( _sprite.program, "halfViewport" );
  21484. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21485. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21486. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21487. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21488. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21489. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21490. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21491. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21492. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21493. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21494. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21495. };
  21496. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21497. var sprites = scene.__webglSprites,
  21498. nSprites = sprites.length;
  21499. if ( ! nSprites ) return;
  21500. var attributes = _sprite.attributes,
  21501. uniforms = _sprite.uniforms;
  21502. var halfViewportWidth = viewportWidth * 0.5,
  21503. halfViewportHeight = viewportHeight * 0.5;
  21504. // setup gl
  21505. _gl.useProgram( _sprite.program );
  21506. _gl.enableVertexAttribArray( attributes.position );
  21507. _gl.enableVertexAttribArray( attributes.uv );
  21508. _gl.disable( _gl.CULL_FACE );
  21509. _gl.enable( _gl.BLEND );
  21510. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21511. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21512. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21513. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21514. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21515. _gl.activeTexture( _gl.TEXTURE0 );
  21516. _gl.uniform1i( uniforms.map, 0 );
  21517. var oldFogType = 0;
  21518. var sceneFogType = 0;
  21519. var fog = scene.fog;
  21520. if ( fog ) {
  21521. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21522. if ( fog instanceof THREE.Fog ) {
  21523. _gl.uniform1f( uniforms.fogNear, fog.near );
  21524. _gl.uniform1f( uniforms.fogFar, fog.far );
  21525. _gl.uniform1i( uniforms.fogType, 1 );
  21526. oldFogType = 1;
  21527. sceneFogType = 1;
  21528. } else if ( fog instanceof THREE.FogExp2 ) {
  21529. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21530. _gl.uniform1i( uniforms.fogType, 2 );
  21531. oldFogType = 2;
  21532. sceneFogType = 2;
  21533. }
  21534. } else {
  21535. _gl.uniform1i( uniforms.fogType, 0 );
  21536. oldFogType = 0;
  21537. sceneFogType = 0;
  21538. }
  21539. // update positions and sort
  21540. var i, sprite, material, fogType, scale = [];
  21541. for( i = 0; i < nSprites; i ++ ) {
  21542. sprite = sprites[ i ];
  21543. material = sprite.material;
  21544. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21545. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21546. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21547. }
  21548. sprites.sort( painterSortStable );
  21549. // render all sprites
  21550. for( i = 0; i < nSprites; i ++ ) {
  21551. sprite = sprites[ i ];
  21552. material = sprite.material;
  21553. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21554. if ( material.map && material.map.image && material.map.image.width ) {
  21555. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21556. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21557. scale[ 0 ] = sprite.scale.x;
  21558. scale[ 1 ] = sprite.scale.y;
  21559. if ( scene.fog && material.fog ) {
  21560. fogType = sceneFogType;
  21561. } else {
  21562. fogType = 0;
  21563. }
  21564. if ( oldFogType !== fogType ) {
  21565. _gl.uniform1i( uniforms.fogType, fogType );
  21566. oldFogType = fogType;
  21567. }
  21568. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21569. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21570. _gl.uniform1f( uniforms.opacity, material.opacity );
  21571. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21572. _gl.uniform1f( uniforms.rotation, material.rotation );
  21573. _gl.uniform2fv( uniforms.scale, scale );
  21574. _gl.uniform2f( uniforms.halfViewport, halfViewportWidth, halfViewportHeight );
  21575. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21576. _renderer.setDepthTest( material.depthTest );
  21577. _renderer.setDepthWrite( material.depthWrite );
  21578. _renderer.setTexture( material.map, 0 );
  21579. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21580. }
  21581. }
  21582. // restore gl
  21583. _gl.enable( _gl.CULL_FACE );
  21584. };
  21585. function createProgram ( shader, precision ) {
  21586. var program = _gl.createProgram();
  21587. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21588. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21589. var prefix = "precision " + precision + " float;\n";
  21590. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21591. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21592. _gl.compileShader( fragmentShader );
  21593. _gl.compileShader( vertexShader );
  21594. _gl.attachShader( program, fragmentShader );
  21595. _gl.attachShader( program, vertexShader );
  21596. _gl.linkProgram( program );
  21597. return program;
  21598. };
  21599. function painterSortStable ( a, b ) {
  21600. if ( a.z !== b.z ) {
  21601. return b.z - a.z;
  21602. } else {
  21603. return b.id - a.id;
  21604. }
  21605. };
  21606. };
  21607. /**
  21608. * @author alteredq / http://alteredqualia.com/
  21609. */
  21610. THREE.DepthPassPlugin = function () {
  21611. this.enabled = false;
  21612. this.renderTarget = null;
  21613. var _gl,
  21614. _renderer,
  21615. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21616. _frustum = new THREE.Frustum(),
  21617. _projScreenMatrix = new THREE.Matrix4();
  21618. this.init = function ( renderer ) {
  21619. _gl = renderer.context;
  21620. _renderer = renderer;
  21621. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21622. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21623. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21624. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21625. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21626. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21627. _depthMaterial._shadowPass = true;
  21628. _depthMaterialMorph._shadowPass = true;
  21629. _depthMaterialSkin._shadowPass = true;
  21630. _depthMaterialMorphSkin._shadowPass = true;
  21631. };
  21632. this.render = function ( scene, camera ) {
  21633. if ( ! this.enabled ) return;
  21634. this.update( scene, camera );
  21635. };
  21636. this.update = function ( scene, camera ) {
  21637. var i, il, j, jl, n,
  21638. program, buffer, material,
  21639. webglObject, object, light,
  21640. renderList,
  21641. fog = null;
  21642. // set GL state for depth map
  21643. _gl.clearColor( 1, 1, 1, 1 );
  21644. _gl.disable( _gl.BLEND );
  21645. _renderer.setDepthTest( true );
  21646. // update scene
  21647. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21648. // update camera matrices and frustum
  21649. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21650. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21651. _frustum.setFromMatrix( _projScreenMatrix );
  21652. // render depth map
  21653. _renderer.setRenderTarget( this.renderTarget );
  21654. _renderer.clear();
  21655. // set object matrices & frustum culling
  21656. renderList = scene.__webglObjects;
  21657. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21658. webglObject = renderList[ j ];
  21659. object = webglObject.object;
  21660. webglObject.render = false;
  21661. if ( object.visible ) {
  21662. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21663. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21664. webglObject.render = true;
  21665. }
  21666. }
  21667. }
  21668. // render regular objects
  21669. var objectMaterial, useMorphing, useSkinning;
  21670. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21671. webglObject = renderList[ j ];
  21672. if ( webglObject.render ) {
  21673. object = webglObject.object;
  21674. buffer = webglObject.buffer;
  21675. // todo: create proper depth material for particles
  21676. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21677. objectMaterial = getObjectMaterial( object );
  21678. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21679. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21680. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21681. if ( object.customDepthMaterial ) {
  21682. material = object.customDepthMaterial;
  21683. } else if ( useSkinning ) {
  21684. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21685. } else if ( useMorphing ) {
  21686. material = _depthMaterialMorph;
  21687. } else {
  21688. material = _depthMaterial;
  21689. }
  21690. if ( buffer instanceof THREE.BufferGeometry ) {
  21691. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21692. } else {
  21693. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21694. }
  21695. }
  21696. }
  21697. // set matrices and render immediate objects
  21698. renderList = scene.__webglObjectsImmediate;
  21699. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21700. webglObject = renderList[ j ];
  21701. object = webglObject.object;
  21702. if ( object.visible ) {
  21703. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21704. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21705. }
  21706. }
  21707. // restore GL state
  21708. var clearColor = _renderer.getClearColor(),
  21709. clearAlpha = _renderer.getClearAlpha();
  21710. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21711. _gl.enable( _gl.BLEND );
  21712. };
  21713. // For the moment just ignore objects that have multiple materials with different animation methods
  21714. // Only the first material will be taken into account for deciding which depth material to use
  21715. function getObjectMaterial( object ) {
  21716. return object.material instanceof THREE.MeshFaceMaterial
  21717. ? object.material.materials[ 0 ]
  21718. : object.material;
  21719. };
  21720. };
  21721. /**
  21722. * @author mikael emtinger / http://gomo.se/
  21723. */
  21724. THREE.ShaderFlares = {
  21725. 'lensFlareVertexTexture': {
  21726. vertexShader: [
  21727. "uniform lowp int renderType;",
  21728. "uniform vec3 screenPosition;",
  21729. "uniform vec2 scale;",
  21730. "uniform float rotation;",
  21731. "uniform sampler2D occlusionMap;",
  21732. "attribute vec2 position;",
  21733. "attribute vec2 uv;",
  21734. "varying vec2 vUV;",
  21735. "varying float vVisibility;",
  21736. "void main() {",
  21737. "vUV = uv;",
  21738. "vec2 pos = position;",
  21739. "if( renderType == 2 ) {",
  21740. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  21741. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  21742. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  21743. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  21744. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  21745. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  21746. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  21747. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  21748. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21749. "vVisibility = visibility.r / 9.0;",
  21750. "vVisibility *= 1.0 - visibility.g / 9.0;",
  21751. "vVisibility *= visibility.b / 9.0;",
  21752. "vVisibility *= 1.0 - visibility.a / 9.0;",
  21753. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21754. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21755. "}",
  21756. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21757. "}"
  21758. ].join( "\n" ),
  21759. fragmentShader: [
  21760. "uniform lowp int renderType;",
  21761. "uniform sampler2D map;",
  21762. "uniform float opacity;",
  21763. "uniform vec3 color;",
  21764. "varying vec2 vUV;",
  21765. "varying float vVisibility;",
  21766. "void main() {",
  21767. // pink square
  21768. "if( renderType == 0 ) {",
  21769. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21770. // restore
  21771. "} else if( renderType == 1 ) {",
  21772. "gl_FragColor = texture2D( map, vUV );",
  21773. // flare
  21774. "} else {",
  21775. "vec4 texture = texture2D( map, vUV );",
  21776. "texture.a *= opacity * vVisibility;",
  21777. "gl_FragColor = texture;",
  21778. "gl_FragColor.rgb *= color;",
  21779. "}",
  21780. "}"
  21781. ].join( "\n" )
  21782. },
  21783. 'lensFlare': {
  21784. vertexShader: [
  21785. "uniform lowp int renderType;",
  21786. "uniform vec3 screenPosition;",
  21787. "uniform vec2 scale;",
  21788. "uniform float rotation;",
  21789. "attribute vec2 position;",
  21790. "attribute vec2 uv;",
  21791. "varying vec2 vUV;",
  21792. "void main() {",
  21793. "vUV = uv;",
  21794. "vec2 pos = position;",
  21795. "if( renderType == 2 ) {",
  21796. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21797. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21798. "}",
  21799. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21800. "}"
  21801. ].join( "\n" ),
  21802. fragmentShader: [
  21803. "precision mediump float;",
  21804. "uniform lowp int renderType;",
  21805. "uniform sampler2D map;",
  21806. "uniform sampler2D occlusionMap;",
  21807. "uniform float opacity;",
  21808. "uniform vec3 color;",
  21809. "varying vec2 vUV;",
  21810. "void main() {",
  21811. // pink square
  21812. "if( renderType == 0 ) {",
  21813. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21814. // restore
  21815. "} else if( renderType == 1 ) {",
  21816. "gl_FragColor = texture2D( map, vUV );",
  21817. // flare
  21818. "} else {",
  21819. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  21820. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  21821. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  21822. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21823. "visibility = ( 1.0 - visibility / 4.0 );",
  21824. "vec4 texture = texture2D( map, vUV );",
  21825. "texture.a *= opacity * visibility;",
  21826. "gl_FragColor = texture;",
  21827. "gl_FragColor.rgb *= color;",
  21828. "}",
  21829. "}"
  21830. ].join( "\n" )
  21831. }
  21832. };
  21833. /**
  21834. * @author mikael emtinger / http://gomo.se/
  21835. * @author alteredq / http://alteredqualia.com/
  21836. *
  21837. */
  21838. THREE.ShaderSprite = {
  21839. 'sprite': {
  21840. vertexShader: [
  21841. "uniform mat4 modelViewMatrix;",
  21842. "uniform mat4 projectionMatrix;",
  21843. "uniform float rotation;",
  21844. "uniform vec2 scale;",
  21845. "uniform vec2 uvOffset;",
  21846. "uniform vec2 uvScale;",
  21847. "uniform vec2 halfViewport;",
  21848. "attribute vec2 position;",
  21849. "attribute vec2 uv;",
  21850. "varying vec2 vUV;",
  21851. "void main() {",
  21852. "vUV = uvOffset + uv * uvScale;",
  21853. "vec2 alignedPosition = position * scale;",
  21854. "vec2 rotatedPosition;",
  21855. "rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;",
  21856. "rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;",
  21857. "vec4 finalPosition;",
  21858. "finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21859. "finalPosition.xy += rotatedPosition;",
  21860. "finalPosition = projectionMatrix * finalPosition;",
  21861. "gl_Position = finalPosition;",
  21862. "}"
  21863. ].join( "\n" ),
  21864. fragmentShader: [
  21865. "uniform vec3 color;",
  21866. "uniform sampler2D map;",
  21867. "uniform float opacity;",
  21868. "uniform int fogType;",
  21869. "uniform vec3 fogColor;",
  21870. "uniform float fogDensity;",
  21871. "uniform float fogNear;",
  21872. "uniform float fogFar;",
  21873. "uniform float alphaTest;",
  21874. "varying vec2 vUV;",
  21875. "void main() {",
  21876. "vec4 texture = texture2D( map, vUV );",
  21877. "if ( texture.a < alphaTest ) discard;",
  21878. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21879. "if ( fogType > 0 ) {",
  21880. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21881. "float fogFactor = 0.0;",
  21882. "if ( fogType == 1 ) {",
  21883. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21884. "} else {",
  21885. "const float LOG2 = 1.442695;",
  21886. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21887. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21888. "}",
  21889. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21890. "}",
  21891. "}"
  21892. ].join( "\n" )
  21893. }
  21894. };