three.js 796 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076
  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: '64' };
  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 ( optionalTarget ) {
  295. // h,s,l ranges are in 0.0 - 1.0
  296. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  297. var r = this.r, g = this.g, b = this.b;
  298. var max = Math.max( r, g, b );
  299. var min = Math.min( r, g, b );
  300. var hue, saturation;
  301. var lightness = ( min + max ) / 2.0;
  302. if ( min === max ) {
  303. hue = 0;
  304. saturation = 0;
  305. } else {
  306. var delta = max - min;
  307. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  308. switch ( max ) {
  309. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  310. case g: hue = ( b - r ) / delta + 2; break;
  311. case b: hue = ( r - g ) / delta + 4; break;
  312. }
  313. hue /= 6;
  314. }
  315. hsl.h = hue;
  316. hsl.s = saturation;
  317. hsl.l = lightness;
  318. return hsl;
  319. },
  320. getStyle: function () {
  321. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  322. },
  323. offsetHSL: function ( h, s, l ) {
  324. var hsl = this.getHSL();
  325. hsl.h += h; hsl.s += s; hsl.l += l;
  326. this.setHSL( hsl.h, hsl.s, hsl.l );
  327. return this;
  328. },
  329. add: function ( color ) {
  330. this.r += color.r;
  331. this.g += color.g;
  332. this.b += color.b;
  333. return this;
  334. },
  335. addColors: function ( color1, color2 ) {
  336. this.r = color1.r + color2.r;
  337. this.g = color1.g + color2.g;
  338. this.b = color1.b + color2.b;
  339. return this;
  340. },
  341. addScalar: function ( s ) {
  342. this.r += s;
  343. this.g += s;
  344. this.b += s;
  345. return this;
  346. },
  347. multiply: function ( color ) {
  348. this.r *= color.r;
  349. this.g *= color.g;
  350. this.b *= color.b;
  351. return this;
  352. },
  353. multiplyScalar: function ( s ) {
  354. this.r *= s;
  355. this.g *= s;
  356. this.b *= s;
  357. return this;
  358. },
  359. lerp: function ( color, alpha ) {
  360. this.r += ( color.r - this.r ) * alpha;
  361. this.g += ( color.g - this.g ) * alpha;
  362. this.b += ( color.b - this.b ) * alpha;
  363. return this;
  364. },
  365. equals: function ( c ) {
  366. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  367. },
  368. fromArray: function ( array ) {
  369. this.r = array[ 0 ];
  370. this.g = array[ 1 ];
  371. this.b = array[ 2 ];
  372. return this;
  373. },
  374. toArray: function () {
  375. return [ this.r, this.g, this.b ];
  376. },
  377. clone: function () {
  378. return new THREE.Color().setRGB( this.r, this.g, this.b );
  379. }
  380. };
  381. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  382. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  383. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  384. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  385. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  386. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  387. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  388. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  389. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  390. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  391. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  392. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  393. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  394. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  395. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  396. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  397. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  398. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  399. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  400. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  401. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  402. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  403. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  404. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  405. /**
  406. * @author mikael emtinger / http://gomo.se/
  407. * @author alteredq / http://alteredqualia.com/
  408. * @author WestLangley / http://github.com/WestLangley
  409. * @author bhouston / http://exocortex.com
  410. */
  411. THREE.Quaternion = function ( x, y, z, w ) {
  412. this._x = x || 0;
  413. this._y = y || 0;
  414. this._z = z || 0;
  415. this._w = ( w !== undefined ) ? w : 1;
  416. };
  417. THREE.Quaternion.prototype = {
  418. constructor: THREE.Quaternion,
  419. _x: 0,_y: 0, _z: 0, _w: 0,
  420. _euler: undefined,
  421. _updateEuler: function ( callback ) {
  422. if ( this._euler !== undefined ) {
  423. this._euler.setFromQuaternion( this, undefined, false );
  424. }
  425. },
  426. get x () {
  427. return this._x;
  428. },
  429. set x ( value ) {
  430. this._x = value;
  431. this._updateEuler();
  432. },
  433. get y () {
  434. return this._y;
  435. },
  436. set y ( value ) {
  437. this._y = value;
  438. this._updateEuler();
  439. },
  440. get z () {
  441. return this._z;
  442. },
  443. set z ( value ) {
  444. this._z = value;
  445. this._updateEuler();
  446. },
  447. get w () {
  448. return this._w;
  449. },
  450. set w ( value ) {
  451. this._w = value;
  452. this._updateEuler();
  453. },
  454. set: function ( x, y, z, w ) {
  455. this._x = x;
  456. this._y = y;
  457. this._z = z;
  458. this._w = w;
  459. this._updateEuler();
  460. return this;
  461. },
  462. copy: function ( quaternion ) {
  463. this._x = quaternion._x;
  464. this._y = quaternion._y;
  465. this._z = quaternion._z;
  466. this._w = quaternion._w;
  467. this._updateEuler();
  468. return this;
  469. },
  470. setFromEuler: function ( euler, update ) {
  471. if ( euler instanceof THREE.Euler === false ) {
  472. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  473. }
  474. // http://www.mathworks.com/matlabcentral/fileexchange/
  475. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  476. // content/SpinCalc.m
  477. var c1 = Math.cos( euler._x / 2 );
  478. var c2 = Math.cos( euler._y / 2 );
  479. var c3 = Math.cos( euler._z / 2 );
  480. var s1 = Math.sin( euler._x / 2 );
  481. var s2 = Math.sin( euler._y / 2 );
  482. var s3 = Math.sin( euler._z / 2 );
  483. if ( euler.order === 'XYZ' ) {
  484. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  485. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  486. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  487. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  488. } else if ( euler.order === 'YXZ' ) {
  489. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  490. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  491. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  492. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  493. } else if ( euler.order === 'ZXY' ) {
  494. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  495. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  496. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  497. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  498. } else if ( euler.order === 'ZYX' ) {
  499. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  500. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  501. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  502. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  503. } else if ( euler.order === 'YZX' ) {
  504. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  505. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  506. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  507. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  508. } else if ( euler.order === 'XZY' ) {
  509. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  510. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  511. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  512. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  513. }
  514. if ( update !== false ) this._updateEuler();
  515. return this;
  516. },
  517. setFromAxisAngle: function ( axis, angle ) {
  518. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  519. // axis have to be normalized
  520. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  521. this._x = axis.x * s;
  522. this._y = axis.y * s;
  523. this._z = axis.z * s;
  524. this._w = Math.cos( halfAngle );
  525. this._updateEuler();
  526. return this;
  527. },
  528. setFromRotationMatrix: function ( m ) {
  529. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  530. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  531. var te = m.elements,
  532. m11 = te[0], m12 = te[4], m13 = te[8],
  533. m21 = te[1], m22 = te[5], m23 = te[9],
  534. m31 = te[2], m32 = te[6], m33 = te[10],
  535. trace = m11 + m22 + m33,
  536. s;
  537. if ( trace > 0 ) {
  538. s = 0.5 / Math.sqrt( trace + 1.0 );
  539. this._w = 0.25 / s;
  540. this._x = ( m32 - m23 ) * s;
  541. this._y = ( m13 - m31 ) * s;
  542. this._z = ( m21 - m12 ) * s;
  543. } else if ( m11 > m22 && m11 > m33 ) {
  544. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  545. this._w = (m32 - m23 ) / s;
  546. this._x = 0.25 * s;
  547. this._y = (m12 + m21 ) / s;
  548. this._z = (m13 + m31 ) / s;
  549. } else if ( m22 > m33 ) {
  550. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  551. this._w = (m13 - m31 ) / s;
  552. this._x = (m12 + m21 ) / s;
  553. this._y = 0.25 * s;
  554. this._z = (m23 + m32 ) / s;
  555. } else {
  556. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  557. this._w = ( m21 - m12 ) / s;
  558. this._x = ( m13 + m31 ) / s;
  559. this._y = ( m23 + m32 ) / s;
  560. this._z = 0.25 * s;
  561. }
  562. this._updateEuler();
  563. return this;
  564. },
  565. inverse: function () {
  566. this.conjugate().normalize();
  567. return this;
  568. },
  569. conjugate: function () {
  570. this._x *= -1;
  571. this._y *= -1;
  572. this._z *= -1;
  573. this._updateEuler();
  574. return this;
  575. },
  576. lengthSq: function () {
  577. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  578. },
  579. length: function () {
  580. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  581. },
  582. normalize: function () {
  583. var l = this.length();
  584. if ( l === 0 ) {
  585. this._x = 0;
  586. this._y = 0;
  587. this._z = 0;
  588. this._w = 1;
  589. } else {
  590. l = 1 / l;
  591. this._x = this._x * l;
  592. this._y = this._y * l;
  593. this._z = this._z * l;
  594. this._w = this._w * l;
  595. }
  596. return this;
  597. },
  598. multiply: function ( q, p ) {
  599. if ( p !== undefined ) {
  600. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  601. return this.multiplyQuaternions( q, p );
  602. }
  603. return this.multiplyQuaternions( this, q );
  604. },
  605. multiplyQuaternions: function ( a, b ) {
  606. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  607. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  608. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  609. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  610. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  611. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  612. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  613. this._updateEuler();
  614. return this;
  615. },
  616. multiplyVector3: function ( vector ) {
  617. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  618. return vector.applyQuaternion( this );
  619. },
  620. slerp: function ( qb, t ) {
  621. var x = this._x, y = this._y, z = this._z, w = this._w;
  622. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  623. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  624. if ( cosHalfTheta < 0 ) {
  625. this._w = -qb._w;
  626. this._x = -qb._x;
  627. this._y = -qb._y;
  628. this._z = -qb._z;
  629. cosHalfTheta = -cosHalfTheta;
  630. } else {
  631. this.copy( qb );
  632. }
  633. if ( cosHalfTheta >= 1.0 ) {
  634. this._w = w;
  635. this._x = x;
  636. this._y = y;
  637. this._z = z;
  638. return this;
  639. }
  640. var halfTheta = Math.acos( cosHalfTheta );
  641. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  642. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  643. this._w = 0.5 * ( w + this._w );
  644. this._x = 0.5 * ( x + this._x );
  645. this._y = 0.5 * ( y + this._y );
  646. this._z = 0.5 * ( z + this._z );
  647. return this;
  648. }
  649. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  650. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  651. this._w = ( w * ratioA + this._w * ratioB );
  652. this._x = ( x * ratioA + this._x * ratioB );
  653. this._y = ( y * ratioA + this._y * ratioB );
  654. this._z = ( z * ratioA + this._z * ratioB );
  655. this._updateEuler();
  656. return this;
  657. },
  658. equals: function ( quaternion ) {
  659. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  660. },
  661. fromArray: function ( array ) {
  662. this._x = array[ 0 ];
  663. this._y = array[ 1 ];
  664. this._z = array[ 2 ];
  665. this._w = array[ 3 ];
  666. this._updateEuler();
  667. return this;
  668. },
  669. toArray: function () {
  670. return [ this._x, this._y, this._z, this._w ];
  671. },
  672. clone: function () {
  673. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  674. }
  675. };
  676. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  677. return qm.copy( qa ).slerp( qb, t );
  678. }
  679. /**
  680. * @author mrdoob / http://mrdoob.com/
  681. * @author philogb / http://blog.thejit.org/
  682. * @author egraether / http://egraether.com/
  683. * @author zz85 / http://www.lab4games.net/zz85/blog
  684. */
  685. THREE.Vector2 = function ( x, y ) {
  686. this.x = x || 0;
  687. this.y = y || 0;
  688. };
  689. THREE.Vector2.prototype = {
  690. constructor: THREE.Vector2,
  691. set: function ( x, y ) {
  692. this.x = x;
  693. this.y = y;
  694. return this;
  695. },
  696. setX: function ( x ) {
  697. this.x = x;
  698. return this;
  699. },
  700. setY: function ( y ) {
  701. this.y = y;
  702. return this;
  703. },
  704. setComponent: function ( index, value ) {
  705. switch ( index ) {
  706. case 0: this.x = value; break;
  707. case 1: this.y = value; break;
  708. default: throw new Error( "index is out of range: " + index );
  709. }
  710. },
  711. getComponent: function ( index ) {
  712. switch ( index ) {
  713. case 0: return this.x;
  714. case 1: return this.y;
  715. default: throw new Error( "index is out of range: " + index );
  716. }
  717. },
  718. copy: function ( v ) {
  719. this.x = v.x;
  720. this.y = v.y;
  721. return this;
  722. },
  723. add: function ( v, w ) {
  724. if ( w !== undefined ) {
  725. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  726. return this.addVectors( v, w );
  727. }
  728. this.x += v.x;
  729. this.y += v.y;
  730. return this;
  731. },
  732. addVectors: function ( a, b ) {
  733. this.x = a.x + b.x;
  734. this.y = a.y + b.y;
  735. return this;
  736. },
  737. addScalar: function ( s ) {
  738. this.x += s;
  739. this.y += s;
  740. return this;
  741. },
  742. sub: function ( v, w ) {
  743. if ( w !== undefined ) {
  744. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  745. return this.subVectors( v, w );
  746. }
  747. this.x -= v.x;
  748. this.y -= v.y;
  749. return this;
  750. },
  751. subVectors: function ( a, b ) {
  752. this.x = a.x - b.x;
  753. this.y = a.y - b.y;
  754. return this;
  755. },
  756. multiplyScalar: function ( s ) {
  757. this.x *= s;
  758. this.y *= s;
  759. return this;
  760. },
  761. divideScalar: function ( scalar ) {
  762. if ( scalar !== 0 ) {
  763. var invScalar = 1 / scalar;
  764. this.x *= invScalar;
  765. this.y *= invScalar;
  766. } else {
  767. this.x = 0;
  768. this.y = 0;
  769. }
  770. return this;
  771. },
  772. min: function ( v ) {
  773. if ( this.x > v.x ) {
  774. this.x = v.x;
  775. }
  776. if ( this.y > v.y ) {
  777. this.y = v.y;
  778. }
  779. return this;
  780. },
  781. max: function ( v ) {
  782. if ( this.x < v.x ) {
  783. this.x = v.x;
  784. }
  785. if ( this.y < v.y ) {
  786. this.y = v.y;
  787. }
  788. return this;
  789. },
  790. clamp: function ( min, max ) {
  791. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  792. if ( this.x < min.x ) {
  793. this.x = min.x;
  794. } else if ( this.x > max.x ) {
  795. this.x = max.x;
  796. }
  797. if ( this.y < min.y ) {
  798. this.y = min.y;
  799. } else if ( this.y > max.y ) {
  800. this.y = max.y;
  801. }
  802. return this;
  803. },
  804. negate: function() {
  805. return this.multiplyScalar( - 1 );
  806. },
  807. dot: function ( v ) {
  808. return this.x * v.x + this.y * v.y;
  809. },
  810. lengthSq: function () {
  811. return this.x * this.x + this.y * this.y;
  812. },
  813. length: function () {
  814. return Math.sqrt( this.x * this.x + this.y * this.y );
  815. },
  816. normalize: function () {
  817. return this.divideScalar( this.length() );
  818. },
  819. distanceTo: function ( v ) {
  820. return Math.sqrt( this.distanceToSquared( v ) );
  821. },
  822. distanceToSquared: function ( v ) {
  823. var dx = this.x - v.x, dy = this.y - v.y;
  824. return dx * dx + dy * dy;
  825. },
  826. setLength: function ( l ) {
  827. var oldLength = this.length();
  828. if ( oldLength !== 0 && l !== oldLength ) {
  829. this.multiplyScalar( l / oldLength );
  830. }
  831. return this;
  832. },
  833. lerp: function ( v, alpha ) {
  834. this.x += ( v.x - this.x ) * alpha;
  835. this.y += ( v.y - this.y ) * alpha;
  836. return this;
  837. },
  838. equals: function( v ) {
  839. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  840. },
  841. fromArray: function ( array ) {
  842. this.x = array[ 0 ];
  843. this.y = array[ 1 ];
  844. return this;
  845. },
  846. toArray: function () {
  847. return [ this.x, this.y ];
  848. },
  849. clone: function () {
  850. return new THREE.Vector2( this.x, this.y );
  851. }
  852. };
  853. /**
  854. * @author mrdoob / http://mrdoob.com/
  855. * @author *kile / http://kile.stravaganza.org/
  856. * @author philogb / http://blog.thejit.org/
  857. * @author mikael emtinger / http://gomo.se/
  858. * @author egraether / http://egraether.com/
  859. * @author WestLangley / http://github.com/WestLangley
  860. */
  861. THREE.Vector3 = function ( x, y, z ) {
  862. this.x = x || 0;
  863. this.y = y || 0;
  864. this.z = z || 0;
  865. };
  866. THREE.Vector3.prototype = {
  867. constructor: THREE.Vector3,
  868. set: function ( x, y, z ) {
  869. this.x = x;
  870. this.y = y;
  871. this.z = z;
  872. return this;
  873. },
  874. setX: function ( x ) {
  875. this.x = x;
  876. return this;
  877. },
  878. setY: function ( y ) {
  879. this.y = y;
  880. return this;
  881. },
  882. setZ: function ( z ) {
  883. this.z = z;
  884. return this;
  885. },
  886. setComponent: function ( index, value ) {
  887. switch ( index ) {
  888. case 0: this.x = value; break;
  889. case 1: this.y = value; break;
  890. case 2: this.z = value; break;
  891. default: throw new Error( "index is out of range: " + index );
  892. }
  893. },
  894. getComponent: function ( index ) {
  895. switch ( index ) {
  896. case 0: return this.x;
  897. case 1: return this.y;
  898. case 2: return this.z;
  899. default: throw new Error( "index is out of range: " + index );
  900. }
  901. },
  902. copy: function ( v ) {
  903. this.x = v.x;
  904. this.y = v.y;
  905. this.z = v.z;
  906. return this;
  907. },
  908. add: function ( v, w ) {
  909. if ( w !== undefined ) {
  910. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  911. return this.addVectors( v, w );
  912. }
  913. this.x += v.x;
  914. this.y += v.y;
  915. this.z += v.z;
  916. return this;
  917. },
  918. addScalar: function ( s ) {
  919. this.x += s;
  920. this.y += s;
  921. this.z += s;
  922. return this;
  923. },
  924. addVectors: function ( a, b ) {
  925. this.x = a.x + b.x;
  926. this.y = a.y + b.y;
  927. this.z = a.z + b.z;
  928. return this;
  929. },
  930. sub: function ( v, w ) {
  931. if ( w !== undefined ) {
  932. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  933. return this.subVectors( v, w );
  934. }
  935. this.x -= v.x;
  936. this.y -= v.y;
  937. this.z -= v.z;
  938. return this;
  939. },
  940. subVectors: function ( a, b ) {
  941. this.x = a.x - b.x;
  942. this.y = a.y - b.y;
  943. this.z = a.z - b.z;
  944. return this;
  945. },
  946. multiply: function ( v, w ) {
  947. if ( w !== undefined ) {
  948. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  949. return this.multiplyVectors( v, w );
  950. }
  951. this.x *= v.x;
  952. this.y *= v.y;
  953. this.z *= v.z;
  954. return this;
  955. },
  956. multiplyScalar: function ( scalar ) {
  957. this.x *= scalar;
  958. this.y *= scalar;
  959. this.z *= scalar;
  960. return this;
  961. },
  962. multiplyVectors: function ( a, b ) {
  963. this.x = a.x * b.x;
  964. this.y = a.y * b.y;
  965. this.z = a.z * b.z;
  966. return this;
  967. },
  968. applyMatrix3: function ( m ) {
  969. var x = this.x;
  970. var y = this.y;
  971. var z = this.z;
  972. var e = m.elements;
  973. this.x = e[0] * x + e[3] * y + e[6] * z;
  974. this.y = e[1] * x + e[4] * y + e[7] * z;
  975. this.z = e[2] * x + e[5] * y + e[8] * z;
  976. return this;
  977. },
  978. applyMatrix4: function ( m ) {
  979. // input: THREE.Matrix4 affine matrix
  980. var x = this.x, y = this.y, z = this.z;
  981. var e = m.elements;
  982. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  983. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  984. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  985. return this;
  986. },
  987. applyProjection: function ( m ) {
  988. // input: THREE.Matrix4 projection matrix
  989. var x = this.x, y = this.y, z = this.z;
  990. var e = m.elements;
  991. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  992. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  993. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  994. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  995. return this;
  996. },
  997. applyQuaternion: function ( q ) {
  998. var x = this.x;
  999. var y = this.y;
  1000. var z = this.z;
  1001. var qx = q.x;
  1002. var qy = q.y;
  1003. var qz = q.z;
  1004. var qw = q.w;
  1005. // calculate quat * vector
  1006. var ix = qw * x + qy * z - qz * y;
  1007. var iy = qw * y + qz * x - qx * z;
  1008. var iz = qw * z + qx * y - qy * x;
  1009. var iw = -qx * x - qy * y - qz * z;
  1010. // calculate result * inverse quat
  1011. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1012. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1013. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1014. return this;
  1015. },
  1016. transformDirection: function ( m ) {
  1017. // input: THREE.Matrix4 affine matrix
  1018. // vector interpreted as a direction
  1019. var x = this.x, y = this.y, z = this.z;
  1020. var e = m.elements;
  1021. this.x = e[0] * x + e[4] * y + e[8] * z;
  1022. this.y = e[1] * x + e[5] * y + e[9] * z;
  1023. this.z = e[2] * x + e[6] * y + e[10] * z;
  1024. this.normalize();
  1025. return this;
  1026. },
  1027. divide: function ( v ) {
  1028. this.x /= v.x;
  1029. this.y /= v.y;
  1030. this.z /= v.z;
  1031. return this;
  1032. },
  1033. divideScalar: function ( scalar ) {
  1034. if ( scalar !== 0 ) {
  1035. var invScalar = 1 / scalar;
  1036. this.x *= invScalar;
  1037. this.y *= invScalar;
  1038. this.z *= invScalar;
  1039. } else {
  1040. this.x = 0;
  1041. this.y = 0;
  1042. this.z = 0;
  1043. }
  1044. return this;
  1045. },
  1046. min: function ( v ) {
  1047. if ( this.x > v.x ) {
  1048. this.x = v.x;
  1049. }
  1050. if ( this.y > v.y ) {
  1051. this.y = v.y;
  1052. }
  1053. if ( this.z > v.z ) {
  1054. this.z = v.z;
  1055. }
  1056. return this;
  1057. },
  1058. max: function ( v ) {
  1059. if ( this.x < v.x ) {
  1060. this.x = v.x;
  1061. }
  1062. if ( this.y < v.y ) {
  1063. this.y = v.y;
  1064. }
  1065. if ( this.z < v.z ) {
  1066. this.z = v.z;
  1067. }
  1068. return this;
  1069. },
  1070. clamp: function ( min, max ) {
  1071. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1072. if ( this.x < min.x ) {
  1073. this.x = min.x;
  1074. } else if ( this.x > max.x ) {
  1075. this.x = max.x;
  1076. }
  1077. if ( this.y < min.y ) {
  1078. this.y = min.y;
  1079. } else if ( this.y > max.y ) {
  1080. this.y = max.y;
  1081. }
  1082. if ( this.z < min.z ) {
  1083. this.z = min.z;
  1084. } else if ( this.z > max.z ) {
  1085. this.z = max.z;
  1086. }
  1087. return this;
  1088. },
  1089. negate: function () {
  1090. return this.multiplyScalar( - 1 );
  1091. },
  1092. dot: function ( v ) {
  1093. return this.x * v.x + this.y * v.y + this.z * v.z;
  1094. },
  1095. lengthSq: function () {
  1096. return this.x * this.x + this.y * this.y + this.z * this.z;
  1097. },
  1098. length: function () {
  1099. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1100. },
  1101. lengthManhattan: function () {
  1102. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1103. },
  1104. normalize: function () {
  1105. return this.divideScalar( this.length() );
  1106. },
  1107. setLength: function ( l ) {
  1108. var oldLength = this.length();
  1109. if ( oldLength !== 0 && l !== oldLength ) {
  1110. this.multiplyScalar( l / oldLength );
  1111. }
  1112. return this;
  1113. },
  1114. lerp: function ( v, alpha ) {
  1115. this.x += ( v.x - this.x ) * alpha;
  1116. this.y += ( v.y - this.y ) * alpha;
  1117. this.z += ( v.z - this.z ) * alpha;
  1118. return this;
  1119. },
  1120. cross: function ( v, w ) {
  1121. if ( w !== undefined ) {
  1122. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1123. return this.crossVectors( v, w );
  1124. }
  1125. var x = this.x, y = this.y, z = this.z;
  1126. this.x = y * v.z - z * v.y;
  1127. this.y = z * v.x - x * v.z;
  1128. this.z = x * v.y - y * v.x;
  1129. return this;
  1130. },
  1131. crossVectors: function ( a, b ) {
  1132. var ax = a.x, ay = a.y, az = a.z;
  1133. var bx = b.x, by = b.y, bz = b.z;
  1134. this.x = ay * bz - az * by;
  1135. this.y = az * bx - ax * bz;
  1136. this.z = ax * by - ay * bx;
  1137. return this;
  1138. },
  1139. angleTo: function ( v ) {
  1140. var theta = this.dot( v ) / ( this.length() * v.length() );
  1141. // clamp, to handle numerical problems
  1142. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1143. },
  1144. distanceTo: function ( v ) {
  1145. return Math.sqrt( this.distanceToSquared( v ) );
  1146. },
  1147. distanceToSquared: function ( v ) {
  1148. var dx = this.x - v.x;
  1149. var dy = this.y - v.y;
  1150. var dz = this.z - v.z;
  1151. return dx * dx + dy * dy + dz * dz;
  1152. },
  1153. setEulerFromRotationMatrix: function ( m, order ) {
  1154. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1155. },
  1156. setEulerFromQuaternion: function ( q, order ) {
  1157. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1158. },
  1159. getPositionFromMatrix: function ( m ) {
  1160. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1161. return this.setFromMatrixPosition( m );
  1162. },
  1163. getScaleFromMatrix: function ( m ) {
  1164. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1165. return this.setFromMatrixScale( m );
  1166. },
  1167. getColumnFromMatrix: function ( index, matrix ) {
  1168. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1169. return this.setFromMatrixColumn( index, matrix );
  1170. },
  1171. setFromMatrixPosition: function ( m ) {
  1172. this.x = m.elements[ 12 ];
  1173. this.y = m.elements[ 13 ];
  1174. this.z = m.elements[ 14 ];
  1175. return this;
  1176. },
  1177. setFromMatrixScale: function ( m ) {
  1178. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1179. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1180. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1181. this.x = sx;
  1182. this.y = sy;
  1183. this.z = sz;
  1184. return this;
  1185. },
  1186. setFromMatrixColumn: function ( index, matrix ) {
  1187. var offset = index * 4;
  1188. var me = matrix.elements;
  1189. this.x = me[ offset ];
  1190. this.y = me[ offset + 1 ];
  1191. this.z = me[ offset + 2 ];
  1192. return this;
  1193. },
  1194. equals: function ( v ) {
  1195. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1196. },
  1197. fromArray: function ( array ) {
  1198. this.x = array[ 0 ];
  1199. this.y = array[ 1 ];
  1200. this.z = array[ 2 ];
  1201. return this;
  1202. },
  1203. toArray: function () {
  1204. return [ this.x, this.y, this.z ];
  1205. },
  1206. clone: function () {
  1207. return new THREE.Vector3( this.x, this.y, this.z );
  1208. }
  1209. };
  1210. THREE.extend( THREE.Vector3.prototype, {
  1211. applyEuler: function () {
  1212. var quaternion = new THREE.Quaternion();
  1213. return function ( euler ) {
  1214. if ( euler instanceof THREE.Euler === false ) {
  1215. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1216. }
  1217. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1218. return this;
  1219. };
  1220. }(),
  1221. applyAxisAngle: function () {
  1222. var quaternion = new THREE.Quaternion();
  1223. return function ( axis, angle ) {
  1224. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1225. return this;
  1226. };
  1227. }(),
  1228. projectOnVector: function () {
  1229. var v1 = new THREE.Vector3();
  1230. return function ( vector ) {
  1231. v1.copy( vector ).normalize();
  1232. var d = this.dot( v1 );
  1233. return this.copy( v1 ).multiplyScalar( d );
  1234. };
  1235. }(),
  1236. projectOnPlane: function () {
  1237. var v1 = new THREE.Vector3();
  1238. return function ( planeNormal ) {
  1239. v1.copy( this ).projectOnVector( planeNormal );
  1240. return this.sub( v1 );
  1241. }
  1242. }(),
  1243. reflect: function () {
  1244. var v1 = new THREE.Vector3();
  1245. return function ( vector ) {
  1246. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1247. return this.subVectors( v1, this );
  1248. }
  1249. }()
  1250. } );
  1251. /**
  1252. * @author supereggbert / http://www.paulbrunt.co.uk/
  1253. * @author philogb / http://blog.thejit.org/
  1254. * @author mikael emtinger / http://gomo.se/
  1255. * @author egraether / http://egraether.com/
  1256. * @author WestLangley / http://github.com/WestLangley
  1257. */
  1258. THREE.Vector4 = function ( x, y, z, w ) {
  1259. this.x = x || 0;
  1260. this.y = y || 0;
  1261. this.z = z || 0;
  1262. this.w = ( w !== undefined ) ? w : 1;
  1263. };
  1264. THREE.Vector4.prototype = {
  1265. constructor: THREE.Vector4,
  1266. set: function ( x, y, z, w ) {
  1267. this.x = x;
  1268. this.y = y;
  1269. this.z = z;
  1270. this.w = w;
  1271. return this;
  1272. },
  1273. setX: function ( x ) {
  1274. this.x = x;
  1275. return this;
  1276. },
  1277. setY: function ( y ) {
  1278. this.y = y;
  1279. return this;
  1280. },
  1281. setZ: function ( z ) {
  1282. this.z = z;
  1283. return this;
  1284. },
  1285. setW: function ( w ) {
  1286. this.w = w;
  1287. return this;
  1288. },
  1289. setComponent: function ( index, value ) {
  1290. switch ( index ) {
  1291. case 0: this.x = value; break;
  1292. case 1: this.y = value; break;
  1293. case 2: this.z = value; break;
  1294. case 3: this.w = value; break;
  1295. default: throw new Error( "index is out of range: " + index );
  1296. }
  1297. },
  1298. getComponent: function ( index ) {
  1299. switch ( index ) {
  1300. case 0: return this.x;
  1301. case 1: return this.y;
  1302. case 2: return this.z;
  1303. case 3: return this.w;
  1304. default: throw new Error( "index is out of range: " + index );
  1305. }
  1306. },
  1307. copy: function ( v ) {
  1308. this.x = v.x;
  1309. this.y = v.y;
  1310. this.z = v.z;
  1311. this.w = ( v.w !== undefined ) ? v.w : 1;
  1312. return this;
  1313. },
  1314. add: function ( v, w ) {
  1315. if ( w !== undefined ) {
  1316. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1317. return this.addVectors( v, w );
  1318. }
  1319. this.x += v.x;
  1320. this.y += v.y;
  1321. this.z += v.z;
  1322. this.w += v.w;
  1323. return this;
  1324. },
  1325. addScalar: function ( s ) {
  1326. this.x += s;
  1327. this.y += s;
  1328. this.z += s;
  1329. this.w += s;
  1330. return this;
  1331. },
  1332. addVectors: function ( a, b ) {
  1333. this.x = a.x + b.x;
  1334. this.y = a.y + b.y;
  1335. this.z = a.z + b.z;
  1336. this.w = a.w + b.w;
  1337. return this;
  1338. },
  1339. sub: function ( v, w ) {
  1340. if ( w !== undefined ) {
  1341. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1342. return this.subVectors( v, w );
  1343. }
  1344. this.x -= v.x;
  1345. this.y -= v.y;
  1346. this.z -= v.z;
  1347. this.w -= v.w;
  1348. return this;
  1349. },
  1350. subVectors: function ( a, b ) {
  1351. this.x = a.x - b.x;
  1352. this.y = a.y - b.y;
  1353. this.z = a.z - b.z;
  1354. this.w = a.w - b.w;
  1355. return this;
  1356. },
  1357. multiplyScalar: function ( scalar ) {
  1358. this.x *= scalar;
  1359. this.y *= scalar;
  1360. this.z *= scalar;
  1361. this.w *= scalar;
  1362. return this;
  1363. },
  1364. applyMatrix4: function ( m ) {
  1365. var x = this.x;
  1366. var y = this.y;
  1367. var z = this.z;
  1368. var w = this.w;
  1369. var e = m.elements;
  1370. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1371. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1372. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1373. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1374. return this;
  1375. },
  1376. divideScalar: function ( scalar ) {
  1377. if ( scalar !== 0 ) {
  1378. var invScalar = 1 / scalar;
  1379. this.x *= invScalar;
  1380. this.y *= invScalar;
  1381. this.z *= invScalar;
  1382. this.w *= invScalar;
  1383. } else {
  1384. this.x = 0;
  1385. this.y = 0;
  1386. this.z = 0;
  1387. this.w = 1;
  1388. }
  1389. return this;
  1390. },
  1391. setAxisAngleFromQuaternion: function ( q ) {
  1392. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1393. // q is assumed to be normalized
  1394. this.w = 2 * Math.acos( q.w );
  1395. var s = Math.sqrt( 1 - q.w * q.w );
  1396. if ( s < 0.0001 ) {
  1397. this.x = 1;
  1398. this.y = 0;
  1399. this.z = 0;
  1400. } else {
  1401. this.x = q.x / s;
  1402. this.y = q.y / s;
  1403. this.z = q.z / s;
  1404. }
  1405. return this;
  1406. },
  1407. setAxisAngleFromRotationMatrix: function ( m ) {
  1408. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1409. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1410. var angle, x, y, z, // variables for result
  1411. epsilon = 0.01, // margin to allow for rounding errors
  1412. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1413. te = m.elements,
  1414. m11 = te[0], m12 = te[4], m13 = te[8],
  1415. m21 = te[1], m22 = te[5], m23 = te[9],
  1416. m31 = te[2], m32 = te[6], m33 = te[10];
  1417. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1418. && ( Math.abs( m13 - m31 ) < epsilon )
  1419. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1420. // singularity found
  1421. // first check for identity matrix which must have +1 for all terms
  1422. // in leading diagonal and zero in other terms
  1423. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1424. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1425. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1426. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1427. // this singularity is identity matrix so angle = 0
  1428. this.set( 1, 0, 0, 0 );
  1429. return this; // zero angle, arbitrary axis
  1430. }
  1431. // otherwise this singularity is angle = 180
  1432. angle = Math.PI;
  1433. var xx = ( m11 + 1 ) / 2;
  1434. var yy = ( m22 + 1 ) / 2;
  1435. var zz = ( m33 + 1 ) / 2;
  1436. var xy = ( m12 + m21 ) / 4;
  1437. var xz = ( m13 + m31 ) / 4;
  1438. var yz = ( m23 + m32 ) / 4;
  1439. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1440. if ( xx < epsilon ) {
  1441. x = 0;
  1442. y = 0.707106781;
  1443. z = 0.707106781;
  1444. } else {
  1445. x = Math.sqrt( xx );
  1446. y = xy / x;
  1447. z = xz / x;
  1448. }
  1449. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1450. if ( yy < epsilon ) {
  1451. x = 0.707106781;
  1452. y = 0;
  1453. z = 0.707106781;
  1454. } else {
  1455. y = Math.sqrt( yy );
  1456. x = xy / y;
  1457. z = yz / y;
  1458. }
  1459. } else { // m33 is the largest diagonal term so base result on this
  1460. if ( zz < epsilon ) {
  1461. x = 0.707106781;
  1462. y = 0.707106781;
  1463. z = 0;
  1464. } else {
  1465. z = Math.sqrt( zz );
  1466. x = xz / z;
  1467. y = yz / z;
  1468. }
  1469. }
  1470. this.set( x, y, z, angle );
  1471. return this; // return 180 deg rotation
  1472. }
  1473. // as we have reached here there are no singularities so we can handle normally
  1474. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1475. + ( m13 - m31 ) * ( m13 - m31 )
  1476. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1477. if ( Math.abs( s ) < 0.001 ) s = 1;
  1478. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1479. // caught by singularity test above, but I've left it in just in case
  1480. this.x = ( m32 - m23 ) / s;
  1481. this.y = ( m13 - m31 ) / s;
  1482. this.z = ( m21 - m12 ) / s;
  1483. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1484. return this;
  1485. },
  1486. min: function ( v ) {
  1487. if ( this.x > v.x ) {
  1488. this.x = v.x;
  1489. }
  1490. if ( this.y > v.y ) {
  1491. this.y = v.y;
  1492. }
  1493. if ( this.z > v.z ) {
  1494. this.z = v.z;
  1495. }
  1496. if ( this.w > v.w ) {
  1497. this.w = v.w;
  1498. }
  1499. return this;
  1500. },
  1501. max: function ( v ) {
  1502. if ( this.x < v.x ) {
  1503. this.x = v.x;
  1504. }
  1505. if ( this.y < v.y ) {
  1506. this.y = v.y;
  1507. }
  1508. if ( this.z < v.z ) {
  1509. this.z = v.z;
  1510. }
  1511. if ( this.w < v.w ) {
  1512. this.w = v.w;
  1513. }
  1514. return this;
  1515. },
  1516. clamp: function ( min, max ) {
  1517. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1518. if ( this.x < min.x ) {
  1519. this.x = min.x;
  1520. } else if ( this.x > max.x ) {
  1521. this.x = max.x;
  1522. }
  1523. if ( this.y < min.y ) {
  1524. this.y = min.y;
  1525. } else if ( this.y > max.y ) {
  1526. this.y = max.y;
  1527. }
  1528. if ( this.z < min.z ) {
  1529. this.z = min.z;
  1530. } else if ( this.z > max.z ) {
  1531. this.z = max.z;
  1532. }
  1533. if ( this.w < min.w ) {
  1534. this.w = min.w;
  1535. } else if ( this.w > max.w ) {
  1536. this.w = max.w;
  1537. }
  1538. return this;
  1539. },
  1540. negate: function() {
  1541. return this.multiplyScalar( -1 );
  1542. },
  1543. dot: function ( v ) {
  1544. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1545. },
  1546. lengthSq: function () {
  1547. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1548. },
  1549. length: function () {
  1550. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1551. },
  1552. lengthManhattan: function () {
  1553. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1554. },
  1555. normalize: function () {
  1556. return this.divideScalar( this.length() );
  1557. },
  1558. setLength: function ( l ) {
  1559. var oldLength = this.length();
  1560. if ( oldLength !== 0 && l !== oldLength ) {
  1561. this.multiplyScalar( l / oldLength );
  1562. }
  1563. return this;
  1564. },
  1565. lerp: function ( v, alpha ) {
  1566. this.x += ( v.x - this.x ) * alpha;
  1567. this.y += ( v.y - this.y ) * alpha;
  1568. this.z += ( v.z - this.z ) * alpha;
  1569. this.w += ( v.w - this.w ) * alpha;
  1570. return this;
  1571. },
  1572. equals: function ( v ) {
  1573. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1574. },
  1575. fromArray: function ( array ) {
  1576. this.x = array[ 0 ];
  1577. this.y = array[ 1 ];
  1578. this.z = array[ 2 ];
  1579. this.w = array[ 3 ];
  1580. return this;
  1581. },
  1582. toArray: function () {
  1583. return [ this.x, this.y, this.z, this.w ];
  1584. },
  1585. clone: function () {
  1586. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1587. }
  1588. };
  1589. /**
  1590. * @author mrdoob / http://mrdoob.com/
  1591. * @author WestLangley / http://github.com/WestLangley
  1592. * @author bhouston / http://exocortex.com
  1593. */
  1594. THREE.Euler = function ( x, y, z, order ) {
  1595. this._x = x || 0;
  1596. this._y = y || 0;
  1597. this._z = z || 0;
  1598. this._order = order || THREE.Euler.DefaultOrder;
  1599. };
  1600. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1601. THREE.Euler.DefaultOrder = 'XYZ';
  1602. THREE.Euler.prototype = {
  1603. constructor: THREE.Euler,
  1604. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1605. _quaternion: undefined,
  1606. _updateQuaternion: function () {
  1607. if ( this._quaternion !== undefined ) {
  1608. this._quaternion.setFromEuler( this, false );
  1609. }
  1610. },
  1611. get x () {
  1612. return this._x;
  1613. },
  1614. set x ( value ) {
  1615. this._x = value;
  1616. this._updateQuaternion();
  1617. },
  1618. get y () {
  1619. return this._y;
  1620. },
  1621. set y ( value ) {
  1622. this._y = value;
  1623. this._updateQuaternion();
  1624. },
  1625. get z () {
  1626. return this._z;
  1627. },
  1628. set z ( value ) {
  1629. this._z = value;
  1630. this._updateQuaternion();
  1631. },
  1632. get order () {
  1633. return this._order;
  1634. },
  1635. set order ( value ) {
  1636. this._order = value;
  1637. this._updateQuaternion();
  1638. },
  1639. set: function ( x, y, z, order ) {
  1640. this._x = x;
  1641. this._y = y;
  1642. this._z = z;
  1643. this._order = order || this._order;
  1644. this._updateQuaternion();
  1645. return this;
  1646. },
  1647. copy: function ( euler ) {
  1648. this._x = euler._x;
  1649. this._y = euler._y;
  1650. this._z = euler._z;
  1651. this._order = euler._order;
  1652. this._updateQuaternion();
  1653. return this;
  1654. },
  1655. setFromRotationMatrix: function ( m, order ) {
  1656. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1657. // clamp, to handle numerical problems
  1658. function clamp( x ) {
  1659. return Math.min( Math.max( x, -1 ), 1 );
  1660. }
  1661. var te = m.elements;
  1662. var m11 = te[0], m12 = te[4], m13 = te[8];
  1663. var m21 = te[1], m22 = te[5], m23 = te[9];
  1664. var m31 = te[2], m32 = te[6], m33 = te[10];
  1665. order = order || this._order;
  1666. if ( order === 'XYZ' ) {
  1667. this._y = Math.asin( clamp( m13 ) );
  1668. if ( Math.abs( m13 ) < 0.99999 ) {
  1669. this._x = Math.atan2( - m23, m33 );
  1670. this._z = Math.atan2( - m12, m11 );
  1671. } else {
  1672. this._x = Math.atan2( m32, m22 );
  1673. this._z = 0;
  1674. }
  1675. } else if ( order === 'YXZ' ) {
  1676. this._x = Math.asin( - clamp( m23 ) );
  1677. if ( Math.abs( m23 ) < 0.99999 ) {
  1678. this._y = Math.atan2( m13, m33 );
  1679. this._z = Math.atan2( m21, m22 );
  1680. } else {
  1681. this._y = Math.atan2( - m31, m11 );
  1682. this._z = 0;
  1683. }
  1684. } else if ( order === 'ZXY' ) {
  1685. this._x = Math.asin( clamp( m32 ) );
  1686. if ( Math.abs( m32 ) < 0.99999 ) {
  1687. this._y = Math.atan2( - m31, m33 );
  1688. this._z = Math.atan2( - m12, m22 );
  1689. } else {
  1690. this._y = 0;
  1691. this._z = Math.atan2( m21, m11 );
  1692. }
  1693. } else if ( order === 'ZYX' ) {
  1694. this._y = Math.asin( - clamp( m31 ) );
  1695. if ( Math.abs( m31 ) < 0.99999 ) {
  1696. this._x = Math.atan2( m32, m33 );
  1697. this._z = Math.atan2( m21, m11 );
  1698. } else {
  1699. this._x = 0;
  1700. this._z = Math.atan2( - m12, m22 );
  1701. }
  1702. } else if ( order === 'YZX' ) {
  1703. this._z = Math.asin( clamp( m21 ) );
  1704. if ( Math.abs( m21 ) < 0.99999 ) {
  1705. this._x = Math.atan2( - m23, m22 );
  1706. this._y = Math.atan2( - m31, m11 );
  1707. } else {
  1708. this._x = 0;
  1709. this._y = Math.atan2( m13, m33 );
  1710. }
  1711. } else if ( order === 'XZY' ) {
  1712. this._z = Math.asin( - clamp( m12 ) );
  1713. if ( Math.abs( m12 ) < 0.99999 ) {
  1714. this._x = Math.atan2( m32, m22 );
  1715. this._y = Math.atan2( m13, m11 );
  1716. } else {
  1717. this._x = Math.atan2( - m23, m33 );
  1718. this._y = 0;
  1719. }
  1720. } else {
  1721. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1722. }
  1723. this._order = order;
  1724. this._updateQuaternion();
  1725. return this;
  1726. },
  1727. setFromQuaternion: function ( q, order, update ) {
  1728. // q is assumed to be normalized
  1729. // clamp, to handle numerical problems
  1730. function clamp( x ) {
  1731. return Math.min( Math.max( x, -1 ), 1 );
  1732. }
  1733. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1734. var sqx = q.x * q.x;
  1735. var sqy = q.y * q.y;
  1736. var sqz = q.z * q.z;
  1737. var sqw = q.w * q.w;
  1738. order = order || this._order;
  1739. if ( order === 'XYZ' ) {
  1740. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1741. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1742. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1743. } else if ( order === 'YXZ' ) {
  1744. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1745. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1746. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1747. } else if ( order === 'ZXY' ) {
  1748. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1749. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1750. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1751. } else if ( order === 'ZYX' ) {
  1752. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1753. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1754. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1755. } else if ( order === 'YZX' ) {
  1756. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1757. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1758. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1759. } else if ( order === 'XZY' ) {
  1760. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1761. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1762. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1763. } else {
  1764. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1765. }
  1766. this._order = order;
  1767. if ( update !== false ) this._updateQuaternion();
  1768. return this;
  1769. },
  1770. reorder: function () {
  1771. // WARNING: this discards revolution information -bhouston
  1772. var q = new THREE.Quaternion();
  1773. return function ( newOrder ) {
  1774. q.setFromEuler( this );
  1775. this.setFromQuaternion( q, newOrder );
  1776. };
  1777. }(),
  1778. fromArray: function ( array ) {
  1779. this._x = array[ 0 ];
  1780. this._y = array[ 1 ];
  1781. this._z = array[ 2 ];
  1782. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1783. this._updateQuaternion();
  1784. return this;
  1785. },
  1786. toArray: function () {
  1787. return [ this._x, this._y, this._z, this._order ];
  1788. },
  1789. equals: function ( euler ) {
  1790. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1791. },
  1792. clone: function () {
  1793. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1794. }
  1795. };
  1796. /**
  1797. * @author bhouston / http://exocortex.com
  1798. */
  1799. THREE.Line3 = function ( start, end ) {
  1800. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1801. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1802. };
  1803. THREE.Line3.prototype = {
  1804. constructor: THREE.Line3,
  1805. set: function ( start, end ) {
  1806. this.start.copy( start );
  1807. this.end.copy( end );
  1808. return this;
  1809. },
  1810. copy: function ( line ) {
  1811. this.start.copy( line.start );
  1812. this.end.copy( line.end );
  1813. return this;
  1814. },
  1815. center: function ( optionalTarget ) {
  1816. var result = optionalTarget || new THREE.Vector3();
  1817. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1818. },
  1819. delta: function ( optionalTarget ) {
  1820. var result = optionalTarget || new THREE.Vector3();
  1821. return result.subVectors( this.end, this.start );
  1822. },
  1823. distanceSq: function () {
  1824. return this.start.distanceToSquared( this.end );
  1825. },
  1826. distance: function () {
  1827. return this.start.distanceTo( this.end );
  1828. },
  1829. at: function ( t, optionalTarget ) {
  1830. var result = optionalTarget || new THREE.Vector3();
  1831. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1832. },
  1833. closestPointToPointParameter: function() {
  1834. var startP = new THREE.Vector3();
  1835. var startEnd = new THREE.Vector3();
  1836. return function ( point, clampToLine ) {
  1837. startP.subVectors( point, this.start );
  1838. startEnd.subVectors( this.end, this.start );
  1839. var startEnd2 = startEnd.dot( startEnd );
  1840. var startEnd_startP = startEnd.dot( startP );
  1841. var t = startEnd_startP / startEnd2;
  1842. if ( clampToLine ) {
  1843. t = THREE.Math.clamp( t, 0, 1 );
  1844. }
  1845. return t;
  1846. };
  1847. }(),
  1848. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1849. var t = this.closestPointToPointParameter( point, clampToLine );
  1850. var result = optionalTarget || new THREE.Vector3();
  1851. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1852. },
  1853. applyMatrix4: function ( matrix ) {
  1854. this.start.applyMatrix4( matrix );
  1855. this.end.applyMatrix4( matrix );
  1856. return this;
  1857. },
  1858. equals: function ( line ) {
  1859. return line.start.equals( this.start ) && line.end.equals( this.end );
  1860. },
  1861. clone: function () {
  1862. return new THREE.Line3().copy( this );
  1863. }
  1864. };
  1865. /**
  1866. * @author bhouston / http://exocortex.com
  1867. */
  1868. THREE.Box2 = function ( min, max ) {
  1869. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1870. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1871. };
  1872. THREE.Box2.prototype = {
  1873. constructor: THREE.Box2,
  1874. set: function ( min, max ) {
  1875. this.min.copy( min );
  1876. this.max.copy( max );
  1877. return this;
  1878. },
  1879. setFromPoints: function ( points ) {
  1880. if ( points.length > 0 ) {
  1881. var point = points[ 0 ];
  1882. this.min.copy( point );
  1883. this.max.copy( point );
  1884. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1885. point = points[ i ];
  1886. if ( point.x < this.min.x ) {
  1887. this.min.x = point.x;
  1888. } else if ( point.x > this.max.x ) {
  1889. this.max.x = point.x;
  1890. }
  1891. if ( point.y < this.min.y ) {
  1892. this.min.y = point.y;
  1893. } else if ( point.y > this.max.y ) {
  1894. this.max.y = point.y;
  1895. }
  1896. }
  1897. } else {
  1898. this.makeEmpty();
  1899. }
  1900. return this;
  1901. },
  1902. setFromCenterAndSize: function () {
  1903. var v1 = new THREE.Vector2();
  1904. return function ( center, size ) {
  1905. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1906. this.min.copy( center ).sub( halfSize );
  1907. this.max.copy( center ).add( halfSize );
  1908. return this;
  1909. };
  1910. }(),
  1911. copy: function ( box ) {
  1912. this.min.copy( box.min );
  1913. this.max.copy( box.max );
  1914. return this;
  1915. },
  1916. makeEmpty: function () {
  1917. this.min.x = this.min.y = Infinity;
  1918. this.max.x = this.max.y = -Infinity;
  1919. return this;
  1920. },
  1921. empty: function () {
  1922. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1923. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1924. },
  1925. center: function ( optionalTarget ) {
  1926. var result = optionalTarget || new THREE.Vector2();
  1927. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1928. },
  1929. size: function ( optionalTarget ) {
  1930. var result = optionalTarget || new THREE.Vector2();
  1931. return result.subVectors( this.max, this.min );
  1932. },
  1933. expandByPoint: function ( point ) {
  1934. this.min.min( point );
  1935. this.max.max( point );
  1936. return this;
  1937. },
  1938. expandByVector: function ( vector ) {
  1939. this.min.sub( vector );
  1940. this.max.add( vector );
  1941. return this;
  1942. },
  1943. expandByScalar: function ( scalar ) {
  1944. this.min.addScalar( -scalar );
  1945. this.max.addScalar( scalar );
  1946. return this;
  1947. },
  1948. containsPoint: function ( point ) {
  1949. if ( point.x < this.min.x || point.x > this.max.x ||
  1950. point.y < this.min.y || point.y > this.max.y ) {
  1951. return false;
  1952. }
  1953. return true;
  1954. },
  1955. containsBox: function ( box ) {
  1956. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1957. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1958. return true;
  1959. }
  1960. return false;
  1961. },
  1962. getParameter: function ( point, optionalTarget ) {
  1963. // This can potentially have a divide by zero if the box
  1964. // has a size dimension of 0.
  1965. var result = optionalTarget || new THREE.Vector2();
  1966. return result.set(
  1967. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1968. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1969. );
  1970. },
  1971. isIntersectionBox: function ( box ) {
  1972. // using 6 splitting planes to rule out intersections.
  1973. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1974. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1975. return false;
  1976. }
  1977. return true;
  1978. },
  1979. clampPoint: function ( point, optionalTarget ) {
  1980. var result = optionalTarget || new THREE.Vector2();
  1981. return result.copy( point ).clamp( this.min, this.max );
  1982. },
  1983. distanceToPoint: function () {
  1984. var v1 = new THREE.Vector2();
  1985. return function ( point ) {
  1986. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1987. return clampedPoint.sub( point ).length();
  1988. };
  1989. }(),
  1990. intersect: function ( box ) {
  1991. this.min.max( box.min );
  1992. this.max.min( box.max );
  1993. return this;
  1994. },
  1995. union: function ( box ) {
  1996. this.min.min( box.min );
  1997. this.max.max( box.max );
  1998. return this;
  1999. },
  2000. translate: function ( offset ) {
  2001. this.min.add( offset );
  2002. this.max.add( offset );
  2003. return this;
  2004. },
  2005. equals: function ( box ) {
  2006. return box.min.equals( this.min ) && box.max.equals( this.max );
  2007. },
  2008. clone: function () {
  2009. return new THREE.Box2().copy( this );
  2010. }
  2011. };
  2012. /**
  2013. * @author bhouston / http://exocortex.com
  2014. * @author WestLangley / http://github.com/WestLangley
  2015. */
  2016. THREE.Box3 = function ( min, max ) {
  2017. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2018. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2019. };
  2020. THREE.Box3.prototype = {
  2021. constructor: THREE.Box3,
  2022. set: function ( min, max ) {
  2023. this.min.copy( min );
  2024. this.max.copy( max );
  2025. return this;
  2026. },
  2027. addPoint: function ( point ) {
  2028. if ( point.x < this.min.x ) {
  2029. this.min.x = point.x;
  2030. } else if ( point.x > this.max.x ) {
  2031. this.max.x = point.x;
  2032. }
  2033. if ( point.y < this.min.y ) {
  2034. this.min.y = point.y;
  2035. } else if ( point.y > this.max.y ) {
  2036. this.max.y = point.y;
  2037. }
  2038. if ( point.z < this.min.z ) {
  2039. this.min.z = point.z;
  2040. } else if ( point.z > this.max.z ) {
  2041. this.max.z = point.z;
  2042. }
  2043. },
  2044. setFromPoints: function ( points ) {
  2045. if ( points.length > 0 ) {
  2046. var point = points[ 0 ];
  2047. this.min.copy( point );
  2048. this.max.copy( point );
  2049. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2050. this.addPoint( points[ i ] )
  2051. }
  2052. } else {
  2053. this.makeEmpty();
  2054. }
  2055. return this;
  2056. },
  2057. setFromCenterAndSize: function() {
  2058. var v1 = new THREE.Vector3();
  2059. return function ( center, size ) {
  2060. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2061. this.min.copy( center ).sub( halfSize );
  2062. this.max.copy( center ).add( halfSize );
  2063. return this;
  2064. };
  2065. }(),
  2066. setFromObject: function() {
  2067. // Computes the world-axis-aligned bounding box of an object (including its children),
  2068. // accounting for both the object's, and childrens', world transforms
  2069. var v1 = new THREE.Vector3();
  2070. return function( object ) {
  2071. var scope = this;
  2072. object.updateMatrixWorld( true );
  2073. this.makeEmpty();
  2074. object.traverse( function ( node ) {
  2075. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2076. var vertices = node.geometry.vertices;
  2077. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2078. v1.copy( vertices[ i ] );
  2079. v1.applyMatrix4( node.matrixWorld );
  2080. scope.expandByPoint( v1 );
  2081. }
  2082. }
  2083. } );
  2084. return this;
  2085. };
  2086. }(),
  2087. copy: function ( box ) {
  2088. this.min.copy( box.min );
  2089. this.max.copy( box.max );
  2090. return this;
  2091. },
  2092. makeEmpty: function () {
  2093. this.min.x = this.min.y = this.min.z = Infinity;
  2094. this.max.x = this.max.y = this.max.z = -Infinity;
  2095. return this;
  2096. },
  2097. empty: function () {
  2098. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2099. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2100. },
  2101. center: function ( optionalTarget ) {
  2102. var result = optionalTarget || new THREE.Vector3();
  2103. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2104. },
  2105. size: function ( optionalTarget ) {
  2106. var result = optionalTarget || new THREE.Vector3();
  2107. return result.subVectors( this.max, this.min );
  2108. },
  2109. expandByPoint: function ( point ) {
  2110. this.min.min( point );
  2111. this.max.max( point );
  2112. return this;
  2113. },
  2114. expandByVector: function ( vector ) {
  2115. this.min.sub( vector );
  2116. this.max.add( vector );
  2117. return this;
  2118. },
  2119. expandByScalar: function ( scalar ) {
  2120. this.min.addScalar( -scalar );
  2121. this.max.addScalar( scalar );
  2122. return this;
  2123. },
  2124. containsPoint: function ( point ) {
  2125. if ( point.x < this.min.x || point.x > this.max.x ||
  2126. point.y < this.min.y || point.y > this.max.y ||
  2127. point.z < this.min.z || point.z > this.max.z ) {
  2128. return false;
  2129. }
  2130. return true;
  2131. },
  2132. containsBox: function ( box ) {
  2133. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2134. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2135. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2136. return true;
  2137. }
  2138. return false;
  2139. },
  2140. getParameter: function ( point, optionalTarget ) {
  2141. // This can potentially have a divide by zero if the box
  2142. // has a size dimension of 0.
  2143. var result = optionalTarget || new THREE.Vector3();
  2144. return result.set(
  2145. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2146. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2147. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2148. );
  2149. },
  2150. isIntersectionBox: function ( box ) {
  2151. // using 6 splitting planes to rule out intersections.
  2152. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2153. box.max.y < this.min.y || box.min.y > this.max.y ||
  2154. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2155. return false;
  2156. }
  2157. return true;
  2158. },
  2159. clampPoint: function ( point, optionalTarget ) {
  2160. var result = optionalTarget || new THREE.Vector3();
  2161. return result.copy( point ).clamp( this.min, this.max );
  2162. },
  2163. distanceToPoint: function() {
  2164. var v1 = new THREE.Vector3();
  2165. return function ( point ) {
  2166. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2167. return clampedPoint.sub( point ).length();
  2168. };
  2169. }(),
  2170. getBoundingSphere: function() {
  2171. var v1 = new THREE.Vector3();
  2172. return function ( optionalTarget ) {
  2173. var result = optionalTarget || new THREE.Sphere();
  2174. result.center = this.center();
  2175. result.radius = this.size( v1 ).length() * 0.5;
  2176. return result;
  2177. };
  2178. }(),
  2179. intersect: function ( box ) {
  2180. this.min.max( box.min );
  2181. this.max.min( box.max );
  2182. return this;
  2183. },
  2184. union: function ( box ) {
  2185. this.min.min( box.min );
  2186. this.max.max( box.max );
  2187. return this;
  2188. },
  2189. applyMatrix4: function() {
  2190. var points = [
  2191. new THREE.Vector3(),
  2192. new THREE.Vector3(),
  2193. new THREE.Vector3(),
  2194. new THREE.Vector3(),
  2195. new THREE.Vector3(),
  2196. new THREE.Vector3(),
  2197. new THREE.Vector3(),
  2198. new THREE.Vector3()
  2199. ];
  2200. return function ( matrix ) {
  2201. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2202. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2203. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2204. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2205. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2206. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2207. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2208. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2209. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2210. this.makeEmpty();
  2211. this.setFromPoints( points );
  2212. return this;
  2213. };
  2214. }(),
  2215. translate: function ( offset ) {
  2216. this.min.add( offset );
  2217. this.max.add( offset );
  2218. return this;
  2219. },
  2220. equals: function ( box ) {
  2221. return box.min.equals( this.min ) && box.max.equals( this.max );
  2222. },
  2223. clone: function () {
  2224. return new THREE.Box3().copy( this );
  2225. }
  2226. };
  2227. /**
  2228. * @author alteredq / http://alteredqualia.com/
  2229. * @author WestLangley / http://github.com/WestLangley
  2230. * @author bhouston / http://exocortex.com
  2231. */
  2232. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2233. this.elements = new Float32Array(9);
  2234. this.set(
  2235. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2236. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2237. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2238. );
  2239. };
  2240. THREE.Matrix3.prototype = {
  2241. constructor: THREE.Matrix3,
  2242. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2243. var te = this.elements;
  2244. te[0] = n11; te[3] = n12; te[6] = n13;
  2245. te[1] = n21; te[4] = n22; te[7] = n23;
  2246. te[2] = n31; te[5] = n32; te[8] = n33;
  2247. return this;
  2248. },
  2249. identity: function () {
  2250. this.set(
  2251. 1, 0, 0,
  2252. 0, 1, 0,
  2253. 0, 0, 1
  2254. );
  2255. return this;
  2256. },
  2257. copy: function ( m ) {
  2258. var me = m.elements;
  2259. this.set(
  2260. me[0], me[3], me[6],
  2261. me[1], me[4], me[7],
  2262. me[2], me[5], me[8]
  2263. );
  2264. return this;
  2265. },
  2266. multiplyVector3: function ( vector ) {
  2267. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2268. return vector.applyMatrix3( this );
  2269. },
  2270. multiplyVector3Array: function() {
  2271. var v1 = new THREE.Vector3();
  2272. return function ( a ) {
  2273. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2274. v1.x = a[ i ];
  2275. v1.y = a[ i + 1 ];
  2276. v1.z = a[ i + 2 ];
  2277. v1.applyMatrix3(this);
  2278. a[ i ] = v1.x;
  2279. a[ i + 1 ] = v1.y;
  2280. a[ i + 2 ] = v1.z;
  2281. }
  2282. return a;
  2283. };
  2284. }(),
  2285. multiplyScalar: function ( s ) {
  2286. var te = this.elements;
  2287. te[0] *= s; te[3] *= s; te[6] *= s;
  2288. te[1] *= s; te[4] *= s; te[7] *= s;
  2289. te[2] *= s; te[5] *= s; te[8] *= s;
  2290. return this;
  2291. },
  2292. determinant: function () {
  2293. var te = this.elements;
  2294. var a = te[0], b = te[1], c = te[2],
  2295. d = te[3], e = te[4], f = te[5],
  2296. g = te[6], h = te[7], i = te[8];
  2297. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2298. },
  2299. getInverse: function ( matrix, throwOnInvertible ) {
  2300. // input: THREE.Matrix4
  2301. // ( based on http://code.google.com/p/webgl-mjs/ )
  2302. var me = matrix.elements;
  2303. var te = this.elements;
  2304. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2305. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2306. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2307. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2308. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2309. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2310. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2311. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2312. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2313. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2314. // no inverse
  2315. if ( det === 0 ) {
  2316. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2317. if ( throwOnInvertible || false ) {
  2318. throw new Error( msg );
  2319. } else {
  2320. console.warn( msg );
  2321. }
  2322. this.identity();
  2323. return this;
  2324. }
  2325. this.multiplyScalar( 1.0 / det );
  2326. return this;
  2327. },
  2328. transpose: function () {
  2329. var tmp, m = this.elements;
  2330. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2331. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2332. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2333. return this;
  2334. },
  2335. getNormalMatrix: function ( m ) {
  2336. // input: THREE.Matrix4
  2337. this.getInverse( m ).transpose();
  2338. return this;
  2339. },
  2340. transposeIntoArray: function ( r ) {
  2341. var m = this.elements;
  2342. r[ 0 ] = m[ 0 ];
  2343. r[ 1 ] = m[ 3 ];
  2344. r[ 2 ] = m[ 6 ];
  2345. r[ 3 ] = m[ 1 ];
  2346. r[ 4 ] = m[ 4 ];
  2347. r[ 5 ] = m[ 7 ];
  2348. r[ 6 ] = m[ 2 ];
  2349. r[ 7 ] = m[ 5 ];
  2350. r[ 8 ] = m[ 8 ];
  2351. return this;
  2352. },
  2353. clone: function () {
  2354. var te = this.elements;
  2355. return new THREE.Matrix3(
  2356. te[0], te[3], te[6],
  2357. te[1], te[4], te[7],
  2358. te[2], te[5], te[8]
  2359. );
  2360. }
  2361. };
  2362. /**
  2363. * @author mrdoob / http://mrdoob.com/
  2364. * @author supereggbert / http://www.paulbrunt.co.uk/
  2365. * @author philogb / http://blog.thejit.org/
  2366. * @author jordi_ros / http://plattsoft.com
  2367. * @author D1plo1d / http://github.com/D1plo1d
  2368. * @author alteredq / http://alteredqualia.com/
  2369. * @author mikael emtinger / http://gomo.se/
  2370. * @author timknip / http://www.floorplanner.com/
  2371. * @author bhouston / http://exocortex.com
  2372. * @author WestLangley / http://github.com/WestLangley
  2373. */
  2374. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2375. this.elements = new Float32Array( 16 );
  2376. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2377. // we should not support semi specification of Matrix4, it is just weird.
  2378. var te = this.elements;
  2379. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2380. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2381. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2382. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2383. };
  2384. THREE.Matrix4.prototype = {
  2385. constructor: THREE.Matrix4,
  2386. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2387. var te = this.elements;
  2388. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2389. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2390. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2391. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2392. return this;
  2393. },
  2394. identity: function () {
  2395. this.set(
  2396. 1, 0, 0, 0,
  2397. 0, 1, 0, 0,
  2398. 0, 0, 1, 0,
  2399. 0, 0, 0, 1
  2400. );
  2401. return this;
  2402. },
  2403. copy: function ( m ) {
  2404. this.elements.set( m.elements );
  2405. return this;
  2406. },
  2407. extractPosition: function ( m ) {
  2408. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2409. return this.copyPosition( m );
  2410. },
  2411. copyPosition: function ( m ) {
  2412. var te = this.elements;
  2413. var me = m.elements;
  2414. te[12] = me[12];
  2415. te[13] = me[13];
  2416. te[14] = me[14];
  2417. return this;
  2418. },
  2419. extractRotation: function () {
  2420. var v1 = new THREE.Vector3();
  2421. return function ( m ) {
  2422. var te = this.elements;
  2423. var me = m.elements;
  2424. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2425. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2426. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2427. te[0] = me[0] * scaleX;
  2428. te[1] = me[1] * scaleX;
  2429. te[2] = me[2] * scaleX;
  2430. te[4] = me[4] * scaleY;
  2431. te[5] = me[5] * scaleY;
  2432. te[6] = me[6] * scaleY;
  2433. te[8] = me[8] * scaleZ;
  2434. te[9] = me[9] * scaleZ;
  2435. te[10] = me[10] * scaleZ;
  2436. return this;
  2437. };
  2438. }(),
  2439. makeRotationFromEuler: function ( euler ) {
  2440. if ( euler instanceof THREE.Euler === false ) {
  2441. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2442. }
  2443. var te = this.elements;
  2444. var x = euler.x, y = euler.y, z = euler.z;
  2445. var a = Math.cos( x ), b = Math.sin( x );
  2446. var c = Math.cos( y ), d = Math.sin( y );
  2447. var e = Math.cos( z ), f = Math.sin( z );
  2448. if ( euler.order === 'XYZ' ) {
  2449. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2450. te[0] = c * e;
  2451. te[4] = - c * f;
  2452. te[8] = d;
  2453. te[1] = af + be * d;
  2454. te[5] = ae - bf * d;
  2455. te[9] = - b * c;
  2456. te[2] = bf - ae * d;
  2457. te[6] = be + af * d;
  2458. te[10] = a * c;
  2459. } else if ( euler.order === 'YXZ' ) {
  2460. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2461. te[0] = ce + df * b;
  2462. te[4] = de * b - cf;
  2463. te[8] = a * d;
  2464. te[1] = a * f;
  2465. te[5] = a * e;
  2466. te[9] = - b;
  2467. te[2] = cf * b - de;
  2468. te[6] = df + ce * b;
  2469. te[10] = a * c;
  2470. } else if ( euler.order === 'ZXY' ) {
  2471. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2472. te[0] = ce - df * b;
  2473. te[4] = - a * f;
  2474. te[8] = de + cf * b;
  2475. te[1] = cf + de * b;
  2476. te[5] = a * e;
  2477. te[9] = df - ce * b;
  2478. te[2] = - a * d;
  2479. te[6] = b;
  2480. te[10] = a * c;
  2481. } else if ( euler.order === 'ZYX' ) {
  2482. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2483. te[0] = c * e;
  2484. te[4] = be * d - af;
  2485. te[8] = ae * d + bf;
  2486. te[1] = c * f;
  2487. te[5] = bf * d + ae;
  2488. te[9] = af * d - be;
  2489. te[2] = - d;
  2490. te[6] = b * c;
  2491. te[10] = a * c;
  2492. } else if ( euler.order === 'YZX' ) {
  2493. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2494. te[0] = c * e;
  2495. te[4] = bd - ac * f;
  2496. te[8] = bc * f + ad;
  2497. te[1] = f;
  2498. te[5] = a * e;
  2499. te[9] = - b * e;
  2500. te[2] = - d * e;
  2501. te[6] = ad * f + bc;
  2502. te[10] = ac - bd * f;
  2503. } else if ( euler.order === 'XZY' ) {
  2504. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2505. te[0] = c * e;
  2506. te[4] = - f;
  2507. te[8] = d * e;
  2508. te[1] = ac * f + bd;
  2509. te[5] = a * e;
  2510. te[9] = ad * f - bc;
  2511. te[2] = bc * f - ad;
  2512. te[6] = b * e;
  2513. te[10] = bd * f + ac;
  2514. }
  2515. // last column
  2516. te[3] = 0;
  2517. te[7] = 0;
  2518. te[11] = 0;
  2519. // bottom row
  2520. te[12] = 0;
  2521. te[13] = 0;
  2522. te[14] = 0;
  2523. te[15] = 1;
  2524. return this;
  2525. },
  2526. setRotationFromQuaternion: function ( q ) {
  2527. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2528. return this.makeRotationFromQuaternion( q );
  2529. },
  2530. makeRotationFromQuaternion: function ( q ) {
  2531. var te = this.elements;
  2532. var x = q.x, y = q.y, z = q.z, w = q.w;
  2533. var x2 = x + x, y2 = y + y, z2 = z + z;
  2534. var xx = x * x2, xy = x * y2, xz = x * z2;
  2535. var yy = y * y2, yz = y * z2, zz = z * z2;
  2536. var wx = w * x2, wy = w * y2, wz = w * z2;
  2537. te[0] = 1 - ( yy + zz );
  2538. te[4] = xy - wz;
  2539. te[8] = xz + wy;
  2540. te[1] = xy + wz;
  2541. te[5] = 1 - ( xx + zz );
  2542. te[9] = yz - wx;
  2543. te[2] = xz - wy;
  2544. te[6] = yz + wx;
  2545. te[10] = 1 - ( xx + yy );
  2546. // last column
  2547. te[3] = 0;
  2548. te[7] = 0;
  2549. te[11] = 0;
  2550. // bottom row
  2551. te[12] = 0;
  2552. te[13] = 0;
  2553. te[14] = 0;
  2554. te[15] = 1;
  2555. return this;
  2556. },
  2557. lookAt: function() {
  2558. var x = new THREE.Vector3();
  2559. var y = new THREE.Vector3();
  2560. var z = new THREE.Vector3();
  2561. return function ( eye, target, up ) {
  2562. var te = this.elements;
  2563. z.subVectors( eye, target ).normalize();
  2564. if ( z.length() === 0 ) {
  2565. z.z = 1;
  2566. }
  2567. x.crossVectors( up, z ).normalize();
  2568. if ( x.length() === 0 ) {
  2569. z.x += 0.0001;
  2570. x.crossVectors( up, z ).normalize();
  2571. }
  2572. y.crossVectors( z, x );
  2573. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2574. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2575. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2576. return this;
  2577. };
  2578. }(),
  2579. multiply: function ( m, n ) {
  2580. if ( n !== undefined ) {
  2581. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2582. return this.multiplyMatrices( m, n );
  2583. }
  2584. return this.multiplyMatrices( this, m );
  2585. },
  2586. multiplyMatrices: function ( a, b ) {
  2587. var ae = a.elements;
  2588. var be = b.elements;
  2589. var te = this.elements;
  2590. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2591. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2592. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2593. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2594. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2595. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2596. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2597. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2598. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2599. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2600. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2601. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2602. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2603. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2604. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2605. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2606. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2607. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2608. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2609. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2610. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2611. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2612. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2613. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2614. return this;
  2615. },
  2616. multiplyToArray: function ( a, b, r ) {
  2617. var te = this.elements;
  2618. this.multiplyMatrices( a, b );
  2619. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2620. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2621. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2622. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2623. return this;
  2624. },
  2625. multiplyScalar: function ( s ) {
  2626. var te = this.elements;
  2627. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2628. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2629. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2630. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2631. return this;
  2632. },
  2633. multiplyVector3: function ( vector ) {
  2634. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2635. return vector.applyProjection( this );
  2636. },
  2637. multiplyVector4: function ( vector ) {
  2638. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2639. return vector.applyMatrix4( this );
  2640. },
  2641. multiplyVector3Array: function() {
  2642. var v1 = new THREE.Vector3();
  2643. return function ( a ) {
  2644. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2645. v1.x = a[ i ];
  2646. v1.y = a[ i + 1 ];
  2647. v1.z = a[ i + 2 ];
  2648. v1.applyProjection( this );
  2649. a[ i ] = v1.x;
  2650. a[ i + 1 ] = v1.y;
  2651. a[ i + 2 ] = v1.z;
  2652. }
  2653. return a;
  2654. };
  2655. }(),
  2656. rotateAxis: function ( v ) {
  2657. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2658. v.transformDirection( this );
  2659. },
  2660. crossVector: function ( vector ) {
  2661. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2662. return vector.applyMatrix4( this );
  2663. },
  2664. determinant: function () {
  2665. var te = this.elements;
  2666. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2667. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2668. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2669. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2670. //TODO: make this more efficient
  2671. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2672. return (
  2673. n41 * (
  2674. +n14 * n23 * n32
  2675. -n13 * n24 * n32
  2676. -n14 * n22 * n33
  2677. +n12 * n24 * n33
  2678. +n13 * n22 * n34
  2679. -n12 * n23 * n34
  2680. ) +
  2681. n42 * (
  2682. +n11 * n23 * n34
  2683. -n11 * n24 * n33
  2684. +n14 * n21 * n33
  2685. -n13 * n21 * n34
  2686. +n13 * n24 * n31
  2687. -n14 * n23 * n31
  2688. ) +
  2689. n43 * (
  2690. +n11 * n24 * n32
  2691. -n11 * n22 * n34
  2692. -n14 * n21 * n32
  2693. +n12 * n21 * n34
  2694. +n14 * n22 * n31
  2695. -n12 * n24 * n31
  2696. ) +
  2697. n44 * (
  2698. -n13 * n22 * n31
  2699. -n11 * n23 * n32
  2700. +n11 * n22 * n33
  2701. +n13 * n21 * n32
  2702. -n12 * n21 * n33
  2703. +n12 * n23 * n31
  2704. )
  2705. );
  2706. },
  2707. transpose: function () {
  2708. var te = this.elements;
  2709. var tmp;
  2710. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2711. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2712. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2713. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2714. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2715. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2716. return this;
  2717. },
  2718. flattenToArray: function ( flat ) {
  2719. var te = this.elements;
  2720. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2721. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2722. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2723. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2724. return flat;
  2725. },
  2726. flattenToArrayOffset: function( flat, offset ) {
  2727. var te = this.elements;
  2728. flat[ offset ] = te[0];
  2729. flat[ offset + 1 ] = te[1];
  2730. flat[ offset + 2 ] = te[2];
  2731. flat[ offset + 3 ] = te[3];
  2732. flat[ offset + 4 ] = te[4];
  2733. flat[ offset + 5 ] = te[5];
  2734. flat[ offset + 6 ] = te[6];
  2735. flat[ offset + 7 ] = te[7];
  2736. flat[ offset + 8 ] = te[8];
  2737. flat[ offset + 9 ] = te[9];
  2738. flat[ offset + 10 ] = te[10];
  2739. flat[ offset + 11 ] = te[11];
  2740. flat[ offset + 12 ] = te[12];
  2741. flat[ offset + 13 ] = te[13];
  2742. flat[ offset + 14 ] = te[14];
  2743. flat[ offset + 15 ] = te[15];
  2744. return flat;
  2745. },
  2746. getPosition: function() {
  2747. var v1 = new THREE.Vector3();
  2748. return function () {
  2749. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2750. var te = this.elements;
  2751. return v1.set( te[12], te[13], te[14] );
  2752. };
  2753. }(),
  2754. setPosition: function ( v ) {
  2755. var te = this.elements;
  2756. te[12] = v.x;
  2757. te[13] = v.y;
  2758. te[14] = v.z;
  2759. return this;
  2760. },
  2761. getInverse: function ( m, throwOnInvertible ) {
  2762. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2763. var te = this.elements;
  2764. var me = m.elements;
  2765. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2766. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2767. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2768. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2769. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2770. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2771. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2772. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2773. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2774. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2775. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2776. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2777. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2778. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2779. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2780. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2781. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2782. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2783. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2784. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2785. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2786. if ( det == 0 ) {
  2787. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2788. if ( throwOnInvertible || false ) {
  2789. throw new Error( msg );
  2790. } else {
  2791. console.warn( msg );
  2792. }
  2793. this.identity();
  2794. return this;
  2795. }
  2796. this.multiplyScalar( 1 / det );
  2797. return this;
  2798. },
  2799. translate: function ( v ) {
  2800. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2801. },
  2802. rotateX: function ( angle ) {
  2803. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2804. },
  2805. rotateY: function ( angle ) {
  2806. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2807. },
  2808. rotateZ: function ( angle ) {
  2809. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2810. },
  2811. rotateByAxis: function ( axis, angle ) {
  2812. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2813. },
  2814. scale: function ( v ) {
  2815. var te = this.elements;
  2816. var x = v.x, y = v.y, z = v.z;
  2817. te[0] *= x; te[4] *= y; te[8] *= z;
  2818. te[1] *= x; te[5] *= y; te[9] *= z;
  2819. te[2] *= x; te[6] *= y; te[10] *= z;
  2820. te[3] *= x; te[7] *= y; te[11] *= z;
  2821. return this;
  2822. },
  2823. getMaxScaleOnAxis: function () {
  2824. var te = this.elements;
  2825. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2826. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2827. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2828. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2829. },
  2830. makeTranslation: function ( x, y, z ) {
  2831. this.set(
  2832. 1, 0, 0, x,
  2833. 0, 1, 0, y,
  2834. 0, 0, 1, z,
  2835. 0, 0, 0, 1
  2836. );
  2837. return this;
  2838. },
  2839. makeRotationX: function ( theta ) {
  2840. var c = Math.cos( theta ), s = Math.sin( theta );
  2841. this.set(
  2842. 1, 0, 0, 0,
  2843. 0, c, -s, 0,
  2844. 0, s, c, 0,
  2845. 0, 0, 0, 1
  2846. );
  2847. return this;
  2848. },
  2849. makeRotationY: function ( theta ) {
  2850. var c = Math.cos( theta ), s = Math.sin( theta );
  2851. this.set(
  2852. c, 0, s, 0,
  2853. 0, 1, 0, 0,
  2854. -s, 0, c, 0,
  2855. 0, 0, 0, 1
  2856. );
  2857. return this;
  2858. },
  2859. makeRotationZ: function ( theta ) {
  2860. var c = Math.cos( theta ), s = Math.sin( theta );
  2861. this.set(
  2862. c, -s, 0, 0,
  2863. s, c, 0, 0,
  2864. 0, 0, 1, 0,
  2865. 0, 0, 0, 1
  2866. );
  2867. return this;
  2868. },
  2869. makeRotationAxis: function ( axis, angle ) {
  2870. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2871. var c = Math.cos( angle );
  2872. var s = Math.sin( angle );
  2873. var t = 1 - c;
  2874. var x = axis.x, y = axis.y, z = axis.z;
  2875. var tx = t * x, ty = t * y;
  2876. this.set(
  2877. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2878. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2879. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2880. 0, 0, 0, 1
  2881. );
  2882. return this;
  2883. },
  2884. makeScale: function ( x, y, z ) {
  2885. this.set(
  2886. x, 0, 0, 0,
  2887. 0, y, 0, 0,
  2888. 0, 0, z, 0,
  2889. 0, 0, 0, 1
  2890. );
  2891. return this;
  2892. },
  2893. compose: function ( position, quaternion, scale ) {
  2894. this.makeRotationFromQuaternion( quaternion );
  2895. this.scale( scale );
  2896. this.setPosition( position );
  2897. return this;
  2898. },
  2899. decompose: function () {
  2900. var vector = new THREE.Vector3();
  2901. var matrix = new THREE.Matrix4();
  2902. return function ( position, quaternion, scale ) {
  2903. var te = this.elements;
  2904. var sx = vector.set( te[0], te[1], te[2] ).length();
  2905. var sy = vector.set( te[4], te[5], te[6] ).length();
  2906. var sz = vector.set( te[8], te[9], te[10] ).length();
  2907. position.x = te[12];
  2908. position.y = te[13];
  2909. position.z = te[14];
  2910. // scale the rotation part
  2911. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2912. var invSX = 1 / sx;
  2913. var invSY = 1 / sy;
  2914. var invSZ = 1 / sz;
  2915. matrix.elements[0] *= invSX;
  2916. matrix.elements[1] *= invSX;
  2917. matrix.elements[2] *= invSX;
  2918. matrix.elements[4] *= invSY;
  2919. matrix.elements[5] *= invSY;
  2920. matrix.elements[6] *= invSY;
  2921. matrix.elements[8] *= invSZ;
  2922. matrix.elements[9] *= invSZ;
  2923. matrix.elements[10] *= invSZ;
  2924. quaternion.setFromRotationMatrix( matrix );
  2925. scale.x = sx;
  2926. scale.y = sy;
  2927. scale.z = sz;
  2928. return this;
  2929. };
  2930. }(),
  2931. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2932. var te = this.elements;
  2933. var x = 2 * near / ( right - left );
  2934. var y = 2 * near / ( top - bottom );
  2935. var a = ( right + left ) / ( right - left );
  2936. var b = ( top + bottom ) / ( top - bottom );
  2937. var c = - ( far + near ) / ( far - near );
  2938. var d = - 2 * far * near / ( far - near );
  2939. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2940. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2941. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2942. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2943. return this;
  2944. },
  2945. makePerspective: function ( fov, aspect, near, far ) {
  2946. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2947. var ymin = - ymax;
  2948. var xmin = ymin * aspect;
  2949. var xmax = ymax * aspect;
  2950. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2951. },
  2952. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2953. var te = this.elements;
  2954. var w = right - left;
  2955. var h = top - bottom;
  2956. var p = far - near;
  2957. var x = ( right + left ) / w;
  2958. var y = ( top + bottom ) / h;
  2959. var z = ( far + near ) / p;
  2960. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2961. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2962. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2963. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2964. return this;
  2965. },
  2966. fromArray: function ( array ) {
  2967. this.elements.set( array );
  2968. return this;
  2969. },
  2970. toArray: function () {
  2971. var te = this.elements;
  2972. return [
  2973. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2974. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2975. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2976. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2977. ];
  2978. },
  2979. clone: function () {
  2980. var te = this.elements;
  2981. return new THREE.Matrix4(
  2982. te[0], te[4], te[8], te[12],
  2983. te[1], te[5], te[9], te[13],
  2984. te[2], te[6], te[10], te[14],
  2985. te[3], te[7], te[11], te[15]
  2986. );
  2987. }
  2988. };
  2989. /**
  2990. * @author bhouston / http://exocortex.com
  2991. */
  2992. THREE.Ray = function ( origin, direction ) {
  2993. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2994. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2995. };
  2996. THREE.Ray.prototype = {
  2997. constructor: THREE.Ray,
  2998. set: function ( origin, direction ) {
  2999. this.origin.copy( origin );
  3000. this.direction.copy( direction );
  3001. return this;
  3002. },
  3003. copy: function ( ray ) {
  3004. this.origin.copy( ray.origin );
  3005. this.direction.copy( ray.direction );
  3006. return this;
  3007. },
  3008. at: function ( t, optionalTarget ) {
  3009. var result = optionalTarget || new THREE.Vector3();
  3010. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3011. },
  3012. recast: function () {
  3013. var v1 = new THREE.Vector3();
  3014. return function ( t ) {
  3015. this.origin.copy( this.at( t, v1 ) );
  3016. return this;
  3017. };
  3018. }(),
  3019. closestPointToPoint: function ( point, optionalTarget ) {
  3020. var result = optionalTarget || new THREE.Vector3();
  3021. result.subVectors( point, this.origin );
  3022. var directionDistance = result.dot( this.direction );
  3023. if ( directionDistance < 0 ) {
  3024. return result.copy( this.origin );
  3025. }
  3026. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3027. },
  3028. distanceToPoint: function () {
  3029. var v1 = new THREE.Vector3();
  3030. return function ( point ) {
  3031. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3032. // point behind the ray
  3033. if ( directionDistance < 0 ) {
  3034. return this.origin.distanceTo( point );
  3035. }
  3036. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3037. return v1.distanceTo( point );
  3038. };
  3039. }(),
  3040. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3041. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3042. // It returns the min distance between the ray and the segment
  3043. // defined by v0 and v1
  3044. // It can also set two optional targets :
  3045. // - The closest point on the ray
  3046. // - The closest point on the segment
  3047. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3048. var segDir = v1.clone().sub( v0 ).normalize();
  3049. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3050. var diff = this.origin.clone().sub( segCenter );
  3051. var a01 = - this.direction.dot( segDir );
  3052. var b0 = diff.dot( this.direction );
  3053. var b1 = - diff.dot( segDir );
  3054. var c = diff.lengthSq();
  3055. var det = Math.abs( 1 - a01 * a01 );
  3056. var s0, s1, sqrDist, extDet;
  3057. if ( det >= 0 ) {
  3058. // The ray and segment are not parallel.
  3059. s0 = a01 * b1 - b0;
  3060. s1 = a01 * b0 - b1;
  3061. extDet = segExtent * det;
  3062. if ( s0 >= 0 ) {
  3063. if ( s1 >= - extDet ) {
  3064. if ( s1 <= extDet ) {
  3065. // region 0
  3066. // Minimum at interior points of ray and segment.
  3067. var invDet = 1 / det;
  3068. s0 *= invDet;
  3069. s1 *= invDet;
  3070. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3071. } else {
  3072. // region 1
  3073. s1 = segExtent;
  3074. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3075. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3076. }
  3077. } else {
  3078. // region 5
  3079. s1 = - segExtent;
  3080. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3081. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3082. }
  3083. } else {
  3084. if ( s1 <= - extDet) {
  3085. // region 4
  3086. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3087. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3088. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3089. } else if ( s1 <= extDet ) {
  3090. // region 3
  3091. s0 = 0;
  3092. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3093. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3094. } else {
  3095. // region 2
  3096. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3097. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3098. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3099. }
  3100. }
  3101. } else {
  3102. // Ray and segment are parallel.
  3103. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3104. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3105. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3106. }
  3107. if ( optionalPointOnRay ) {
  3108. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3109. }
  3110. if ( optionalPointOnSegment ) {
  3111. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3112. }
  3113. return sqrDist;
  3114. },
  3115. isIntersectionSphere: function ( sphere ) {
  3116. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3117. },
  3118. isIntersectionPlane: function ( plane ) {
  3119. // check if the ray lies on the plane first
  3120. var distToPoint = plane.distanceToPoint( this.origin );
  3121. if ( distToPoint === 0 ) {
  3122. return true;
  3123. }
  3124. var denominator = plane.normal.dot( this.direction );
  3125. if ( denominator * distToPoint < 0 ) {
  3126. return true
  3127. }
  3128. // ray origin is behind the plane (and is pointing behind it)
  3129. return false;
  3130. },
  3131. distanceToPlane: function ( plane ) {
  3132. var denominator = plane.normal.dot( this.direction );
  3133. if ( denominator == 0 ) {
  3134. // line is coplanar, return origin
  3135. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3136. return 0;
  3137. }
  3138. // Null is preferable to undefined since undefined means.... it is undefined
  3139. return null;
  3140. }
  3141. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3142. // Return if the ray never intersects the plane
  3143. return t >= 0 ? t : null;
  3144. },
  3145. intersectPlane: function ( plane, optionalTarget ) {
  3146. var t = this.distanceToPlane( plane );
  3147. if ( t === null ) {
  3148. return null;
  3149. }
  3150. return this.at( t, optionalTarget );
  3151. },
  3152. isIntersectionBox: function () {
  3153. var v = new THREE.Vector3();
  3154. return function ( box ) {
  3155. return this.intersectBox( box, v ) !== null;
  3156. }
  3157. }(),
  3158. intersectBox: function ( box , optionalTarget ) {
  3159. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3160. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3161. var invdirx = 1/this.direction.x,
  3162. invdiry = 1/this.direction.y,
  3163. invdirz = 1/this.direction.z;
  3164. var origin = this.origin;
  3165. if (invdirx >= 0) {
  3166. tmin = (box.min.x - origin.x) * invdirx;
  3167. tmax = (box.max.x - origin.x) * invdirx;
  3168. } else {
  3169. tmin = (box.max.x - origin.x) * invdirx;
  3170. tmax = (box.min.x - origin.x) * invdirx;
  3171. }
  3172. if (invdiry >= 0) {
  3173. tymin = (box.min.y - origin.y) * invdiry;
  3174. tymax = (box.max.y - origin.y) * invdiry;
  3175. } else {
  3176. tymin = (box.max.y - origin.y) * invdiry;
  3177. tymax = (box.min.y - origin.y) * invdiry;
  3178. }
  3179. if ((tmin > tymax) || (tymin > tmax)) return null;
  3180. // These lines also handle the case where tmin or tmax is NaN
  3181. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3182. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3183. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3184. if (invdirz >= 0) {
  3185. tzmin = (box.min.z - origin.z) * invdirz;
  3186. tzmax = (box.max.z - origin.z) * invdirz;
  3187. } else {
  3188. tzmin = (box.max.z - origin.z) * invdirz;
  3189. tzmax = (box.min.z - origin.z) * invdirz;
  3190. }
  3191. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3192. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3193. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3194. //return point closest to the ray (positive side)
  3195. if ( tmax < 0 ) return null;
  3196. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3197. },
  3198. intersectTriangle: function() {
  3199. // Compute the offset origin, edges, and normal.
  3200. var diff = new THREE.Vector3();
  3201. var edge1 = new THREE.Vector3();
  3202. var edge2 = new THREE.Vector3();
  3203. var normal = new THREE.Vector3();
  3204. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3205. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3206. edge1.subVectors( b, a );
  3207. edge2.subVectors( c, a );
  3208. normal.crossVectors( edge1, edge2 );
  3209. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3210. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3211. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3212. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3213. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3214. var DdN = this.direction.dot( normal );
  3215. var sign;
  3216. if ( DdN > 0 ) {
  3217. if ( backfaceCulling ) return null;
  3218. sign = 1;
  3219. } else if ( DdN < 0 ) {
  3220. sign = - 1;
  3221. DdN = - DdN;
  3222. } else {
  3223. return null;
  3224. }
  3225. diff.subVectors( this.origin, a );
  3226. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3227. // b1 < 0, no intersection
  3228. if ( DdQxE2 < 0 ) {
  3229. return null;
  3230. }
  3231. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3232. // b2 < 0, no intersection
  3233. if ( DdE1xQ < 0 ) {
  3234. return null;
  3235. }
  3236. // b1+b2 > 1, no intersection
  3237. if ( DdQxE2 + DdE1xQ > DdN ) {
  3238. return null;
  3239. }
  3240. // Line intersects triangle, check if ray does.
  3241. var QdN = - sign * diff.dot( normal );
  3242. // t < 0, no intersection
  3243. if ( QdN < 0 ) {
  3244. return null;
  3245. }
  3246. // Ray intersects triangle.
  3247. return this.at( QdN / DdN, optionalTarget );
  3248. }
  3249. }(),
  3250. applyMatrix4: function ( matrix4 ) {
  3251. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3252. this.origin.applyMatrix4( matrix4 );
  3253. this.direction.sub( this.origin );
  3254. this.direction.normalize();
  3255. return this;
  3256. },
  3257. equals: function ( ray ) {
  3258. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3259. },
  3260. clone: function () {
  3261. return new THREE.Ray().copy( this );
  3262. }
  3263. };
  3264. /**
  3265. * @author bhouston / http://exocortex.com
  3266. * @author mrdoob / http://mrdoob.com/
  3267. */
  3268. THREE.Sphere = function ( center, radius ) {
  3269. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3270. this.radius = ( radius !== undefined ) ? radius : 0;
  3271. };
  3272. THREE.Sphere.prototype = {
  3273. constructor: THREE.Sphere,
  3274. set: function ( center, radius ) {
  3275. this.center.copy( center );
  3276. this.radius = radius;
  3277. return this;
  3278. },
  3279. setFromPoints: function () {
  3280. var box = new THREE.Box3();
  3281. return function ( points, optionalCenter ) {
  3282. var center = this.center;
  3283. if ( optionalCenter !== undefined ) {
  3284. center.copy( optionalCenter );
  3285. } else {
  3286. box.setFromPoints( points ).center( center );
  3287. }
  3288. var maxRadiusSq = 0;
  3289. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3290. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3291. }
  3292. this.radius = Math.sqrt( maxRadiusSq );
  3293. return this;
  3294. };
  3295. }(),
  3296. copy: function ( sphere ) {
  3297. this.center.copy( sphere.center );
  3298. this.radius = sphere.radius;
  3299. return this;
  3300. },
  3301. empty: function () {
  3302. return ( this.radius <= 0 );
  3303. },
  3304. containsPoint: function ( point ) {
  3305. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3306. },
  3307. distanceToPoint: function ( point ) {
  3308. return ( point.distanceTo( this.center ) - this.radius );
  3309. },
  3310. intersectsSphere: function ( sphere ) {
  3311. var radiusSum = this.radius + sphere.radius;
  3312. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3313. },
  3314. clampPoint: function ( point, optionalTarget ) {
  3315. var deltaLengthSq = this.center.distanceToSquared( point );
  3316. var result = optionalTarget || new THREE.Vector3();
  3317. result.copy( point );
  3318. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3319. result.sub( this.center ).normalize();
  3320. result.multiplyScalar( this.radius ).add( this.center );
  3321. }
  3322. return result;
  3323. },
  3324. getBoundingBox: function ( optionalTarget ) {
  3325. var box = optionalTarget || new THREE.Box3();
  3326. box.set( this.center, this.center );
  3327. box.expandByScalar( this.radius );
  3328. return box;
  3329. },
  3330. applyMatrix4: function ( matrix ) {
  3331. this.center.applyMatrix4( matrix );
  3332. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3333. return this;
  3334. },
  3335. translate: function ( offset ) {
  3336. this.center.add( offset );
  3337. return this;
  3338. },
  3339. equals: function ( sphere ) {
  3340. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3341. },
  3342. clone: function () {
  3343. return new THREE.Sphere().copy( this );
  3344. }
  3345. };
  3346. /**
  3347. * @author mrdoob / http://mrdoob.com/
  3348. * @author alteredq / http://alteredqualia.com/
  3349. * @author bhouston / http://exocortex.com
  3350. */
  3351. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3352. this.planes = [
  3353. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3354. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3355. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3356. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3357. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3358. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3359. ];
  3360. };
  3361. THREE.Frustum.prototype = {
  3362. constructor: THREE.Frustum,
  3363. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3364. var planes = this.planes;
  3365. planes[0].copy( p0 );
  3366. planes[1].copy( p1 );
  3367. planes[2].copy( p2 );
  3368. planes[3].copy( p3 );
  3369. planes[4].copy( p4 );
  3370. planes[5].copy( p5 );
  3371. return this;
  3372. },
  3373. copy: function ( frustum ) {
  3374. var planes = this.planes;
  3375. for( var i = 0; i < 6; i ++ ) {
  3376. planes[i].copy( frustum.planes[i] );
  3377. }
  3378. return this;
  3379. },
  3380. setFromMatrix: function ( m ) {
  3381. var planes = this.planes;
  3382. var me = m.elements;
  3383. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3384. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3385. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3386. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3387. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3388. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3389. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3390. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3391. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3392. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3393. return this;
  3394. },
  3395. intersectsObject: function () {
  3396. var sphere = new THREE.Sphere();
  3397. return function ( object ) {
  3398. var geometry = object.geometry;
  3399. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3400. sphere.copy( geometry.boundingSphere );
  3401. sphere.applyMatrix4( object.matrixWorld );
  3402. return this.intersectsSphere( sphere );
  3403. };
  3404. }(),
  3405. intersectsSphere: function ( sphere ) {
  3406. var planes = this.planes;
  3407. var center = sphere.center;
  3408. var negRadius = -sphere.radius;
  3409. for ( var i = 0; i < 6; i ++ ) {
  3410. var distance = planes[ i ].distanceToPoint( center );
  3411. if ( distance < negRadius ) {
  3412. return false;
  3413. }
  3414. }
  3415. return true;
  3416. },
  3417. intersectsBox : function() {
  3418. var p1 = new THREE.Vector3(),
  3419. p2 = new THREE.Vector3();
  3420. return function( box ) {
  3421. var planes = this.planes;
  3422. for ( var i = 0; i < 6 ; i ++ ) {
  3423. var plane = planes[i];
  3424. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3425. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3426. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3427. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3428. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3429. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3430. var d1 = plane.distanceToPoint( p1 );
  3431. var d2 = plane.distanceToPoint( p2 );
  3432. // if both outside plane, no intersection
  3433. if ( d1 < 0 && d2 < 0 ) {
  3434. return false;
  3435. }
  3436. }
  3437. return true;
  3438. };
  3439. }(),
  3440. containsPoint: function ( point ) {
  3441. var planes = this.planes;
  3442. for ( var i = 0; i < 6; i ++ ) {
  3443. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3444. return false;
  3445. }
  3446. }
  3447. return true;
  3448. },
  3449. clone: function () {
  3450. return new THREE.Frustum().copy( this );
  3451. }
  3452. };
  3453. /**
  3454. * @author bhouston / http://exocortex.com
  3455. */
  3456. THREE.Plane = function ( normal, constant ) {
  3457. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3458. this.constant = ( constant !== undefined ) ? constant : 0;
  3459. };
  3460. THREE.Plane.prototype = {
  3461. constructor: THREE.Plane,
  3462. set: function ( normal, constant ) {
  3463. this.normal.copy( normal );
  3464. this.constant = constant;
  3465. return this;
  3466. },
  3467. setComponents: function ( x, y, z, w ) {
  3468. this.normal.set( x, y, z );
  3469. this.constant = w;
  3470. return this;
  3471. },
  3472. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3473. this.normal.copy( normal );
  3474. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3475. return this;
  3476. },
  3477. setFromCoplanarPoints: function() {
  3478. var v1 = new THREE.Vector3();
  3479. var v2 = new THREE.Vector3();
  3480. return function ( a, b, c ) {
  3481. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3482. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3483. this.setFromNormalAndCoplanarPoint( normal, a );
  3484. return this;
  3485. };
  3486. }(),
  3487. copy: function ( plane ) {
  3488. this.normal.copy( plane.normal );
  3489. this.constant = plane.constant;
  3490. return this;
  3491. },
  3492. normalize: function () {
  3493. // Note: will lead to a divide by zero if the plane is invalid.
  3494. var inverseNormalLength = 1.0 / this.normal.length();
  3495. this.normal.multiplyScalar( inverseNormalLength );
  3496. this.constant *= inverseNormalLength;
  3497. return this;
  3498. },
  3499. negate: function () {
  3500. this.constant *= -1;
  3501. this.normal.negate();
  3502. return this;
  3503. },
  3504. distanceToPoint: function ( point ) {
  3505. return this.normal.dot( point ) + this.constant;
  3506. },
  3507. distanceToSphere: function ( sphere ) {
  3508. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3509. },
  3510. projectPoint: function ( point, optionalTarget ) {
  3511. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3512. },
  3513. orthoPoint: function ( point, optionalTarget ) {
  3514. var perpendicularMagnitude = this.distanceToPoint( point );
  3515. var result = optionalTarget || new THREE.Vector3();
  3516. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3517. },
  3518. isIntersectionLine: function ( line ) {
  3519. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3520. var startSign = this.distanceToPoint( line.start );
  3521. var endSign = this.distanceToPoint( line.end );
  3522. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3523. },
  3524. intersectLine: function() {
  3525. var v1 = new THREE.Vector3();
  3526. return function ( line, optionalTarget ) {
  3527. var result = optionalTarget || new THREE.Vector3();
  3528. var direction = line.delta( v1 );
  3529. var denominator = this.normal.dot( direction );
  3530. if ( denominator == 0 ) {
  3531. // line is coplanar, return origin
  3532. if( this.distanceToPoint( line.start ) == 0 ) {
  3533. return result.copy( line.start );
  3534. }
  3535. // Unsure if this is the correct method to handle this case.
  3536. return undefined;
  3537. }
  3538. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3539. if( t < 0 || t > 1 ) {
  3540. return undefined;
  3541. }
  3542. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3543. };
  3544. }(),
  3545. coplanarPoint: function ( optionalTarget ) {
  3546. var result = optionalTarget || new THREE.Vector3();
  3547. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3548. },
  3549. applyMatrix4: function() {
  3550. var v1 = new THREE.Vector3();
  3551. var v2 = new THREE.Vector3();
  3552. var m1 = new THREE.Matrix3();
  3553. return function ( matrix, optionalNormalMatrix ) {
  3554. // compute new normal based on theory here:
  3555. // http://www.songho.ca/opengl/gl_normaltransform.html
  3556. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3557. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3558. var newCoplanarPoint = this.coplanarPoint( v2 );
  3559. newCoplanarPoint.applyMatrix4( matrix );
  3560. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3561. return this;
  3562. };
  3563. }(),
  3564. translate: function ( offset ) {
  3565. this.constant = this.constant - offset.dot( this.normal );
  3566. return this;
  3567. },
  3568. equals: function ( plane ) {
  3569. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3570. },
  3571. clone: function () {
  3572. return new THREE.Plane().copy( this );
  3573. }
  3574. };
  3575. /**
  3576. * @author alteredq / http://alteredqualia.com/
  3577. * @author mrdoob / http://mrdoob.com/
  3578. */
  3579. THREE.Math = {
  3580. PI2: Math.PI * 2,
  3581. generateUUID: function () {
  3582. // http://www.broofa.com/Tools/Math.uuid.htm
  3583. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3584. var uuid = new Array(36);
  3585. var rnd = 0, r;
  3586. return function () {
  3587. for ( var i = 0; i < 36; i ++ ) {
  3588. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3589. uuid[ i ] = '-';
  3590. } else if ( i == 14 ) {
  3591. uuid[ i ] = '4';
  3592. } else {
  3593. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3594. r = rnd & 0xf;
  3595. rnd = rnd >> 4;
  3596. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3597. }
  3598. }
  3599. return uuid.join('');
  3600. };
  3601. }(),
  3602. // Clamp value to range <a, b>
  3603. clamp: function ( x, a, b ) {
  3604. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3605. },
  3606. // Clamp value to range <a, inf)
  3607. clampBottom: function ( x, a ) {
  3608. return x < a ? a : x;
  3609. },
  3610. // Linear mapping from range <a1, a2> to range <b1, b2>
  3611. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3612. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3613. },
  3614. // http://en.wikipedia.org/wiki/Smoothstep
  3615. smoothstep: function ( x, min, max ) {
  3616. if ( x <= min ) return 0;
  3617. if ( x >= max ) return 1;
  3618. x = ( x - min )/( max - min );
  3619. return x*x*(3 - 2*x);
  3620. },
  3621. smootherstep: function ( x, min, max ) {
  3622. if ( x <= min ) return 0;
  3623. if ( x >= max ) return 1;
  3624. x = ( x - min )/( max - min );
  3625. return x*x*x*(x*(x*6 - 15) + 10);
  3626. },
  3627. // Random float from <0, 1> with 16 bits of randomness
  3628. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3629. random16: function () {
  3630. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3631. },
  3632. // Random integer from <low, high> interval
  3633. randInt: function ( low, high ) {
  3634. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3635. },
  3636. // Random float from <low, high> interval
  3637. randFloat: function ( low, high ) {
  3638. return low + Math.random() * ( high - low );
  3639. },
  3640. // Random float from <-range/2, range/2> interval
  3641. randFloatSpread: function ( range ) {
  3642. return range * ( 0.5 - Math.random() );
  3643. },
  3644. sign: function ( x ) {
  3645. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3646. },
  3647. degToRad: function() {
  3648. var degreeToRadiansFactor = Math.PI / 180;
  3649. return function ( degrees ) {
  3650. return degrees * degreeToRadiansFactor;
  3651. };
  3652. }(),
  3653. radToDeg: function() {
  3654. var radianToDegreesFactor = 180 / Math.PI;
  3655. return function ( radians ) {
  3656. return radians * radianToDegreesFactor;
  3657. };
  3658. }()
  3659. };
  3660. /**
  3661. * Spline from Tween.js, slightly optimized (and trashed)
  3662. * http://sole.github.com/tween.js/examples/05_spline.html
  3663. *
  3664. * @author mrdoob / http://mrdoob.com/
  3665. * @author alteredq / http://alteredqualia.com/
  3666. */
  3667. THREE.Spline = function ( points ) {
  3668. this.points = points;
  3669. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3670. point, intPoint, weight, w2, w3,
  3671. pa, pb, pc, pd;
  3672. this.initFromArray = function( a ) {
  3673. this.points = [];
  3674. for ( var i = 0; i < a.length; i++ ) {
  3675. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3676. }
  3677. };
  3678. this.getPoint = function ( k ) {
  3679. point = ( this.points.length - 1 ) * k;
  3680. intPoint = Math.floor( point );
  3681. weight = point - intPoint;
  3682. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3683. c[ 1 ] = intPoint;
  3684. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3685. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3686. pa = this.points[ c[ 0 ] ];
  3687. pb = this.points[ c[ 1 ] ];
  3688. pc = this.points[ c[ 2 ] ];
  3689. pd = this.points[ c[ 3 ] ];
  3690. w2 = weight * weight;
  3691. w3 = weight * w2;
  3692. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3693. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3694. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3695. return v3;
  3696. };
  3697. this.getControlPointsArray = function () {
  3698. var i, p, l = this.points.length,
  3699. coords = [];
  3700. for ( i = 0; i < l; i ++ ) {
  3701. p = this.points[ i ];
  3702. coords[ i ] = [ p.x, p.y, p.z ];
  3703. }
  3704. return coords;
  3705. };
  3706. // approximate length by summing linear segments
  3707. this.getLength = function ( nSubDivisions ) {
  3708. var i, index, nSamples, position,
  3709. point = 0, intPoint = 0, oldIntPoint = 0,
  3710. oldPosition = new THREE.Vector3(),
  3711. tmpVec = new THREE.Vector3(),
  3712. chunkLengths = [],
  3713. totalLength = 0;
  3714. // first point has 0 length
  3715. chunkLengths[ 0 ] = 0;
  3716. if ( !nSubDivisions ) nSubDivisions = 100;
  3717. nSamples = this.points.length * nSubDivisions;
  3718. oldPosition.copy( this.points[ 0 ] );
  3719. for ( i = 1; i < nSamples; i ++ ) {
  3720. index = i / nSamples;
  3721. position = this.getPoint( index );
  3722. tmpVec.copy( position );
  3723. totalLength += tmpVec.distanceTo( oldPosition );
  3724. oldPosition.copy( position );
  3725. point = ( this.points.length - 1 ) * index;
  3726. intPoint = Math.floor( point );
  3727. if ( intPoint != oldIntPoint ) {
  3728. chunkLengths[ intPoint ] = totalLength;
  3729. oldIntPoint = intPoint;
  3730. }
  3731. }
  3732. // last point ends with total length
  3733. chunkLengths[ chunkLengths.length ] = totalLength;
  3734. return { chunks: chunkLengths, total: totalLength };
  3735. };
  3736. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3737. var i, j,
  3738. index, indexCurrent, indexNext,
  3739. linearDistance, realDistance,
  3740. sampling, position,
  3741. newpoints = [],
  3742. tmpVec = new THREE.Vector3(),
  3743. sl = this.getLength();
  3744. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3745. for ( i = 1; i < this.points.length; i++ ) {
  3746. //tmpVec.copy( this.points[ i - 1 ] );
  3747. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3748. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3749. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3750. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3751. indexNext = i / ( this.points.length - 1 );
  3752. for ( j = 1; j < sampling - 1; j++ ) {
  3753. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3754. position = this.getPoint( index );
  3755. newpoints.push( tmpVec.copy( position ).clone() );
  3756. }
  3757. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3758. }
  3759. this.points = newpoints;
  3760. };
  3761. // Catmull-Rom
  3762. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3763. var v0 = ( p2 - p0 ) * 0.5,
  3764. v1 = ( p3 - p1 ) * 0.5;
  3765. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3766. };
  3767. };
  3768. /**
  3769. * @author bhouston / http://exocortex.com
  3770. * @author mrdoob / http://mrdoob.com/
  3771. */
  3772. THREE.Triangle = function ( a, b, c ) {
  3773. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3774. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3775. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3776. };
  3777. THREE.Triangle.normal = function() {
  3778. var v0 = new THREE.Vector3();
  3779. return function ( a, b, c, optionalTarget ) {
  3780. var result = optionalTarget || new THREE.Vector3();
  3781. result.subVectors( c, b );
  3782. v0.subVectors( a, b );
  3783. result.cross( v0 );
  3784. var resultLengthSq = result.lengthSq();
  3785. if( resultLengthSq > 0 ) {
  3786. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3787. }
  3788. return result.set( 0, 0, 0 );
  3789. };
  3790. }();
  3791. // static/instance method to calculate barycoordinates
  3792. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3793. THREE.Triangle.barycoordFromPoint = function() {
  3794. var v0 = new THREE.Vector3();
  3795. var v1 = new THREE.Vector3();
  3796. var v2 = new THREE.Vector3();
  3797. return function ( point, a, b, c, optionalTarget ) {
  3798. v0.subVectors( c, a );
  3799. v1.subVectors( b, a );
  3800. v2.subVectors( point, a );
  3801. var dot00 = v0.dot( v0 );
  3802. var dot01 = v0.dot( v1 );
  3803. var dot02 = v0.dot( v2 );
  3804. var dot11 = v1.dot( v1 );
  3805. var dot12 = v1.dot( v2 );
  3806. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3807. var result = optionalTarget || new THREE.Vector3();
  3808. // colinear or singular triangle
  3809. if( denom == 0 ) {
  3810. // arbitrary location outside of triangle?
  3811. // not sure if this is the best idea, maybe should be returning undefined
  3812. return result.set( -2, -1, -1 );
  3813. }
  3814. var invDenom = 1 / denom;
  3815. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3816. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3817. // barycoordinates must always sum to 1
  3818. return result.set( 1 - u - v, v, u );
  3819. };
  3820. }();
  3821. THREE.Triangle.containsPoint = function() {
  3822. var v1 = new THREE.Vector3();
  3823. return function ( point, a, b, c ) {
  3824. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3825. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3826. };
  3827. }();
  3828. THREE.Triangle.prototype = {
  3829. constructor: THREE.Triangle,
  3830. set: function ( a, b, c ) {
  3831. this.a.copy( a );
  3832. this.b.copy( b );
  3833. this.c.copy( c );
  3834. return this;
  3835. },
  3836. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3837. this.a.copy( points[i0] );
  3838. this.b.copy( points[i1] );
  3839. this.c.copy( points[i2] );
  3840. return this;
  3841. },
  3842. copy: function ( triangle ) {
  3843. this.a.copy( triangle.a );
  3844. this.b.copy( triangle.b );
  3845. this.c.copy( triangle.c );
  3846. return this;
  3847. },
  3848. area: function() {
  3849. var v0 = new THREE.Vector3();
  3850. var v1 = new THREE.Vector3();
  3851. return function () {
  3852. v0.subVectors( this.c, this.b );
  3853. v1.subVectors( this.a, this.b );
  3854. return v0.cross( v1 ).length() * 0.5;
  3855. };
  3856. }(),
  3857. midpoint: function ( optionalTarget ) {
  3858. var result = optionalTarget || new THREE.Vector3();
  3859. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3860. },
  3861. normal: function ( optionalTarget ) {
  3862. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3863. },
  3864. plane: function ( optionalTarget ) {
  3865. var result = optionalTarget || new THREE.Plane();
  3866. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3867. },
  3868. barycoordFromPoint: function ( point, optionalTarget ) {
  3869. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3870. },
  3871. containsPoint: function ( point ) {
  3872. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3873. },
  3874. equals: function ( triangle ) {
  3875. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3876. },
  3877. clone: function () {
  3878. return new THREE.Triangle().copy( this );
  3879. }
  3880. };
  3881. /**
  3882. * @author mrdoob / http://mrdoob.com/
  3883. */
  3884. THREE.Vertex = function ( v ) {
  3885. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3886. return v;
  3887. };
  3888. /**
  3889. * @author mrdoob / http://mrdoob.com/
  3890. */
  3891. THREE.UV = function ( u, v ) {
  3892. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3893. return new THREE.Vector2( u, v );
  3894. };
  3895. /**
  3896. * @author alteredq / http://alteredqualia.com/
  3897. */
  3898. THREE.Clock = function ( autoStart ) {
  3899. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3900. this.startTime = 0;
  3901. this.oldTime = 0;
  3902. this.elapsedTime = 0;
  3903. this.running = false;
  3904. };
  3905. THREE.Clock.prototype = {
  3906. constructor: THREE.Clock,
  3907. start: function () {
  3908. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3909. ? self.performance.now()
  3910. : Date.now();
  3911. this.oldTime = this.startTime;
  3912. this.running = true;
  3913. },
  3914. stop: function () {
  3915. this.getElapsedTime();
  3916. this.running = false;
  3917. },
  3918. getElapsedTime: function () {
  3919. this.getDelta();
  3920. return this.elapsedTime;
  3921. },
  3922. getDelta: function () {
  3923. var diff = 0;
  3924. if ( this.autoStart && ! this.running ) {
  3925. this.start();
  3926. }
  3927. if ( this.running ) {
  3928. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3929. ? self.performance.now()
  3930. : Date.now();
  3931. diff = 0.001 * ( newTime - this.oldTime );
  3932. this.oldTime = newTime;
  3933. this.elapsedTime += diff;
  3934. }
  3935. return diff;
  3936. }
  3937. };
  3938. /**
  3939. * https://github.com/mrdoob/eventdispatcher.js/
  3940. */
  3941. THREE.EventDispatcher = function () {}
  3942. THREE.EventDispatcher.prototype = {
  3943. constructor: THREE.EventDispatcher,
  3944. apply: function ( object ) {
  3945. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  3946. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  3947. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  3948. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  3949. },
  3950. addEventListener: function ( type, listener ) {
  3951. if ( this._listeners === undefined ) this._listeners = {};
  3952. var listeners = this._listeners;
  3953. if ( listeners[ type ] === undefined ) {
  3954. listeners[ type ] = [];
  3955. }
  3956. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3957. listeners[ type ].push( listener );
  3958. }
  3959. },
  3960. hasEventListener: function ( type, listener ) {
  3961. if ( this._listeners === undefined ) return false;
  3962. var listeners = this._listeners;
  3963. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3964. return true;
  3965. }
  3966. return false;
  3967. },
  3968. removeEventListener: function ( type, listener ) {
  3969. if ( this._listeners === undefined ) return;
  3970. var listeners = this._listeners;
  3971. var listenerArray = listeners[ type ];
  3972. if ( listenerArray !== undefined ) {
  3973. var index = listenerArray.indexOf( listener );
  3974. if ( index !== - 1 ) {
  3975. listenerArray.splice( index, 1 );
  3976. }
  3977. }
  3978. },
  3979. dispatchEvent: function () {
  3980. var array = [];
  3981. return function ( event ) {
  3982. if ( this._listeners === undefined ) return;
  3983. var listeners = this._listeners;
  3984. var listenerArray = listeners[ event.type ];
  3985. if ( listenerArray !== undefined ) {
  3986. event.target = this;
  3987. var length = listenerArray.length;
  3988. for ( var i = 0; i < length; i ++ ) {
  3989. array[ i ] = listenerArray[ i ];
  3990. }
  3991. for ( var i = 0; i < length; i ++ ) {
  3992. array[ i ].call( this, event );
  3993. }
  3994. }
  3995. };
  3996. }()
  3997. };
  3998. /**
  3999. * @author mrdoob / http://mrdoob.com/
  4000. * @author bhouston / http://exocortex.com/
  4001. * @author stephomi / http://stephaneginier.com/
  4002. */
  4003. ( function ( THREE ) {
  4004. THREE.Raycaster = function ( origin, direction, near, far ) {
  4005. this.ray = new THREE.Ray( origin, direction );
  4006. // direction is assumed to be normalized (for accurate distance calculations)
  4007. this.near = near || 0;
  4008. this.far = far || Infinity;
  4009. };
  4010. var sphere = new THREE.Sphere();
  4011. var localRay = new THREE.Ray();
  4012. var facePlane = new THREE.Plane();
  4013. var intersectPoint = new THREE.Vector3();
  4014. var matrixPosition = new THREE.Vector3();
  4015. var inverseMatrix = new THREE.Matrix4();
  4016. var descSort = function ( a, b ) {
  4017. return a.distance - b.distance;
  4018. };
  4019. var vA = new THREE.Vector3();
  4020. var vB = new THREE.Vector3();
  4021. var vC = new THREE.Vector3();
  4022. var intersectObject = function ( object, raycaster, intersects ) {
  4023. if ( object instanceof THREE.Sprite ) {
  4024. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4025. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4026. if ( distance > object.scale.x ) {
  4027. return intersects;
  4028. }
  4029. intersects.push( {
  4030. distance: distance,
  4031. point: object.position,
  4032. face: null,
  4033. object: object
  4034. } );
  4035. } else if ( object instanceof THREE.LOD ) {
  4036. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4037. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4038. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4039. } else if ( object instanceof THREE.Mesh ) {
  4040. var geometry = object.geometry;
  4041. // Checking boundingSphere distance to ray
  4042. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4043. sphere.copy( geometry.boundingSphere );
  4044. sphere.applyMatrix4( object.matrixWorld );
  4045. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4046. return intersects;
  4047. }
  4048. // Check boundingBox before continuing
  4049. inverseMatrix.getInverse( object.matrixWorld );
  4050. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4051. if ( geometry.boundingBox !== null ) {
  4052. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4053. return intersects;
  4054. }
  4055. }
  4056. if ( geometry instanceof THREE.BufferGeometry ) {
  4057. var material = object.material;
  4058. if ( material === undefined ) return intersects;
  4059. if ( geometry.dynamic === false ) return intersects;
  4060. var a, b, c;
  4061. var precision = raycaster.precision;
  4062. if ( geometry.attributes.index !== undefined ) {
  4063. var offsets = geometry.offsets;
  4064. var indices = geometry.attributes.index.array;
  4065. var positions = geometry.attributes.position.array;
  4066. var offLength = geometry.offsets.length;
  4067. var fl = geometry.attributes.index.array.length / 3;
  4068. for ( var oi = 0; oi < offLength; ++oi ) {
  4069. var start = offsets[ oi ].start;
  4070. var count = offsets[ oi ].count;
  4071. var index = offsets[ oi ].index;
  4072. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4073. a = index + indices[ i ];
  4074. b = index + indices[ i + 1 ];
  4075. c = index + indices[ i + 2 ];
  4076. vA.set(
  4077. positions[ a * 3 ],
  4078. positions[ a * 3 + 1 ],
  4079. positions[ a * 3 + 2 ]
  4080. );
  4081. vB.set(
  4082. positions[ b * 3 ],
  4083. positions[ b * 3 + 1 ],
  4084. positions[ b * 3 + 2 ]
  4085. );
  4086. vC.set(
  4087. positions[ c * 3 ],
  4088. positions[ c * 3 + 1 ],
  4089. positions[ c * 3 + 2 ]
  4090. );
  4091. if ( material.side === THREE.BackSide ) {
  4092. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4093. } else {
  4094. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4095. }
  4096. if ( intersectionPoint === null ) continue;
  4097. intersectionPoint.applyMatrix4( object.matrixWorld );
  4098. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4099. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4100. intersects.push( {
  4101. distance: distance,
  4102. point: intersectionPoint,
  4103. face: null,
  4104. faceIndex: null,
  4105. object: object
  4106. } );
  4107. }
  4108. }
  4109. } else {
  4110. var offsets = geometry.offsets;
  4111. var positions = geometry.attributes.position.array;
  4112. var offLength = geometry.offsets.length;
  4113. var fl = geometry.attributes.position.array.length;
  4114. for ( var i = 0; i < fl; i += 3 ) {
  4115. a = i;
  4116. b = i + 1;
  4117. c = i + 2;
  4118. vA.set(
  4119. positions[ a * 3 ],
  4120. positions[ a * 3 + 1 ],
  4121. positions[ a * 3 + 2 ]
  4122. );
  4123. vB.set(
  4124. positions[ b * 3 ],
  4125. positions[ b * 3 + 1 ],
  4126. positions[ b * 3 + 2 ]
  4127. );
  4128. vC.set(
  4129. positions[ c * 3 ],
  4130. positions[ c * 3 + 1 ],
  4131. positions[ c * 3 + 2 ]
  4132. );
  4133. if ( material.side === THREE.BackSide ) {
  4134. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4135. } else {
  4136. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4137. }
  4138. if ( intersectionPoint === null ) continue;
  4139. intersectionPoint.applyMatrix4( object.matrixWorld );
  4140. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4141. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4142. intersects.push( {
  4143. distance: distance,
  4144. point: intersectionPoint,
  4145. face: null,
  4146. faceIndex: null,
  4147. object: object
  4148. } );
  4149. }
  4150. }
  4151. } else if ( geometry instanceof THREE.Geometry ) {
  4152. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4153. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4154. var a, b, c, d;
  4155. var precision = raycaster.precision;
  4156. var vertices = geometry.vertices;
  4157. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4158. var face = geometry.faces[ f ];
  4159. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4160. if ( material === undefined ) continue;
  4161. a = vertices[ face.a ];
  4162. b = vertices[ face.b ];
  4163. c = vertices[ face.c ];
  4164. if ( material.side === THREE.BackSide ) {
  4165. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4166. } else {
  4167. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4168. }
  4169. if ( intersectionPoint === null ) continue;
  4170. intersectionPoint.applyMatrix4( object.matrixWorld );
  4171. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4172. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4173. intersects.push( {
  4174. distance: distance,
  4175. point: intersectionPoint,
  4176. face: face,
  4177. faceIndex: f,
  4178. object: object
  4179. } );
  4180. }
  4181. }
  4182. } else if ( object instanceof THREE.Line ) {
  4183. var precision = raycaster.linePrecision;
  4184. var precisionSq = precision * precision;
  4185. var geometry = object.geometry;
  4186. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4187. // Checking boundingSphere distance to ray
  4188. sphere.copy( geometry.boundingSphere );
  4189. sphere.applyMatrix4( object.matrixWorld );
  4190. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4191. return intersects;
  4192. }
  4193. inverseMatrix.getInverse( object.matrixWorld );
  4194. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4195. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4196. } else */ if ( geometry instanceof THREE.Geometry ) {
  4197. var vertices = geometry.vertices;
  4198. var nbVertices = vertices.length;
  4199. var interSegment = new THREE.Vector3();
  4200. var interRay = new THREE.Vector3();
  4201. var step = object.type === THREE.LineStrip ? 1 : 2;
  4202. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4203. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4204. if ( distSq > precisionSq ) continue;
  4205. var distance = localRay.origin.distanceTo( interRay );
  4206. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4207. intersects.push( {
  4208. distance: distance,
  4209. // What do we want? intersection point on the ray or on the segment??
  4210. // point: raycaster.ray.at( distance ),
  4211. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4212. face: null,
  4213. faceIndex: null,
  4214. object: object
  4215. } );
  4216. }
  4217. }
  4218. }
  4219. };
  4220. var intersectDescendants = function ( object, raycaster, intersects ) {
  4221. var descendants = object.getDescendants();
  4222. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4223. intersectObject( descendants[ i ], raycaster, intersects );
  4224. }
  4225. };
  4226. //
  4227. THREE.Raycaster.prototype.precision = 0.0001;
  4228. THREE.Raycaster.prototype.linePrecision = 1;
  4229. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4230. this.ray.set( origin, direction );
  4231. // direction is assumed to be normalized (for accurate distance calculations)
  4232. };
  4233. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4234. var intersects = [];
  4235. if ( recursive === true ) {
  4236. intersectDescendants( object, this, intersects );
  4237. }
  4238. intersectObject( object, this, intersects );
  4239. intersects.sort( descSort );
  4240. return intersects;
  4241. };
  4242. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4243. var intersects = [];
  4244. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4245. intersectObject( objects[ i ], this, intersects );
  4246. if ( recursive === true ) {
  4247. intersectDescendants( objects[ i ], this, intersects );
  4248. }
  4249. }
  4250. intersects.sort( descSort );
  4251. return intersects;
  4252. };
  4253. }( THREE ) );
  4254. /**
  4255. * @author mrdoob / http://mrdoob.com/
  4256. * @author mikael emtinger / http://gomo.se/
  4257. * @author alteredq / http://alteredqualia.com/
  4258. * @author WestLangley / http://github.com/WestLangley
  4259. */
  4260. THREE.Object3D = function () {
  4261. this.id = THREE.Object3DIdCount ++;
  4262. this.uuid = THREE.Math.generateUUID();
  4263. this.name = '';
  4264. this.parent = undefined;
  4265. this.children = [];
  4266. this.up = new THREE.Vector3( 0, 1, 0 );
  4267. this.position = new THREE.Vector3();
  4268. this._rotation = new THREE.Euler();
  4269. this._quaternion = new THREE.Quaternion();
  4270. this.scale = new THREE.Vector3( 1, 1, 1 );
  4271. // keep rotation and quaternion in sync
  4272. this._rotation._quaternion = this.quaternion;
  4273. this._quaternion._euler = this.rotation;
  4274. this.renderDepth = null;
  4275. this.rotationAutoUpdate = true;
  4276. this.matrix = new THREE.Matrix4();
  4277. this.matrixWorld = new THREE.Matrix4();
  4278. this.matrixAutoUpdate = true;
  4279. this.matrixWorldNeedsUpdate = true;
  4280. this.visible = true;
  4281. this.castShadow = false;
  4282. this.receiveShadow = false;
  4283. this.frustumCulled = true;
  4284. this.userData = {};
  4285. };
  4286. THREE.Object3D.prototype = {
  4287. constructor: THREE.Object3D,
  4288. get rotation () {
  4289. return this._rotation;
  4290. },
  4291. set rotation ( value ) {
  4292. this._rotation = value;
  4293. this._rotation._quaternion = this._quaternion;
  4294. this._quaternion._euler = this._rotation;
  4295. this._rotation._updateQuaternion();
  4296. },
  4297. get quaternion () {
  4298. return this._quaternion;
  4299. },
  4300. set quaternion ( value ) {
  4301. this._quaternion = value;
  4302. this._quaternion._euler = this._rotation;
  4303. this._rotation._quaternion = this._quaternion;
  4304. this._quaternion._updateEuler();
  4305. },
  4306. get eulerOrder () {
  4307. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4308. return this.rotation.order;
  4309. },
  4310. set eulerOrder ( value ) {
  4311. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4312. this.rotation.order = value;
  4313. },
  4314. get useQuaternion () {
  4315. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4316. },
  4317. set useQuaternion ( value ) {
  4318. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4319. },
  4320. applyMatrix: function () {
  4321. var m1 = new THREE.Matrix4();
  4322. return function ( matrix ) {
  4323. this.matrix.multiplyMatrices( matrix, this.matrix );
  4324. this.position.setFromMatrixPosition( this.matrix );
  4325. this.scale.setFromMatrixScale( this.matrix );
  4326. m1.extractRotation( this.matrix );
  4327. this.quaternion.setFromRotationMatrix( m1 );
  4328. }
  4329. }(),
  4330. setRotationFromAxisAngle: function ( axis, angle ) {
  4331. // assumes axis is normalized
  4332. this.quaternion.setFromAxisAngle( axis, angle );
  4333. },
  4334. setRotationFromEuler: function ( euler ) {
  4335. this.quaternion.setFromEuler( euler, true );
  4336. },
  4337. setRotationFromMatrix: function ( m ) {
  4338. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4339. this.quaternion.setFromRotationMatrix( m );
  4340. },
  4341. setRotationFromQuaternion: function ( q ) {
  4342. // assumes q is normalized
  4343. this.quaternion.copy( q );
  4344. },
  4345. rotateOnAxis: function() {
  4346. // rotate object on axis in object space
  4347. // axis is assumed to be normalized
  4348. var q1 = new THREE.Quaternion();
  4349. return function ( axis, angle ) {
  4350. q1.setFromAxisAngle( axis, angle );
  4351. this.quaternion.multiply( q1 );
  4352. return this;
  4353. }
  4354. }(),
  4355. rotateX: function () {
  4356. var v1 = new THREE.Vector3( 1, 0, 0 );
  4357. return function ( angle ) {
  4358. return this.rotateOnAxis( v1, angle );
  4359. };
  4360. }(),
  4361. rotateY: function () {
  4362. var v1 = new THREE.Vector3( 0, 1, 0 );
  4363. return function ( angle ) {
  4364. return this.rotateOnAxis( v1, angle );
  4365. };
  4366. }(),
  4367. rotateZ: function () {
  4368. var v1 = new THREE.Vector3( 0, 0, 1 );
  4369. return function ( angle ) {
  4370. return this.rotateOnAxis( v1, angle );
  4371. };
  4372. }(),
  4373. translateOnAxis: function () {
  4374. // translate object by distance along axis in object space
  4375. // axis is assumed to be normalized
  4376. var v1 = new THREE.Vector3();
  4377. return function ( axis, distance ) {
  4378. v1.copy( axis );
  4379. v1.applyQuaternion( this.quaternion );
  4380. this.position.add( v1.multiplyScalar( distance ) );
  4381. return this;
  4382. }
  4383. }(),
  4384. translate: function ( distance, axis ) {
  4385. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4386. return this.translateOnAxis( axis, distance );
  4387. },
  4388. translateX: function () {
  4389. var v1 = new THREE.Vector3( 1, 0, 0 );
  4390. return function ( distance ) {
  4391. return this.translateOnAxis( v1, distance );
  4392. };
  4393. }(),
  4394. translateY: function () {
  4395. var v1 = new THREE.Vector3( 0, 1, 0 );
  4396. return function ( distance ) {
  4397. return this.translateOnAxis( v1, distance );
  4398. };
  4399. }(),
  4400. translateZ: function () {
  4401. var v1 = new THREE.Vector3( 0, 0, 1 );
  4402. return function ( distance ) {
  4403. return this.translateOnAxis( v1, distance );
  4404. };
  4405. }(),
  4406. localToWorld: function ( vector ) {
  4407. return vector.applyMatrix4( this.matrixWorld );
  4408. },
  4409. worldToLocal: function () {
  4410. var m1 = new THREE.Matrix4();
  4411. return function ( vector ) {
  4412. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4413. };
  4414. }(),
  4415. lookAt: function () {
  4416. // This routine does not support objects with rotated and/or translated parent(s)
  4417. var m1 = new THREE.Matrix4();
  4418. return function ( vector ) {
  4419. m1.lookAt( vector, this.position, this.up );
  4420. this.quaternion.setFromRotationMatrix( m1 );
  4421. };
  4422. }(),
  4423. add: function ( object ) {
  4424. if ( object === this ) {
  4425. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4426. return;
  4427. }
  4428. if ( object instanceof THREE.Object3D ) {
  4429. if ( object.parent !== undefined ) {
  4430. object.parent.remove( object );
  4431. }
  4432. object.parent = this;
  4433. object.dispatchEvent( { type: 'added' } );
  4434. this.children.push( object );
  4435. // add to 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.__addObject( object );
  4442. }
  4443. }
  4444. },
  4445. remove: function ( object ) {
  4446. var index = this.children.indexOf( object );
  4447. if ( index !== - 1 ) {
  4448. object.parent = undefined;
  4449. object.dispatchEvent( { type: 'removed' } );
  4450. this.children.splice( index, 1 );
  4451. // remove from scene
  4452. var scene = this;
  4453. while ( scene.parent !== undefined ) {
  4454. scene = scene.parent;
  4455. }
  4456. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4457. scene.__removeObject( object );
  4458. }
  4459. }
  4460. },
  4461. traverse: function ( callback ) {
  4462. callback( this );
  4463. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4464. this.children[ i ].traverse( callback );
  4465. }
  4466. },
  4467. getObjectById: function ( id, recursive ) {
  4468. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4469. var child = this.children[ i ];
  4470. if ( child.id === id ) {
  4471. return child;
  4472. }
  4473. if ( recursive === true ) {
  4474. child = child.getObjectById( id, recursive );
  4475. if ( child !== undefined ) {
  4476. return child;
  4477. }
  4478. }
  4479. }
  4480. return undefined;
  4481. },
  4482. getObjectByName: function ( name, recursive ) {
  4483. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4484. var child = this.children[ i ];
  4485. if ( child.name === name ) {
  4486. return child;
  4487. }
  4488. if ( recursive === true ) {
  4489. child = child.getObjectByName( name, recursive );
  4490. if ( child !== undefined ) {
  4491. return child;
  4492. }
  4493. }
  4494. }
  4495. return undefined;
  4496. },
  4497. getChildByName: function ( name, recursive ) {
  4498. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4499. return this.getObjectByName( name, recursive );
  4500. },
  4501. getDescendants: function ( array ) {
  4502. if ( array === undefined ) array = [];
  4503. Array.prototype.push.apply( array, this.children );
  4504. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4505. this.children[ i ].getDescendants( array );
  4506. }
  4507. return array;
  4508. },
  4509. updateMatrix: function () {
  4510. this.matrix.compose( this.position, this.quaternion, this.scale );
  4511. this.matrixWorldNeedsUpdate = true;
  4512. },
  4513. updateMatrixWorld: function ( force ) {
  4514. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4515. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4516. if ( this.parent === undefined ) {
  4517. this.matrixWorld.copy( this.matrix );
  4518. } else {
  4519. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4520. }
  4521. this.matrixWorldNeedsUpdate = false;
  4522. force = true;
  4523. }
  4524. // update children
  4525. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4526. this.children[ i ].updateMatrixWorld( force );
  4527. }
  4528. },
  4529. clone: function ( object, recursive ) {
  4530. if ( object === undefined ) object = new THREE.Object3D();
  4531. if ( recursive === undefined ) recursive = true;
  4532. object.name = this.name;
  4533. object.up.copy( this.up );
  4534. object.position.copy( this.position );
  4535. object.quaternion.copy( this.quaternion );
  4536. object.scale.copy( this.scale );
  4537. object.renderDepth = this.renderDepth;
  4538. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4539. object.matrix.copy( this.matrix );
  4540. object.matrixWorld.copy( this.matrixWorld );
  4541. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4542. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4543. object.visible = this.visible;
  4544. object.castShadow = this.castShadow;
  4545. object.receiveShadow = this.receiveShadow;
  4546. object.frustumCulled = this.frustumCulled;
  4547. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4548. if ( recursive === true ) {
  4549. for ( var i = 0; i < this.children.length; i ++ ) {
  4550. var child = this.children[ i ];
  4551. object.add( child.clone() );
  4552. }
  4553. }
  4554. return object;
  4555. }
  4556. };
  4557. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4558. THREE.Object3DIdCount = 0;
  4559. /**
  4560. * @author mrdoob / http://mrdoob.com/
  4561. * @author supereggbert / http://www.paulbrunt.co.uk/
  4562. * @author julianwa / https://github.com/julianwa
  4563. */
  4564. THREE.Projector = function () {
  4565. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4566. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4567. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4568. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4569. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4570. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4571. _vector3 = new THREE.Vector3(),
  4572. _vector4 = new THREE.Vector4(),
  4573. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4574. _boundingBox = new THREE.Box3(),
  4575. _points3 = new Array( 3 ),
  4576. _points4 = new Array( 4 ),
  4577. _viewMatrix = new THREE.Matrix4(),
  4578. _viewProjectionMatrix = new THREE.Matrix4(),
  4579. _modelMatrix,
  4580. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4581. _normalMatrix = new THREE.Matrix3(),
  4582. _normalViewMatrix = new THREE.Matrix3(),
  4583. _centroid = new THREE.Vector3(),
  4584. _frustum = new THREE.Frustum(),
  4585. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4586. _clippedVertex2PositionScreen = new THREE.Vector4();
  4587. this.projectVector = function ( vector, camera ) {
  4588. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4589. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4590. return vector.applyProjection( _viewProjectionMatrix );
  4591. };
  4592. this.unprojectVector = function ( vector, camera ) {
  4593. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4594. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4595. return vector.applyProjection( _viewProjectionMatrix );
  4596. };
  4597. this.pickingRay = function ( vector, camera ) {
  4598. // set two vectors with opposing z values
  4599. vector.z = -1.0;
  4600. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4601. this.unprojectVector( vector, camera );
  4602. this.unprojectVector( end, camera );
  4603. // find direction from vector to end
  4604. end.sub( vector ).normalize();
  4605. return new THREE.Raycaster( vector, end );
  4606. };
  4607. var getObject = function ( object ) {
  4608. _object = getNextObjectInPool();
  4609. _object.id = object.id;
  4610. _object.object = object;
  4611. if ( object.renderDepth !== null ) {
  4612. _object.z = object.renderDepth;
  4613. } else {
  4614. _vector3.setFromMatrixPosition( object.matrixWorld );
  4615. _vector3.applyProjection( _viewProjectionMatrix );
  4616. _object.z = _vector3.z;
  4617. }
  4618. return _object;
  4619. };
  4620. var projectObject = function ( object ) {
  4621. if ( object.visible === false ) return;
  4622. if ( object instanceof THREE.Light ) {
  4623. _renderData.lights.push( object );
  4624. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4625. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4626. _renderData.objects.push( getObject( object ) );
  4627. }
  4628. } else if ( object instanceof THREE.Sprite ) {
  4629. _renderData.sprites.push( getObject( object ) );
  4630. }
  4631. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4632. projectObject( object.children[ i ] );
  4633. }
  4634. };
  4635. var projectGraph = function ( root, sortObjects ) {
  4636. _objectCount = 0;
  4637. _renderData.objects.length = 0;
  4638. _renderData.sprites.length = 0;
  4639. _renderData.lights.length = 0;
  4640. projectObject( root );
  4641. if ( sortObjects === true ) {
  4642. _renderData.objects.sort( painterSort );
  4643. }
  4644. };
  4645. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4646. var visible = false,
  4647. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4648. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4649. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4650. _face3Count = 0;
  4651. _lineCount = 0;
  4652. _spriteCount = 0;
  4653. _renderData.elements.length = 0;
  4654. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4655. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4656. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4657. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4658. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4659. _frustum.setFromMatrix( _viewProjectionMatrix );
  4660. projectGraph( scene, sortObjects );
  4661. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4662. object = _renderData.objects[ o ].object;
  4663. _modelMatrix = object.matrixWorld;
  4664. _vertexCount = 0;
  4665. if ( object instanceof THREE.Mesh ) {
  4666. geometry = object.geometry;
  4667. vertices = geometry.vertices;
  4668. faces = geometry.faces;
  4669. faceVertexUvs = geometry.faceVertexUvs;
  4670. _normalMatrix.getNormalMatrix( _modelMatrix );
  4671. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4672. objectMaterials = isFaceMaterial === true ? object.material : null;
  4673. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4674. _vertex = getNextVertexInPool();
  4675. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4676. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4677. var invW = 1 / _vertex.positionScreen.w;
  4678. _vertex.positionScreen.x *= invW;
  4679. _vertex.positionScreen.y *= invW;
  4680. _vertex.positionScreen.z *= invW;
  4681. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4682. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4683. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4684. }
  4685. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4686. face = faces[ f ];
  4687. var material = isFaceMaterial === true
  4688. ? objectMaterials.materials[ face.materialIndex ]
  4689. : object.material;
  4690. if ( material === undefined ) continue;
  4691. var side = material.side;
  4692. v1 = _vertexPool[ face.a ];
  4693. v2 = _vertexPool[ face.b ];
  4694. v3 = _vertexPool[ face.c ];
  4695. _points3[ 0 ] = v1.positionScreen;
  4696. _points3[ 1 ] = v2.positionScreen;
  4697. _points3[ 2 ] = v3.positionScreen;
  4698. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4699. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4700. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4701. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4702. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4703. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4704. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4705. _face = getNextFace3InPool();
  4706. _face.id = object.id;
  4707. _face.v1.copy( v1 );
  4708. _face.v2.copy( v2 );
  4709. _face.v3.copy( v3 );
  4710. } else {
  4711. continue;
  4712. }
  4713. } else {
  4714. continue;
  4715. }
  4716. _face.normalModel.copy( face.normal );
  4717. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4718. _face.normalModel.negate();
  4719. }
  4720. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4721. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4722. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4723. faceVertexNormals = face.vertexNormals;
  4724. for ( n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4725. var normalModel = _face.vertexNormalsModel[ n ];
  4726. normalModel.copy( faceVertexNormals[ n ] );
  4727. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4728. normalModel.negate();
  4729. }
  4730. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4731. var normalModelView = _face.vertexNormalsModelView[ n ];
  4732. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4733. }
  4734. _face.vertexNormalsLength = faceVertexNormals.length;
  4735. for ( c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4736. uvs = faceVertexUvs[ c ][ f ];
  4737. if ( uvs === undefined ) continue;
  4738. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4739. _face.uvs[ c ][ u ] = uvs[ u ];
  4740. }
  4741. }
  4742. _face.color = face.color;
  4743. _face.material = material;
  4744. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4745. _face.z = _centroid.z;
  4746. _renderData.elements.push( _face );
  4747. }
  4748. } else if ( object instanceof THREE.Line ) {
  4749. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4750. vertices = object.geometry.vertices;
  4751. v1 = getNextVertexInPool();
  4752. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4753. // Handle LineStrip and LinePieces
  4754. var step = object.type === THREE.LinePieces ? 2 : 1;
  4755. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4756. v1 = getNextVertexInPool();
  4757. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4758. if ( ( v + 1 ) % step > 0 ) continue;
  4759. v2 = _vertexPool[ _vertexCount - 2 ];
  4760. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4761. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4762. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4763. // Perform the perspective divide
  4764. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4765. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4766. _line = getNextLineInPool();
  4767. _line.id = object.id;
  4768. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4769. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4770. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4771. _line.material = object.material;
  4772. if ( object.material.vertexColors === THREE.VertexColors ) {
  4773. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4774. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4775. }
  4776. _renderData.elements.push( _line );
  4777. }
  4778. }
  4779. }
  4780. }
  4781. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4782. object = _renderData.sprites[ o ].object;
  4783. _modelMatrix = object.matrixWorld;
  4784. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4785. _vector4.applyMatrix4( _viewProjectionMatrix );
  4786. var invW = 1 / _vector4.w;
  4787. _vector4.z *= invW;
  4788. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  4789. _sprite = getNextSpriteInPool();
  4790. _sprite.id = object.id;
  4791. _sprite.x = _vector4.x * invW;
  4792. _sprite.y = _vector4.y * invW;
  4793. _sprite.z = _vector4.z;
  4794. _sprite.object = object;
  4795. _sprite.rotation = object.rotation;
  4796. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4797. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4798. _sprite.material = object.material;
  4799. _renderData.elements.push( _sprite );
  4800. }
  4801. }
  4802. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4803. return _renderData;
  4804. };
  4805. // Pools
  4806. function getNextObjectInPool() {
  4807. if ( _objectCount === _objectPoolLength ) {
  4808. var object = new THREE.RenderableObject();
  4809. _objectPool.push( object );
  4810. _objectPoolLength ++;
  4811. _objectCount ++;
  4812. return object;
  4813. }
  4814. return _objectPool[ _objectCount ++ ];
  4815. }
  4816. function getNextVertexInPool() {
  4817. if ( _vertexCount === _vertexPoolLength ) {
  4818. var vertex = new THREE.RenderableVertex();
  4819. _vertexPool.push( vertex );
  4820. _vertexPoolLength ++;
  4821. _vertexCount ++;
  4822. return vertex;
  4823. }
  4824. return _vertexPool[ _vertexCount ++ ];
  4825. }
  4826. function getNextFace3InPool() {
  4827. if ( _face3Count === _face3PoolLength ) {
  4828. var face = new THREE.RenderableFace3();
  4829. _face3Pool.push( face );
  4830. _face3PoolLength ++;
  4831. _face3Count ++;
  4832. return face;
  4833. }
  4834. return _face3Pool[ _face3Count ++ ];
  4835. }
  4836. function getNextLineInPool() {
  4837. if ( _lineCount === _linePoolLength ) {
  4838. var line = new THREE.RenderableLine();
  4839. _linePool.push( line );
  4840. _linePoolLength ++;
  4841. _lineCount ++
  4842. return line;
  4843. }
  4844. return _linePool[ _lineCount ++ ];
  4845. }
  4846. function getNextSpriteInPool() {
  4847. if ( _spriteCount === _spritePoolLength ) {
  4848. var sprite = new THREE.RenderableSprite();
  4849. _spritePool.push( sprite );
  4850. _spritePoolLength ++;
  4851. _spriteCount ++
  4852. return sprite;
  4853. }
  4854. return _spritePool[ _spriteCount ++ ];
  4855. }
  4856. //
  4857. function painterSort( a, b ) {
  4858. if ( a.z !== b.z ) {
  4859. return b.z - a.z;
  4860. } else if ( a.id !== b.id ) {
  4861. return a.id - b.id;
  4862. } else {
  4863. return 0;
  4864. }
  4865. }
  4866. function clipLine( s1, s2 ) {
  4867. var alpha1 = 0, alpha2 = 1,
  4868. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4869. // Z = -1 and Z = +1, respectively.
  4870. bc1near = s1.z + s1.w,
  4871. bc2near = s2.z + s2.w,
  4872. bc1far = - s1.z + s1.w,
  4873. bc2far = - s2.z + s2.w;
  4874. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4875. // Both vertices lie entirely within all clip planes.
  4876. return true;
  4877. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4878. // Both vertices lie entirely outside one of the clip planes.
  4879. return false;
  4880. } else {
  4881. // The line segment spans at least one clip plane.
  4882. if ( bc1near < 0 ) {
  4883. // v1 lies outside the near plane, v2 inside
  4884. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4885. } else if ( bc2near < 0 ) {
  4886. // v2 lies outside the near plane, v1 inside
  4887. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4888. }
  4889. if ( bc1far < 0 ) {
  4890. // v1 lies outside the far plane, v2 inside
  4891. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4892. } else if ( bc2far < 0 ) {
  4893. // v2 lies outside the far plane, v2 inside
  4894. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4895. }
  4896. if ( alpha2 < alpha1 ) {
  4897. // The line segment spans two boundaries, but is outside both of them.
  4898. // (This can't happen when we're only clipping against just near/far but good
  4899. // to leave the check here for future usage if other clip planes are added.)
  4900. return false;
  4901. } else {
  4902. // Update the s1 and s2 vertices to match the clipped line segment.
  4903. s1.lerp( s2, alpha1 );
  4904. s2.lerp( s1, 1 - alpha2 );
  4905. return true;
  4906. }
  4907. }
  4908. }
  4909. };
  4910. /**
  4911. * @author mrdoob / http://mrdoob.com/
  4912. * @author alteredq / http://alteredqualia.com/
  4913. */
  4914. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4915. this.a = a;
  4916. this.b = b;
  4917. this.c = c;
  4918. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4919. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4920. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4921. this.vertexColors = color instanceof Array ? color : [];
  4922. this.vertexTangents = [];
  4923. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4924. this.centroid = new THREE.Vector3();
  4925. };
  4926. THREE.Face3.prototype = {
  4927. constructor: THREE.Face3,
  4928. clone: function () {
  4929. var face = new THREE.Face3( this.a, this.b, this.c );
  4930. face.normal.copy( this.normal );
  4931. face.color.copy( this.color );
  4932. face.centroid.copy( this.centroid );
  4933. face.materialIndex = this.materialIndex;
  4934. var i, il;
  4935. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4936. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4937. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4938. return face;
  4939. }
  4940. };
  4941. /**
  4942. * @author mrdoob / http://mrdoob.com/
  4943. */
  4944. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4945. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  4946. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  4947. };
  4948. /**
  4949. * @author mrdoob / http://mrdoob.com/
  4950. * @author kile / http://kile.stravaganza.org/
  4951. * @author alteredq / http://alteredqualia.com/
  4952. * @author mikael emtinger / http://gomo.se/
  4953. * @author zz85 / http://www.lab4games.net/zz85/blog
  4954. * @author bhouston / http://exocortex.com
  4955. */
  4956. THREE.Geometry = function () {
  4957. this.id = THREE.GeometryIdCount ++;
  4958. this.uuid = THREE.Math.generateUUID();
  4959. this.name = '';
  4960. this.vertices = [];
  4961. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  4962. this.faces = [];
  4963. this.faceVertexUvs = [[]];
  4964. this.morphTargets = [];
  4965. this.morphColors = [];
  4966. this.morphNormals = [];
  4967. this.skinWeights = [];
  4968. this.skinIndices = [];
  4969. this.lineDistances = [];
  4970. this.boundingBox = null;
  4971. this.boundingSphere = null;
  4972. this.hasTangents = false;
  4973. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4974. // update flags
  4975. this.verticesNeedUpdate = false;
  4976. this.elementsNeedUpdate = false;
  4977. this.uvsNeedUpdate = false;
  4978. this.normalsNeedUpdate = false;
  4979. this.tangentsNeedUpdate = false;
  4980. this.colorsNeedUpdate = false;
  4981. this.lineDistancesNeedUpdate = false;
  4982. this.buffersNeedUpdate = false;
  4983. };
  4984. THREE.Geometry.prototype = {
  4985. constructor: THREE.Geometry,
  4986. applyMatrix: function ( matrix ) {
  4987. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4988. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4989. var vertex = this.vertices[ i ];
  4990. vertex.applyMatrix4( matrix );
  4991. }
  4992. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4993. var face = this.faces[ i ];
  4994. face.normal.applyMatrix3( normalMatrix ).normalize();
  4995. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4996. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4997. }
  4998. face.centroid.applyMatrix4( matrix );
  4999. }
  5000. if ( this.boundingBox instanceof THREE.Box3 ) {
  5001. this.computeBoundingBox();
  5002. }
  5003. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5004. this.computeBoundingSphere();
  5005. }
  5006. },
  5007. computeCentroids: function () {
  5008. var f, fl, face;
  5009. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5010. face = this.faces[ f ];
  5011. face.centroid.set( 0, 0, 0 );
  5012. face.centroid.add( this.vertices[ face.a ] );
  5013. face.centroid.add( this.vertices[ face.b ] );
  5014. face.centroid.add( this.vertices[ face.c ] );
  5015. face.centroid.divideScalar( 3 );
  5016. }
  5017. },
  5018. computeFaceNormals: function () {
  5019. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5020. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5021. var face = this.faces[ f ];
  5022. var vA = this.vertices[ face.a ];
  5023. var vB = this.vertices[ face.b ];
  5024. var vC = this.vertices[ face.c ];
  5025. cb.subVectors( vC, vB );
  5026. ab.subVectors( vA, vB );
  5027. cb.cross( ab );
  5028. cb.normalize();
  5029. face.normal.copy( cb );
  5030. }
  5031. },
  5032. computeVertexNormals: function ( areaWeighted ) {
  5033. var v, vl, f, fl, face, vertices;
  5034. // create internal buffers for reuse when calling this method repeatedly
  5035. // (otherwise memory allocation / deallocation every frame is big resource hog)
  5036. if ( this.__tmpVertices === undefined ) {
  5037. this.__tmpVertices = new Array( this.vertices.length );
  5038. vertices = this.__tmpVertices;
  5039. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5040. vertices[ v ] = new THREE.Vector3();
  5041. }
  5042. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5043. face = this.faces[ f ];
  5044. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  5045. }
  5046. } else {
  5047. vertices = this.__tmpVertices;
  5048. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5049. vertices[ v ].set( 0, 0, 0 );
  5050. }
  5051. }
  5052. if ( areaWeighted ) {
  5053. // vertex normals weighted by triangle areas
  5054. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5055. var vA, vB, vC, vD;
  5056. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5057. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5058. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5059. face = this.faces[ f ];
  5060. vA = this.vertices[ face.a ];
  5061. vB = this.vertices[ face.b ];
  5062. vC = this.vertices[ face.c ];
  5063. cb.subVectors( vC, vB );
  5064. ab.subVectors( vA, vB );
  5065. cb.cross( ab );
  5066. vertices[ face.a ].add( cb );
  5067. vertices[ face.b ].add( cb );
  5068. vertices[ face.c ].add( cb );
  5069. }
  5070. } else {
  5071. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5072. face = this.faces[ f ];
  5073. vertices[ face.a ].add( face.normal );
  5074. vertices[ face.b ].add( face.normal );
  5075. vertices[ face.c ].add( face.normal );
  5076. }
  5077. }
  5078. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5079. vertices[ v ].normalize();
  5080. }
  5081. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5082. face = this.faces[ f ];
  5083. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  5084. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  5085. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  5086. }
  5087. },
  5088. computeMorphNormals: function () {
  5089. var i, il, f, fl, face;
  5090. // save original normals
  5091. // - create temp variables on first access
  5092. // otherwise just copy (for faster repeated calls)
  5093. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5094. face = this.faces[ f ];
  5095. if ( ! face.__originalFaceNormal ) {
  5096. face.__originalFaceNormal = face.normal.clone();
  5097. } else {
  5098. face.__originalFaceNormal.copy( face.normal );
  5099. }
  5100. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5101. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5102. if ( ! face.__originalVertexNormals[ i ] ) {
  5103. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5104. } else {
  5105. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5106. }
  5107. }
  5108. }
  5109. // use temp geometry to compute face and vertex normals for each morph
  5110. var tmpGeo = new THREE.Geometry();
  5111. tmpGeo.faces = this.faces;
  5112. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5113. // create on first access
  5114. if ( ! this.morphNormals[ i ] ) {
  5115. this.morphNormals[ i ] = {};
  5116. this.morphNormals[ i ].faceNormals = [];
  5117. this.morphNormals[ i ].vertexNormals = [];
  5118. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5119. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5120. var faceNormal, vertexNormals;
  5121. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5122. face = this.faces[ f ];
  5123. faceNormal = new THREE.Vector3();
  5124. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5125. dstNormalsFace.push( faceNormal );
  5126. dstNormalsVertex.push( vertexNormals );
  5127. }
  5128. }
  5129. var morphNormals = this.morphNormals[ i ];
  5130. // set vertices to morph target
  5131. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5132. // compute morph normals
  5133. tmpGeo.computeFaceNormals();
  5134. tmpGeo.computeVertexNormals();
  5135. // store morph normals
  5136. var faceNormal, vertexNormals;
  5137. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5138. face = this.faces[ f ];
  5139. faceNormal = morphNormals.faceNormals[ f ];
  5140. vertexNormals = morphNormals.vertexNormals[ f ];
  5141. faceNormal.copy( face.normal );
  5142. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5143. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5144. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5145. }
  5146. }
  5147. // restore original normals
  5148. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5149. face = this.faces[ f ];
  5150. face.normal = face.__originalFaceNormal;
  5151. face.vertexNormals = face.__originalVertexNormals;
  5152. }
  5153. },
  5154. computeTangents: function () {
  5155. // based on http://www.terathon.com/code/tangent.html
  5156. // tangents go to vertices
  5157. var f, fl, v, vl, i, il, vertexIndex,
  5158. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5159. x1, x2, y1, y2, z1, z2,
  5160. s1, s2, t1, t2, r, t, test,
  5161. tan1 = [], tan2 = [],
  5162. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5163. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5164. n = new THREE.Vector3(), w;
  5165. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5166. tan1[ v ] = new THREE.Vector3();
  5167. tan2[ v ] = new THREE.Vector3();
  5168. }
  5169. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5170. vA = context.vertices[ a ];
  5171. vB = context.vertices[ b ];
  5172. vC = context.vertices[ c ];
  5173. uvA = uv[ ua ];
  5174. uvB = uv[ ub ];
  5175. uvC = uv[ uc ];
  5176. x1 = vB.x - vA.x;
  5177. x2 = vC.x - vA.x;
  5178. y1 = vB.y - vA.y;
  5179. y2 = vC.y - vA.y;
  5180. z1 = vB.z - vA.z;
  5181. z2 = vC.z - vA.z;
  5182. s1 = uvB.x - uvA.x;
  5183. s2 = uvC.x - uvA.x;
  5184. t1 = uvB.y - uvA.y;
  5185. t2 = uvC.y - uvA.y;
  5186. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5187. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5188. ( t2 * y1 - t1 * y2 ) * r,
  5189. ( t2 * z1 - t1 * z2 ) * r );
  5190. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5191. ( s1 * y2 - s2 * y1 ) * r,
  5192. ( s1 * z2 - s2 * z1 ) * r );
  5193. tan1[ a ].add( sdir );
  5194. tan1[ b ].add( sdir );
  5195. tan1[ c ].add( sdir );
  5196. tan2[ a ].add( tdir );
  5197. tan2[ b ].add( tdir );
  5198. tan2[ c ].add( tdir );
  5199. }
  5200. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5201. face = this.faces[ f ];
  5202. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5203. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5204. }
  5205. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5206. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5207. face = this.faces[ f ];
  5208. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5209. n.copy( face.vertexNormals[ i ] );
  5210. vertexIndex = face[ faceIndex[ i ] ];
  5211. t = tan1[ vertexIndex ];
  5212. // Gram-Schmidt orthogonalize
  5213. tmp.copy( t );
  5214. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5215. // Calculate handedness
  5216. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5217. test = tmp2.dot( tan2[ vertexIndex ] );
  5218. w = (test < 0.0) ? -1.0 : 1.0;
  5219. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5220. }
  5221. }
  5222. this.hasTangents = true;
  5223. },
  5224. computeLineDistances: function ( ) {
  5225. var d = 0;
  5226. var vertices = this.vertices;
  5227. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5228. if ( i > 0 ) {
  5229. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5230. }
  5231. this.lineDistances[ i ] = d;
  5232. }
  5233. },
  5234. computeBoundingBox: function () {
  5235. if ( this.boundingBox === null ) {
  5236. this.boundingBox = new THREE.Box3();
  5237. }
  5238. this.boundingBox.setFromPoints( this.vertices );
  5239. },
  5240. computeBoundingSphere: function () {
  5241. if ( this.boundingSphere === null ) {
  5242. this.boundingSphere = new THREE.Sphere();
  5243. }
  5244. this.boundingSphere.setFromPoints( this.vertices );
  5245. },
  5246. /*
  5247. * Checks for duplicate vertices with hashmap.
  5248. * Duplicated vertices are removed
  5249. * and faces' vertices are updated.
  5250. */
  5251. mergeVertices: function () {
  5252. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5253. var unique = [], changes = [];
  5254. var v, key;
  5255. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5256. var precision = Math.pow( 10, precisionPoints );
  5257. var i,il, face;
  5258. var indices, k, j, jl, u;
  5259. // reset cache of vertices as it now will be changing.
  5260. this.__tmpVertices = undefined;
  5261. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5262. v = this.vertices[ i ];
  5263. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5264. if ( verticesMap[ key ] === undefined ) {
  5265. verticesMap[ key ] = i;
  5266. unique.push( this.vertices[ i ] );
  5267. changes[ i ] = unique.length - 1;
  5268. } else {
  5269. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5270. changes[ i ] = changes[ verticesMap[ key ] ];
  5271. }
  5272. };
  5273. // if faces are completely degenerate after merging vertices, we
  5274. // have to remove them from the geometry.
  5275. var faceIndicesToRemove = [];
  5276. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5277. face = this.faces[ i ];
  5278. face.a = changes[ face.a ];
  5279. face.b = changes[ face.b ];
  5280. face.c = changes[ face.c ];
  5281. indices = [ face.a, face.b, face.c ];
  5282. var dupIndex = -1;
  5283. // if any duplicate vertices are found in a Face3
  5284. // we have to remove the face as nothing can be saved
  5285. for ( var n = 0; n < 3; n ++ ) {
  5286. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5287. dupIndex = n;
  5288. faceIndicesToRemove.push( i );
  5289. break;
  5290. }
  5291. }
  5292. }
  5293. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5294. var idx = faceIndicesToRemove[ i ];
  5295. this.faces.splice( idx, 1 );
  5296. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5297. this.faceVertexUvs[ j ].splice( idx, 1 );
  5298. }
  5299. }
  5300. // Use unique set of vertices
  5301. var diff = this.vertices.length - unique.length;
  5302. this.vertices = unique;
  5303. return diff;
  5304. },
  5305. clone: function () {
  5306. var geometry = new THREE.Geometry();
  5307. var vertices = this.vertices;
  5308. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5309. geometry.vertices.push( vertices[ i ].clone() );
  5310. }
  5311. var faces = this.faces;
  5312. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5313. geometry.faces.push( faces[ i ].clone() );
  5314. }
  5315. var uvs = this.faceVertexUvs[ 0 ];
  5316. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5317. var uv = uvs[ i ], uvCopy = [];
  5318. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5319. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5320. }
  5321. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5322. }
  5323. return geometry;
  5324. },
  5325. dispose: function () {
  5326. this.dispatchEvent( { type: 'dispose' } );
  5327. }
  5328. };
  5329. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5330. THREE.GeometryIdCount = 0;
  5331. /**
  5332. * @author alteredq / http://alteredqualia.com/
  5333. */
  5334. THREE.BufferGeometry = function () {
  5335. this.id = THREE.GeometryIdCount ++;
  5336. this.uuid = THREE.Math.generateUUID();
  5337. this.name = '';
  5338. // attributes
  5339. this.attributes = {};
  5340. // attributes typed arrays are kept only if dynamic flag is set
  5341. this.dynamic = true;
  5342. // offsets for chunks when using indexed elements
  5343. this.offsets = [];
  5344. // boundings
  5345. this.boundingBox = null;
  5346. this.boundingSphere = null;
  5347. this.hasTangents = false;
  5348. // for compatibility
  5349. this.morphTargets = [];
  5350. };
  5351. THREE.BufferGeometry.prototype = {
  5352. constructor: THREE.BufferGeometry,
  5353. addAttribute: function( name, type, numItems, itemSize ) {
  5354. this.attributes[ name ] = {
  5355. itemSize: itemSize,
  5356. array: new type( numItems * itemSize )
  5357. };
  5358. },
  5359. applyMatrix: function ( matrix ) {
  5360. var positionArray;
  5361. var normalArray;
  5362. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5363. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5364. if ( positionArray !== undefined ) {
  5365. matrix.multiplyVector3Array( positionArray );
  5366. this.verticesNeedUpdate = true;
  5367. }
  5368. if ( normalArray !== undefined ) {
  5369. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5370. normalMatrix.multiplyVector3Array( normalArray );
  5371. this.normalizeNormals();
  5372. this.normalsNeedUpdate = true;
  5373. }
  5374. },
  5375. computeBoundingBox: function () {
  5376. if ( this.boundingBox === null ) {
  5377. this.boundingBox = new THREE.Box3();
  5378. }
  5379. var positions = this.attributes[ "position" ].array;
  5380. if ( positions ) {
  5381. var bb = this.boundingBox;
  5382. var x, y, z;
  5383. if( positions.length >= 3 ) {
  5384. bb.min.x = bb.max.x = positions[ 0 ];
  5385. bb.min.y = bb.max.y = positions[ 1 ];
  5386. bb.min.z = bb.max.z = positions[ 2 ];
  5387. }
  5388. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5389. x = positions[ i ];
  5390. y = positions[ i + 1 ];
  5391. z = positions[ i + 2 ];
  5392. // bounding box
  5393. if ( x < bb.min.x ) {
  5394. bb.min.x = x;
  5395. } else if ( x > bb.max.x ) {
  5396. bb.max.x = x;
  5397. }
  5398. if ( y < bb.min.y ) {
  5399. bb.min.y = y;
  5400. } else if ( y > bb.max.y ) {
  5401. bb.max.y = y;
  5402. }
  5403. if ( z < bb.min.z ) {
  5404. bb.min.z = z;
  5405. } else if ( z > bb.max.z ) {
  5406. bb.max.z = z;
  5407. }
  5408. }
  5409. }
  5410. if ( positions === undefined || positions.length === 0 ) {
  5411. this.boundingBox.min.set( 0, 0, 0 );
  5412. this.boundingBox.max.set( 0, 0, 0 );
  5413. }
  5414. },
  5415. computeBoundingSphere: function () {
  5416. var box = new THREE.Box3();
  5417. var vector = new THREE.Vector3();
  5418. return function () {
  5419. if ( this.boundingSphere === null ) {
  5420. this.boundingSphere = new THREE.Sphere();
  5421. }
  5422. var positions = this.attributes[ "position" ].array;
  5423. if ( positions ) {
  5424. var center = this.boundingSphere.center;
  5425. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5426. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5427. box.addPoint( vector );
  5428. }
  5429. box.center( center );
  5430. var maxRadiusSq = 0;
  5431. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5432. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5433. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5434. }
  5435. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5436. }
  5437. }
  5438. }(),
  5439. computeVertexNormals: function () {
  5440. if ( this.attributes[ "position" ] ) {
  5441. var i, il;
  5442. var j, jl;
  5443. var nVertexElements = this.attributes[ "position" ].array.length;
  5444. if ( this.attributes[ "normal" ] === undefined ) {
  5445. this.attributes[ "normal" ] = {
  5446. itemSize: 3,
  5447. array: new Float32Array( nVertexElements )
  5448. };
  5449. } else {
  5450. // reset existing normals to zero
  5451. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5452. this.attributes[ "normal" ].array[ i ] = 0;
  5453. }
  5454. }
  5455. var positions = this.attributes[ "position" ].array;
  5456. var normals = this.attributes[ "normal" ].array;
  5457. var vA, vB, vC, x, y, z,
  5458. pA = new THREE.Vector3(),
  5459. pB = new THREE.Vector3(),
  5460. pC = new THREE.Vector3(),
  5461. cb = new THREE.Vector3(),
  5462. ab = new THREE.Vector3();
  5463. // indexed elements
  5464. if ( this.attributes[ "index" ] ) {
  5465. var indices = this.attributes[ "index" ].array;
  5466. var offsets = this.offsets;
  5467. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5468. var start = offsets[ j ].start;
  5469. var count = offsets[ j ].count;
  5470. var index = offsets[ j ].index;
  5471. for ( i = start, il = start + count; i < il; i += 3 ) {
  5472. vA = index + indices[ i ];
  5473. vB = index + indices[ i + 1 ];
  5474. vC = index + indices[ i + 2 ];
  5475. x = positions[ vA * 3 ];
  5476. y = positions[ vA * 3 + 1 ];
  5477. z = positions[ vA * 3 + 2 ];
  5478. pA.set( x, y, z );
  5479. x = positions[ vB * 3 ];
  5480. y = positions[ vB * 3 + 1 ];
  5481. z = positions[ vB * 3 + 2 ];
  5482. pB.set( x, y, z );
  5483. x = positions[ vC * 3 ];
  5484. y = positions[ vC * 3 + 1 ];
  5485. z = positions[ vC * 3 + 2 ];
  5486. pC.set( x, y, z );
  5487. cb.subVectors( pC, pB );
  5488. ab.subVectors( pA, pB );
  5489. cb.cross( ab );
  5490. normals[ vA * 3 ] += cb.x;
  5491. normals[ vA * 3 + 1 ] += cb.y;
  5492. normals[ vA * 3 + 2 ] += cb.z;
  5493. normals[ vB * 3 ] += cb.x;
  5494. normals[ vB * 3 + 1 ] += cb.y;
  5495. normals[ vB * 3 + 2 ] += cb.z;
  5496. normals[ vC * 3 ] += cb.x;
  5497. normals[ vC * 3 + 1 ] += cb.y;
  5498. normals[ vC * 3 + 2 ] += cb.z;
  5499. }
  5500. }
  5501. // non-indexed elements (unconnected triangle soup)
  5502. } else {
  5503. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5504. x = positions[ i ];
  5505. y = positions[ i + 1 ];
  5506. z = positions[ i + 2 ];
  5507. pA.set( x, y, z );
  5508. x = positions[ i + 3 ];
  5509. y = positions[ i + 4 ];
  5510. z = positions[ i + 5 ];
  5511. pB.set( x, y, z );
  5512. x = positions[ i + 6 ];
  5513. y = positions[ i + 7 ];
  5514. z = positions[ i + 8 ];
  5515. pC.set( x, y, z );
  5516. cb.subVectors( pC, pB );
  5517. ab.subVectors( pA, pB );
  5518. cb.cross( ab );
  5519. normals[ i ] = cb.x;
  5520. normals[ i + 1 ] = cb.y;
  5521. normals[ i + 2 ] = cb.z;
  5522. normals[ i + 3 ] = cb.x;
  5523. normals[ i + 4 ] = cb.y;
  5524. normals[ i + 5 ] = cb.z;
  5525. normals[ i + 6 ] = cb.x;
  5526. normals[ i + 7 ] = cb.y;
  5527. normals[ i + 8 ] = cb.z;
  5528. }
  5529. }
  5530. this.normalizeNormals();
  5531. this.normalsNeedUpdate = true;
  5532. }
  5533. },
  5534. normalizeNormals: function () {
  5535. var normals = this.attributes[ "normal" ].array;
  5536. var x, y, z, n;
  5537. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5538. x = normals[ i ];
  5539. y = normals[ i + 1 ];
  5540. z = normals[ i + 2 ];
  5541. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5542. normals[ i ] *= n;
  5543. normals[ i + 1 ] *= n;
  5544. normals[ i + 2 ] *= n;
  5545. }
  5546. },
  5547. computeTangents: function () {
  5548. // based on http://www.terathon.com/code/tangent.html
  5549. // (per vertex tangents)
  5550. if ( this.attributes[ "index" ] === undefined ||
  5551. this.attributes[ "position" ] === undefined ||
  5552. this.attributes[ "normal" ] === undefined ||
  5553. this.attributes[ "uv" ] === undefined ) {
  5554. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5555. return;
  5556. }
  5557. var indices = this.attributes[ "index" ].array;
  5558. var positions = this.attributes[ "position" ].array;
  5559. var normals = this.attributes[ "normal" ].array;
  5560. var uvs = this.attributes[ "uv" ].array;
  5561. var nVertices = positions.length / 3;
  5562. if ( this.attributes[ "tangent" ] === undefined ) {
  5563. var nTangentElements = 4 * nVertices;
  5564. this.attributes[ "tangent" ] = {
  5565. itemSize: 4,
  5566. array: new Float32Array( nTangentElements )
  5567. };
  5568. }
  5569. var tangents = this.attributes[ "tangent" ].array;
  5570. var tan1 = [], tan2 = [];
  5571. for ( var k = 0; k < nVertices; k ++ ) {
  5572. tan1[ k ] = new THREE.Vector3();
  5573. tan2[ k ] = new THREE.Vector3();
  5574. }
  5575. var xA, yA, zA,
  5576. xB, yB, zB,
  5577. xC, yC, zC,
  5578. uA, vA,
  5579. uB, vB,
  5580. uC, vC,
  5581. x1, x2, y1, y2, z1, z2,
  5582. s1, s2, t1, t2, r;
  5583. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5584. function handleTriangle( a, b, c ) {
  5585. xA = positions[ a * 3 ];
  5586. yA = positions[ a * 3 + 1 ];
  5587. zA = positions[ a * 3 + 2 ];
  5588. xB = positions[ b * 3 ];
  5589. yB = positions[ b * 3 + 1 ];
  5590. zB = positions[ b * 3 + 2 ];
  5591. xC = positions[ c * 3 ];
  5592. yC = positions[ c * 3 + 1 ];
  5593. zC = positions[ c * 3 + 2 ];
  5594. uA = uvs[ a * 2 ];
  5595. vA = uvs[ a * 2 + 1 ];
  5596. uB = uvs[ b * 2 ];
  5597. vB = uvs[ b * 2 + 1 ];
  5598. uC = uvs[ c * 2 ];
  5599. vC = uvs[ c * 2 + 1 ];
  5600. x1 = xB - xA;
  5601. x2 = xC - xA;
  5602. y1 = yB - yA;
  5603. y2 = yC - yA;
  5604. z1 = zB - zA;
  5605. z2 = zC - zA;
  5606. s1 = uB - uA;
  5607. s2 = uC - uA;
  5608. t1 = vB - vA;
  5609. t2 = vC - vA;
  5610. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5611. sdir.set(
  5612. ( t2 * x1 - t1 * x2 ) * r,
  5613. ( t2 * y1 - t1 * y2 ) * r,
  5614. ( t2 * z1 - t1 * z2 ) * r
  5615. );
  5616. tdir.set(
  5617. ( s1 * x2 - s2 * x1 ) * r,
  5618. ( s1 * y2 - s2 * y1 ) * r,
  5619. ( s1 * z2 - s2 * z1 ) * r
  5620. );
  5621. tan1[ a ].add( sdir );
  5622. tan1[ b ].add( sdir );
  5623. tan1[ c ].add( sdir );
  5624. tan2[ a ].add( tdir );
  5625. tan2[ b ].add( tdir );
  5626. tan2[ c ].add( tdir );
  5627. }
  5628. var i, il;
  5629. var j, jl;
  5630. var iA, iB, iC;
  5631. var offsets = this.offsets;
  5632. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5633. var start = offsets[ j ].start;
  5634. var count = offsets[ j ].count;
  5635. var index = offsets[ j ].index;
  5636. for ( i = start, il = start + count; i < il; i += 3 ) {
  5637. iA = index + indices[ i ];
  5638. iB = index + indices[ i + 1 ];
  5639. iC = index + indices[ i + 2 ];
  5640. handleTriangle( iA, iB, iC );
  5641. }
  5642. }
  5643. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5644. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5645. var w, t, test;
  5646. function handleVertex( v ) {
  5647. n.x = normals[ v * 3 ];
  5648. n.y = normals[ v * 3 + 1 ];
  5649. n.z = normals[ v * 3 + 2 ];
  5650. n2.copy( n );
  5651. t = tan1[ v ];
  5652. // Gram-Schmidt orthogonalize
  5653. tmp.copy( t );
  5654. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5655. // Calculate handedness
  5656. tmp2.crossVectors( n2, t );
  5657. test = tmp2.dot( tan2[ v ] );
  5658. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5659. tangents[ v * 4 ] = tmp.x;
  5660. tangents[ v * 4 + 1 ] = tmp.y;
  5661. tangents[ v * 4 + 2 ] = tmp.z;
  5662. tangents[ v * 4 + 3 ] = w;
  5663. }
  5664. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5665. var start = offsets[ j ].start;
  5666. var count = offsets[ j ].count;
  5667. var index = offsets[ j ].index;
  5668. for ( i = start, il = start + count; i < il; i += 3 ) {
  5669. iA = index + indices[ i ];
  5670. iB = index + indices[ i + 1 ];
  5671. iC = index + indices[ i + 2 ];
  5672. handleVertex( iA );
  5673. handleVertex( iB );
  5674. handleVertex( iC );
  5675. }
  5676. }
  5677. this.hasTangents = true;
  5678. this.tangentsNeedUpdate = true;
  5679. },
  5680. clone: function () {
  5681. var geometry = new THREE.BufferGeometry();
  5682. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5683. for ( var attr in this.attributes ) {
  5684. var sourceAttr = this.attributes[ attr ];
  5685. var sourceArray = sourceAttr.array;
  5686. var attribute = {
  5687. itemSize: sourceAttr.itemSize,
  5688. numItems: sourceAttr.numItems,
  5689. array: null
  5690. };
  5691. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5692. var type = types[ i ];
  5693. if ( sourceArray instanceof type ) {
  5694. attribute.array = new type( sourceArray );
  5695. break;
  5696. }
  5697. }
  5698. geometry.attributes[ attr ] = attribute;
  5699. }
  5700. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5701. var offset = this.offsets[ i ];
  5702. geometry.offsets.push( {
  5703. start: offset.start,
  5704. index: offset.index,
  5705. count: offset.count
  5706. } );
  5707. }
  5708. return geometry;
  5709. },
  5710. dispose: function () {
  5711. this.dispatchEvent( { type: 'dispose' } );
  5712. }
  5713. };
  5714. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5715. /**
  5716. * @author mrdoob / http://mrdoob.com/
  5717. * @author mikael emtinger / http://gomo.se/
  5718. * @author WestLangley / http://github.com/WestLangley
  5719. */
  5720. THREE.Camera = function () {
  5721. THREE.Object3D.call( this );
  5722. this.matrixWorldInverse = new THREE.Matrix4();
  5723. this.projectionMatrix = new THREE.Matrix4();
  5724. this.projectionMatrixInverse = new THREE.Matrix4();
  5725. };
  5726. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5727. THREE.Camera.prototype.lookAt = function () {
  5728. // This routine does not support cameras with rotated and/or translated parent(s)
  5729. var m1 = new THREE.Matrix4();
  5730. return function ( vector ) {
  5731. m1.lookAt( this.position, vector, this.up );
  5732. this.quaternion.setFromRotationMatrix( m1 );
  5733. };
  5734. }();
  5735. THREE.Camera.prototype.clone = function (camera) {
  5736. if ( camera === undefined ) camera = new THREE.Camera();
  5737. THREE.Object3D.prototype.clone.call( this, camera );
  5738. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  5739. camera.projectionMatrix.copy( this.projectionMatrix );
  5740. camera.projectionMatrixInverse.copy( this.projectionMatrixInverse );
  5741. return camera;
  5742. };
  5743. /**
  5744. * @author alteredq / http://alteredqualia.com/
  5745. */
  5746. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5747. THREE.Camera.call( this );
  5748. this.left = left;
  5749. this.right = right;
  5750. this.top = top;
  5751. this.bottom = bottom;
  5752. this.near = ( near !== undefined ) ? near : 0.1;
  5753. this.far = ( far !== undefined ) ? far : 2000;
  5754. this.updateProjectionMatrix();
  5755. };
  5756. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5757. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5758. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5759. };
  5760. THREE.OrthographicCamera.prototype.clone = function () {
  5761. var camera = new THREE.OrthographicCamera();
  5762. THREE.Camera.prototype.clone.call( this, camera );
  5763. camera.left = this.left;
  5764. camera.right = this.right;
  5765. camera.top = this.top;
  5766. camera.bottom = this.bottom;
  5767. camera.near = this.near;
  5768. camera.far = this.far;
  5769. return camera;
  5770. };
  5771. /**
  5772. * @author mrdoob / http://mrdoob.com/
  5773. * @author greggman / http://games.greggman.com/
  5774. * @author zz85 / http://www.lab4games.net/zz85/blog
  5775. */
  5776. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5777. THREE.Camera.call( this );
  5778. this.fov = fov !== undefined ? fov : 50;
  5779. this.aspect = aspect !== undefined ? aspect : 1;
  5780. this.near = near !== undefined ? near : 0.1;
  5781. this.far = far !== undefined ? far : 2000;
  5782. this.updateProjectionMatrix();
  5783. };
  5784. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5785. /**
  5786. * Uses Focal Length (in mm) to estimate and set FOV
  5787. * 35mm (fullframe) camera is used if frame size is not specified;
  5788. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5789. */
  5790. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5791. if ( frameHeight === undefined ) frameHeight = 24;
  5792. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5793. this.updateProjectionMatrix();
  5794. }
  5795. /**
  5796. * Sets an offset in a larger frustum. This is useful for multi-window or
  5797. * multi-monitor/multi-machine setups.
  5798. *
  5799. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5800. * the monitors are in grid like this
  5801. *
  5802. * +---+---+---+
  5803. * | A | B | C |
  5804. * +---+---+---+
  5805. * | D | E | F |
  5806. * +---+---+---+
  5807. *
  5808. * then for each monitor you would call it like this
  5809. *
  5810. * var w = 1920;
  5811. * var h = 1080;
  5812. * var fullWidth = w * 3;
  5813. * var fullHeight = h * 2;
  5814. *
  5815. * --A--
  5816. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5817. * --B--
  5818. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5819. * --C--
  5820. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5821. * --D--
  5822. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5823. * --E--
  5824. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5825. * --F--
  5826. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5827. *
  5828. * Note there is no reason monitors have to be the same size or in a grid.
  5829. */
  5830. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5831. this.fullWidth = fullWidth;
  5832. this.fullHeight = fullHeight;
  5833. this.x = x;
  5834. this.y = y;
  5835. this.width = width;
  5836. this.height = height;
  5837. this.updateProjectionMatrix();
  5838. };
  5839. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5840. if ( this.fullWidth ) {
  5841. var aspect = this.fullWidth / this.fullHeight;
  5842. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5843. var bottom = -top;
  5844. var left = aspect * bottom;
  5845. var right = aspect * top;
  5846. var width = Math.abs( right - left );
  5847. var height = Math.abs( top - bottom );
  5848. this.projectionMatrix.makeFrustum(
  5849. left + this.x * width / this.fullWidth,
  5850. left + ( this.x + this.width ) * width / this.fullWidth,
  5851. top - ( this.y + this.height ) * height / this.fullHeight,
  5852. top - this.y * height / this.fullHeight,
  5853. this.near,
  5854. this.far
  5855. );
  5856. } else {
  5857. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5858. }
  5859. };
  5860. THREE.PerspectiveCamera.prototype.clone = function () {
  5861. var camera = new THREE.PerspectiveCamera();
  5862. THREE.Camera.prototype.clone.call( this, camera );
  5863. camera.fov = this.fov;
  5864. camera.aspect = this.aspect;
  5865. camera.near = this.near;
  5866. camera.far = this.far;
  5867. return camera;
  5868. };
  5869. /**
  5870. * @author mrdoob / http://mrdoob.com/
  5871. * @author alteredq / http://alteredqualia.com/
  5872. */
  5873. THREE.Light = function ( hex ) {
  5874. THREE.Object3D.call( this );
  5875. this.color = new THREE.Color( hex );
  5876. };
  5877. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5878. THREE.Light.prototype.clone = function ( light ) {
  5879. if ( light === undefined ) light = new THREE.Light();
  5880. THREE.Object3D.prototype.clone.call( this, light );
  5881. light.color.copy( this.color );
  5882. return light;
  5883. };
  5884. /**
  5885. * @author mrdoob / http://mrdoob.com/
  5886. */
  5887. THREE.AmbientLight = function ( hex ) {
  5888. THREE.Light.call( this, hex );
  5889. };
  5890. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5891. THREE.AmbientLight.prototype.clone = function () {
  5892. var light = new THREE.AmbientLight();
  5893. THREE.Light.prototype.clone.call( this, light );
  5894. return light;
  5895. };
  5896. /**
  5897. * @author MPanknin / http://www.redplant.de/
  5898. * @author alteredq / http://alteredqualia.com/
  5899. */
  5900. THREE.AreaLight = function ( hex, intensity ) {
  5901. THREE.Light.call( this, hex );
  5902. this.normal = new THREE.Vector3( 0, -1, 0 );
  5903. this.right = new THREE.Vector3( 1, 0, 0 );
  5904. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5905. this.width = 1.0;
  5906. this.height = 1.0;
  5907. this.constantAttenuation = 1.5;
  5908. this.linearAttenuation = 0.5;
  5909. this.quadraticAttenuation = 0.1;
  5910. };
  5911. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5912. /**
  5913. * @author mrdoob / http://mrdoob.com/
  5914. * @author alteredq / http://alteredqualia.com/
  5915. */
  5916. THREE.DirectionalLight = function ( hex, intensity ) {
  5917. THREE.Light.call( this, hex );
  5918. this.position.set( 0, 1, 0 );
  5919. this.target = new THREE.Object3D();
  5920. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5921. this.castShadow = false;
  5922. this.onlyShadow = false;
  5923. //
  5924. this.shadowCameraNear = 50;
  5925. this.shadowCameraFar = 5000;
  5926. this.shadowCameraLeft = -500;
  5927. this.shadowCameraRight = 500;
  5928. this.shadowCameraTop = 500;
  5929. this.shadowCameraBottom = -500;
  5930. this.shadowCameraVisible = false;
  5931. this.shadowBias = 0;
  5932. this.shadowDarkness = 0.5;
  5933. this.shadowMapWidth = 512;
  5934. this.shadowMapHeight = 512;
  5935. //
  5936. this.shadowCascade = false;
  5937. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5938. this.shadowCascadeCount = 2;
  5939. this.shadowCascadeBias = [ 0, 0, 0 ];
  5940. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5941. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5942. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5943. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5944. this.shadowCascadeArray = [];
  5945. //
  5946. this.shadowMap = null;
  5947. this.shadowMapSize = null;
  5948. this.shadowCamera = null;
  5949. this.shadowMatrix = null;
  5950. };
  5951. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5952. THREE.DirectionalLight.prototype.clone = function () {
  5953. var light = new THREE.DirectionalLight();
  5954. THREE.Light.prototype.clone.call( this, light );
  5955. light.target = this.target.clone();
  5956. light.intensity = this.intensity;
  5957. light.castShadow = this.castShadow;
  5958. light.onlyShadow = this.onlyShadow;
  5959. return light;
  5960. };
  5961. /**
  5962. * @author alteredq / http://alteredqualia.com/
  5963. */
  5964. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5965. THREE.Light.call( this, skyColorHex );
  5966. this.position.set( 0, 100, 0 );
  5967. this.groundColor = new THREE.Color( groundColorHex );
  5968. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5969. };
  5970. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5971. THREE.HemisphereLight.prototype.clone = function () {
  5972. var light = new THREE.HemisphereLight();
  5973. THREE.Light.prototype.clone.call( this, light );
  5974. light.groundColor.copy( this.groundColor );
  5975. light.intensity = this.intensity;
  5976. return light;
  5977. };
  5978. /**
  5979. * @author mrdoob / http://mrdoob.com/
  5980. */
  5981. THREE.PointLight = function ( hex, intensity, distance ) {
  5982. THREE.Light.call( this, hex );
  5983. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5984. this.distance = ( distance !== undefined ) ? distance : 0;
  5985. };
  5986. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5987. THREE.PointLight.prototype.clone = function () {
  5988. var light = new THREE.PointLight();
  5989. THREE.Light.prototype.clone.call( this, light );
  5990. light.intensity = this.intensity;
  5991. light.distance = this.distance;
  5992. return light;
  5993. };
  5994. /**
  5995. * @author alteredq / http://alteredqualia.com/
  5996. */
  5997. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5998. THREE.Light.call( this, hex );
  5999. this.position.set( 0, 1, 0 );
  6000. this.target = new THREE.Object3D();
  6001. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6002. this.distance = ( distance !== undefined ) ? distance : 0;
  6003. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6004. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6005. this.castShadow = false;
  6006. this.onlyShadow = false;
  6007. //
  6008. this.shadowCameraNear = 50;
  6009. this.shadowCameraFar = 5000;
  6010. this.shadowCameraFov = 50;
  6011. this.shadowCameraVisible = false;
  6012. this.shadowBias = 0;
  6013. this.shadowDarkness = 0.5;
  6014. this.shadowMapWidth = 512;
  6015. this.shadowMapHeight = 512;
  6016. //
  6017. this.shadowMap = null;
  6018. this.shadowMapSize = null;
  6019. this.shadowCamera = null;
  6020. this.shadowMatrix = null;
  6021. };
  6022. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6023. THREE.SpotLight.prototype.clone = function () {
  6024. var light = new THREE.SpotLight();
  6025. THREE.Light.prototype.clone.call( this, light );
  6026. light.target = this.target.clone();
  6027. light.intensity = this.intensity;
  6028. light.distance = this.distance;
  6029. light.angle = this.angle;
  6030. light.exponent = this.exponent;
  6031. light.castShadow = this.castShadow;
  6032. light.onlyShadow = this.onlyShadow;
  6033. return light;
  6034. };
  6035. /**
  6036. * @author alteredq / http://alteredqualia.com/
  6037. */
  6038. THREE.Loader = function ( showStatus ) {
  6039. this.showStatus = showStatus;
  6040. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6041. this.onLoadStart = function () {};
  6042. this.onLoadProgress = function () {};
  6043. this.onLoadComplete = function () {};
  6044. };
  6045. THREE.Loader.prototype = {
  6046. constructor: THREE.Loader,
  6047. crossOrigin: 'anonymous',
  6048. addStatusElement: function () {
  6049. var e = document.createElement( "div" );
  6050. e.style.position = "absolute";
  6051. e.style.right = "0px";
  6052. e.style.top = "0px";
  6053. e.style.fontSize = "0.8em";
  6054. e.style.textAlign = "left";
  6055. e.style.background = "rgba(0,0,0,0.25)";
  6056. e.style.color = "#fff";
  6057. e.style.width = "120px";
  6058. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6059. e.style.zIndex = 1000;
  6060. e.innerHTML = "Loading ...";
  6061. return e;
  6062. },
  6063. updateProgress: function ( progress ) {
  6064. var message = "Loaded ";
  6065. if ( progress.total ) {
  6066. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6067. } else {
  6068. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6069. }
  6070. this.statusDomElement.innerHTML = message;
  6071. },
  6072. extractUrlBase: function ( url ) {
  6073. var parts = url.split( '/' );
  6074. parts.pop();
  6075. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  6076. },
  6077. initMaterials: function ( materials, texturePath ) {
  6078. var array = [];
  6079. for ( var i = 0; i < materials.length; ++ i ) {
  6080. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6081. }
  6082. return array;
  6083. },
  6084. needsTangents: function ( materials ) {
  6085. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6086. var m = materials[ i ];
  6087. if ( m instanceof THREE.ShaderMaterial ) return true;
  6088. }
  6089. return false;
  6090. },
  6091. createMaterial: function ( m, texturePath ) {
  6092. var _this = this;
  6093. function is_pow2( n ) {
  6094. var l = Math.log( n ) / Math.LN2;
  6095. return Math.floor( l ) == l;
  6096. }
  6097. function nearest_pow2( n ) {
  6098. var l = Math.log( n ) / Math.LN2;
  6099. return Math.pow( 2, Math.round( l ) );
  6100. }
  6101. function load_image( where, url ) {
  6102. var image = new Image();
  6103. image.onload = function () {
  6104. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6105. var width = nearest_pow2( this.width );
  6106. var height = nearest_pow2( this.height );
  6107. where.image.width = width;
  6108. where.image.height = height;
  6109. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6110. } else {
  6111. where.image = this;
  6112. }
  6113. where.needsUpdate = true;
  6114. };
  6115. image.crossOrigin = _this.crossOrigin;
  6116. image.src = url;
  6117. }
  6118. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6119. var isCompressed = /\.dds$/i.test( sourceFile );
  6120. var fullPath = texturePath + "/" + sourceFile;
  6121. if ( isCompressed ) {
  6122. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6123. where[ name ] = texture;
  6124. } else {
  6125. var texture = document.createElement( 'canvas' );
  6126. where[ name ] = new THREE.Texture( texture );
  6127. }
  6128. where[ name ].sourceFile = sourceFile;
  6129. if( repeat ) {
  6130. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6131. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6132. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6133. }
  6134. if ( offset ) {
  6135. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6136. }
  6137. if ( wrap ) {
  6138. var wrapMap = {
  6139. "repeat": THREE.RepeatWrapping,
  6140. "mirror": THREE.MirroredRepeatWrapping
  6141. }
  6142. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6143. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6144. }
  6145. if ( anisotropy ) {
  6146. where[ name ].anisotropy = anisotropy;
  6147. }
  6148. if ( ! isCompressed ) {
  6149. load_image( where[ name ], fullPath );
  6150. }
  6151. }
  6152. function rgb2hex( rgb ) {
  6153. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6154. }
  6155. // defaults
  6156. var mtype = "MeshLambertMaterial";
  6157. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6158. // parameters from model file
  6159. if ( m.shading ) {
  6160. var shading = m.shading.toLowerCase();
  6161. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6162. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6163. }
  6164. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6165. mpars.blending = THREE[ m.blending ];
  6166. }
  6167. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6168. mpars.transparent = m.transparent;
  6169. }
  6170. if ( m.depthTest !== undefined ) {
  6171. mpars.depthTest = m.depthTest;
  6172. }
  6173. if ( m.depthWrite !== undefined ) {
  6174. mpars.depthWrite = m.depthWrite;
  6175. }
  6176. if ( m.visible !== undefined ) {
  6177. mpars.visible = m.visible;
  6178. }
  6179. if ( m.flipSided !== undefined ) {
  6180. mpars.side = THREE.BackSide;
  6181. }
  6182. if ( m.doubleSided !== undefined ) {
  6183. mpars.side = THREE.DoubleSide;
  6184. }
  6185. if ( m.wireframe !== undefined ) {
  6186. mpars.wireframe = m.wireframe;
  6187. }
  6188. if ( m.vertexColors !== undefined ) {
  6189. if ( m.vertexColors === "face" ) {
  6190. mpars.vertexColors = THREE.FaceColors;
  6191. } else if ( m.vertexColors ) {
  6192. mpars.vertexColors = THREE.VertexColors;
  6193. }
  6194. }
  6195. // colors
  6196. if ( m.colorDiffuse ) {
  6197. mpars.color = rgb2hex( m.colorDiffuse );
  6198. } else if ( m.DbgColor ) {
  6199. mpars.color = m.DbgColor;
  6200. }
  6201. if ( m.colorSpecular ) {
  6202. mpars.specular = rgb2hex( m.colorSpecular );
  6203. }
  6204. if ( m.colorAmbient ) {
  6205. mpars.ambient = rgb2hex( m.colorAmbient );
  6206. }
  6207. // modifiers
  6208. if ( m.transparency ) {
  6209. mpars.opacity = m.transparency;
  6210. }
  6211. if ( m.specularCoef ) {
  6212. mpars.shininess = m.specularCoef;
  6213. }
  6214. // textures
  6215. if ( m.mapDiffuse && texturePath ) {
  6216. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6217. }
  6218. if ( m.mapLight && texturePath ) {
  6219. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6220. }
  6221. if ( m.mapBump && texturePath ) {
  6222. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6223. }
  6224. if ( m.mapNormal && texturePath ) {
  6225. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6226. }
  6227. if ( m.mapSpecular && texturePath ) {
  6228. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6229. }
  6230. //
  6231. if ( m.mapBumpScale ) {
  6232. mpars.bumpScale = m.mapBumpScale;
  6233. }
  6234. // special case for normal mapped material
  6235. if ( m.mapNormal ) {
  6236. var shader = THREE.ShaderLib[ "normalmap" ];
  6237. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6238. uniforms[ "tNormal" ].value = mpars.normalMap;
  6239. if ( m.mapNormalFactor ) {
  6240. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6241. }
  6242. if ( mpars.map ) {
  6243. uniforms[ "tDiffuse" ].value = mpars.map;
  6244. uniforms[ "enableDiffuse" ].value = true;
  6245. }
  6246. if ( mpars.specularMap ) {
  6247. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6248. uniforms[ "enableSpecular" ].value = true;
  6249. }
  6250. if ( mpars.lightMap ) {
  6251. uniforms[ "tAO" ].value = mpars.lightMap;
  6252. uniforms[ "enableAO" ].value = true;
  6253. }
  6254. // for the moment don't handle displacement texture
  6255. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6256. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6257. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6258. uniforms[ "uShininess" ].value = mpars.shininess;
  6259. if ( mpars.opacity !== undefined ) {
  6260. uniforms[ "uOpacity" ].value = mpars.opacity;
  6261. }
  6262. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6263. var material = new THREE.ShaderMaterial( parameters );
  6264. if ( mpars.transparent ) {
  6265. material.transparent = true;
  6266. }
  6267. } else {
  6268. var material = new THREE[ mtype ]( mpars );
  6269. }
  6270. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6271. return material;
  6272. }
  6273. };
  6274. /**
  6275. * @author mrdoob / http://mrdoob.com/
  6276. */
  6277. THREE.XHRLoader = function ( manager ) {
  6278. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6279. };
  6280. THREE.XHRLoader.prototype = {
  6281. constructor: THREE.XHRLoader,
  6282. load: function ( url, onLoad, onProgress, onError ) {
  6283. var scope = this;
  6284. var request = new XMLHttpRequest();
  6285. if ( onLoad !== undefined ) {
  6286. request.addEventListener( 'load', function ( event ) {
  6287. onLoad( event.target.responseText );
  6288. scope.manager.itemEnd( url );
  6289. }, false );
  6290. }
  6291. if ( onProgress !== undefined ) {
  6292. request.addEventListener( 'progress', function ( event ) {
  6293. onProgress( event );
  6294. }, false );
  6295. }
  6296. if ( onError !== undefined ) {
  6297. request.addEventListener( 'error', function ( event ) {
  6298. onError( event );
  6299. }, false );
  6300. }
  6301. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6302. request.open( 'GET', url, true );
  6303. request.send( null );
  6304. scope.manager.itemStart( url );
  6305. },
  6306. setCrossOrigin: function ( value ) {
  6307. this.crossOrigin = value;
  6308. }
  6309. };
  6310. /**
  6311. * @author mrdoob / http://mrdoob.com/
  6312. */
  6313. THREE.ImageLoader = function ( manager ) {
  6314. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6315. };
  6316. THREE.ImageLoader.prototype = {
  6317. constructor: THREE.ImageLoader,
  6318. load: function ( url, onLoad, onProgress, onError ) {
  6319. var scope = this;
  6320. var image = document.createElement( 'img' );
  6321. if ( onLoad !== undefined ) {
  6322. image.addEventListener( 'load', function ( event ) {
  6323. scope.manager.itemEnd( url );
  6324. onLoad( this );
  6325. }, false );
  6326. }
  6327. if ( onProgress !== undefined ) {
  6328. image.addEventListener( 'progress', function ( event ) {
  6329. onProgress( event );
  6330. }, false );
  6331. }
  6332. if ( onError !== undefined ) {
  6333. image.addEventListener( 'error', function ( event ) {
  6334. onError( event );
  6335. }, false );
  6336. }
  6337. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6338. image.src = url;
  6339. scope.manager.itemStart( url );
  6340. return image;
  6341. },
  6342. setCrossOrigin: function ( value ) {
  6343. this.crossOrigin = value;
  6344. }
  6345. }
  6346. /**
  6347. * @author mrdoob / http://mrdoob.com/
  6348. * @author alteredq / http://alteredqualia.com/
  6349. */
  6350. THREE.JSONLoader = function ( showStatus ) {
  6351. THREE.Loader.call( this, showStatus );
  6352. this.withCredentials = false;
  6353. };
  6354. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6355. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6356. var scope = this;
  6357. // todo: unify load API to for easier SceneLoader use
  6358. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6359. this.onLoadStart();
  6360. this.loadAjaxJSON( this, url, callback, texturePath );
  6361. };
  6362. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6363. var xhr = new XMLHttpRequest();
  6364. var length = 0;
  6365. xhr.onreadystatechange = function () {
  6366. if ( xhr.readyState === xhr.DONE ) {
  6367. if ( xhr.status === 200 || xhr.status === 0 ) {
  6368. if ( xhr.responseText ) {
  6369. var json = JSON.parse( xhr.responseText );
  6370. var result = context.parse( json, texturePath );
  6371. callback( result.geometry, result.materials );
  6372. } else {
  6373. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6374. }
  6375. // in context of more complex asset initialization
  6376. // do not block on single failed file
  6377. // maybe should go even one more level up
  6378. context.onLoadComplete();
  6379. } else {
  6380. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6381. }
  6382. } else if ( xhr.readyState === xhr.LOADING ) {
  6383. if ( callbackProgress ) {
  6384. if ( length === 0 ) {
  6385. length = xhr.getResponseHeader( "Content-Length" );
  6386. }
  6387. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6388. }
  6389. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6390. if ( callbackProgress !== undefined ) {
  6391. length = xhr.getResponseHeader( "Content-Length" );
  6392. }
  6393. }
  6394. };
  6395. xhr.open( "GET", url, true );
  6396. xhr.withCredentials = this.withCredentials;
  6397. xhr.send( null );
  6398. };
  6399. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6400. var scope = this,
  6401. geometry = new THREE.Geometry(),
  6402. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6403. parseModel( scale );
  6404. parseSkin();
  6405. parseMorphing( scale );
  6406. geometry.computeCentroids();
  6407. geometry.computeFaceNormals();
  6408. geometry.computeBoundingSphere();
  6409. function parseModel( scale ) {
  6410. function isBitSet( value, position ) {
  6411. return value & ( 1 << position );
  6412. }
  6413. var i, j, fi,
  6414. offset, zLength,
  6415. colorIndex, normalIndex, uvIndex, materialIndex,
  6416. type,
  6417. isQuad,
  6418. hasMaterial,
  6419. hasFaceVertexUv,
  6420. hasFaceNormal, hasFaceVertexNormal,
  6421. hasFaceColor, hasFaceVertexColor,
  6422. vertex, face, faceA, faceB, color, hex, normal,
  6423. uvLayer, uv, u, v,
  6424. faces = json.faces,
  6425. vertices = json.vertices,
  6426. normals = json.normals,
  6427. colors = json.colors,
  6428. nUvLayers = 0;
  6429. if ( json.uvs !== undefined ) {
  6430. // disregard empty arrays
  6431. for ( i = 0; i < json.uvs.length; i++ ) {
  6432. if ( json.uvs[ i ].length ) nUvLayers ++;
  6433. }
  6434. for ( i = 0; i < nUvLayers; i++ ) {
  6435. geometry.faceVertexUvs[ i ] = [];
  6436. }
  6437. }
  6438. offset = 0;
  6439. zLength = vertices.length;
  6440. while ( offset < zLength ) {
  6441. vertex = new THREE.Vector3();
  6442. vertex.x = vertices[ offset ++ ] * scale;
  6443. vertex.y = vertices[ offset ++ ] * scale;
  6444. vertex.z = vertices[ offset ++ ] * scale;
  6445. geometry.vertices.push( vertex );
  6446. }
  6447. offset = 0;
  6448. zLength = faces.length;
  6449. while ( offset < zLength ) {
  6450. type = faces[ offset ++ ];
  6451. isQuad = isBitSet( type, 0 );
  6452. hasMaterial = isBitSet( type, 1 );
  6453. hasFaceVertexUv = isBitSet( type, 3 );
  6454. hasFaceNormal = isBitSet( type, 4 );
  6455. hasFaceVertexNormal = isBitSet( type, 5 );
  6456. hasFaceColor = isBitSet( type, 6 );
  6457. hasFaceVertexColor = isBitSet( type, 7 );
  6458. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6459. if ( isQuad ) {
  6460. faceA = new THREE.Face3();
  6461. faceA.a = faces[ offset ];
  6462. faceA.b = faces[ offset + 1 ];
  6463. faceA.c = faces[ offset + 3 ];
  6464. faceB = new THREE.Face3();
  6465. faceB.a = faces[ offset + 1 ];
  6466. faceB.b = faces[ offset + 2 ];
  6467. faceB.c = faces[ offset + 3 ];
  6468. offset += 4;
  6469. if ( hasMaterial ) {
  6470. materialIndex = faces[ offset ++ ];
  6471. faceA.materialIndex = materialIndex;
  6472. faceB.materialIndex = materialIndex;
  6473. }
  6474. // to get face <=> uv index correspondence
  6475. fi = geometry.faces.length;
  6476. if ( hasFaceVertexUv ) {
  6477. for ( i = 0; i < nUvLayers; i++ ) {
  6478. uvLayer = json.uvs[ i ];
  6479. geometry.faceVertexUvs[ i ][ fi ] = [];
  6480. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6481. for ( j = 0; j < 4; j ++ ) {
  6482. uvIndex = faces[ offset ++ ];
  6483. u = uvLayer[ uvIndex * 2 ];
  6484. v = uvLayer[ uvIndex * 2 + 1 ];
  6485. uv = new THREE.Vector2( u, v );
  6486. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6487. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6488. }
  6489. }
  6490. }
  6491. if ( hasFaceNormal ) {
  6492. normalIndex = faces[ offset ++ ] * 3;
  6493. faceA.normal.set(
  6494. normals[ normalIndex ++ ],
  6495. normals[ normalIndex ++ ],
  6496. normals[ normalIndex ]
  6497. );
  6498. faceB.normal.copy( faceA.normal );
  6499. }
  6500. if ( hasFaceVertexNormal ) {
  6501. for ( i = 0; i < 4; i++ ) {
  6502. normalIndex = faces[ offset ++ ] * 3;
  6503. normal = new THREE.Vector3(
  6504. normals[ normalIndex ++ ],
  6505. normals[ normalIndex ++ ],
  6506. normals[ normalIndex ]
  6507. );
  6508. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  6509. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  6510. }
  6511. }
  6512. if ( hasFaceColor ) {
  6513. colorIndex = faces[ offset ++ ];
  6514. hex = colors[ colorIndex ];
  6515. faceA.color.setHex( hex );
  6516. faceB.color.setHex( hex );
  6517. }
  6518. if ( hasFaceVertexColor ) {
  6519. for ( i = 0; i < 4; i++ ) {
  6520. colorIndex = faces[ offset ++ ];
  6521. hex = colors[ colorIndex ];
  6522. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  6523. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  6524. }
  6525. }
  6526. geometry.faces.push( faceA );
  6527. geometry.faces.push( faceB );
  6528. } else {
  6529. face = new THREE.Face3();
  6530. face.a = faces[ offset ++ ];
  6531. face.b = faces[ offset ++ ];
  6532. face.c = faces[ offset ++ ];
  6533. if ( hasMaterial ) {
  6534. materialIndex = faces[ offset ++ ];
  6535. face.materialIndex = materialIndex;
  6536. }
  6537. // to get face <=> uv index correspondence
  6538. fi = geometry.faces.length;
  6539. if ( hasFaceVertexUv ) {
  6540. for ( i = 0; i < nUvLayers; i++ ) {
  6541. uvLayer = json.uvs[ i ];
  6542. geometry.faceVertexUvs[ i ][ fi ] = [];
  6543. for ( j = 0; j < 3; j ++ ) {
  6544. uvIndex = faces[ offset ++ ];
  6545. u = uvLayer[ uvIndex * 2 ];
  6546. v = uvLayer[ uvIndex * 2 + 1 ];
  6547. uv = new THREE.Vector2( u, v );
  6548. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6549. }
  6550. }
  6551. }
  6552. if ( hasFaceNormal ) {
  6553. normalIndex = faces[ offset ++ ] * 3;
  6554. face.normal.set(
  6555. normals[ normalIndex ++ ],
  6556. normals[ normalIndex ++ ],
  6557. normals[ normalIndex ]
  6558. );
  6559. }
  6560. if ( hasFaceVertexNormal ) {
  6561. for ( i = 0; i < 3; i++ ) {
  6562. normalIndex = faces[ offset ++ ] * 3;
  6563. normal = new THREE.Vector3(
  6564. normals[ normalIndex ++ ],
  6565. normals[ normalIndex ++ ],
  6566. normals[ normalIndex ]
  6567. );
  6568. face.vertexNormals.push( normal );
  6569. }
  6570. }
  6571. if ( hasFaceColor ) {
  6572. colorIndex = faces[ offset ++ ];
  6573. face.color.setHex( colors[ colorIndex ] );
  6574. }
  6575. if ( hasFaceVertexColor ) {
  6576. for ( i = 0; i < 3; i++ ) {
  6577. colorIndex = faces[ offset ++ ];
  6578. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  6579. }
  6580. }
  6581. geometry.faces.push( face );
  6582. }
  6583. }
  6584. };
  6585. function parseSkin() {
  6586. var i, l, x, y, z, w, a, b, c, d;
  6587. if ( json.skinWeights ) {
  6588. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6589. x = json.skinWeights[ i ];
  6590. y = json.skinWeights[ i + 1 ];
  6591. z = 0;
  6592. w = 0;
  6593. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6594. }
  6595. }
  6596. if ( json.skinIndices ) {
  6597. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6598. a = json.skinIndices[ i ];
  6599. b = json.skinIndices[ i + 1 ];
  6600. c = 0;
  6601. d = 0;
  6602. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6603. }
  6604. }
  6605. geometry.bones = json.bones;
  6606. // could change this to json.animations[0] or remove completely
  6607. geometry.animation = json.animation;
  6608. geometry.animations = json.animations;
  6609. };
  6610. function parseMorphing( scale ) {
  6611. if ( json.morphTargets !== undefined ) {
  6612. var i, l, v, vl, dstVertices, srcVertices;
  6613. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6614. geometry.morphTargets[ i ] = {};
  6615. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6616. geometry.morphTargets[ i ].vertices = [];
  6617. dstVertices = geometry.morphTargets[ i ].vertices;
  6618. srcVertices = json.morphTargets [ i ].vertices;
  6619. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6620. var vertex = new THREE.Vector3();
  6621. vertex.x = srcVertices[ v ] * scale;
  6622. vertex.y = srcVertices[ v + 1 ] * scale;
  6623. vertex.z = srcVertices[ v + 2 ] * scale;
  6624. dstVertices.push( vertex );
  6625. }
  6626. }
  6627. }
  6628. if ( json.morphColors !== undefined ) {
  6629. var i, l, c, cl, dstColors, srcColors, color;
  6630. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6631. geometry.morphColors[ i ] = {};
  6632. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6633. geometry.morphColors[ i ].colors = [];
  6634. dstColors = geometry.morphColors[ i ].colors;
  6635. srcColors = json.morphColors [ i ].colors;
  6636. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6637. color = new THREE.Color( 0xffaa00 );
  6638. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6639. dstColors.push( color );
  6640. }
  6641. }
  6642. }
  6643. };
  6644. if ( json.materials === undefined ) {
  6645. return { geometry: geometry };
  6646. } else {
  6647. var materials = this.initMaterials( json.materials, texturePath );
  6648. if ( this.needsTangents( materials ) ) {
  6649. geometry.computeTangents();
  6650. }
  6651. return { geometry: geometry, materials: materials };
  6652. }
  6653. };
  6654. /**
  6655. * @author mrdoob / http://mrdoob.com/
  6656. */
  6657. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6658. var scope = this;
  6659. var loaded = 0, total = 0;
  6660. this.onLoad = onLoad;
  6661. this.onProgress = onProgress;
  6662. this.onError = onError;
  6663. this.itemStart = function ( url ) {
  6664. total ++;
  6665. };
  6666. this.itemEnd = function ( url ) {
  6667. loaded ++;
  6668. if ( scope.onProgress !== undefined ) {
  6669. scope.onProgress( url, loaded, total );
  6670. }
  6671. if ( loaded === total && scope.onLoad !== undefined ) {
  6672. scope.onLoad();
  6673. }
  6674. };
  6675. };
  6676. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6677. /**
  6678. * @author mrdoob / http://mrdoob.com/
  6679. */
  6680. THREE.BufferGeometryLoader = function ( manager ) {
  6681. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6682. };
  6683. THREE.BufferGeometryLoader.prototype = {
  6684. constructor: THREE.BufferGeometryLoader,
  6685. load: function ( url, onLoad, onProgress, onError ) {
  6686. var scope = this;
  6687. var loader = new THREE.XHRLoader();
  6688. loader.setCrossOrigin( this.crossOrigin );
  6689. loader.load( url, function ( text ) {
  6690. onLoad( scope.parse( JSON.parse( text ) ) );
  6691. } );
  6692. },
  6693. setCrossOrigin: function ( value ) {
  6694. this.crossOrigin = value;
  6695. },
  6696. parse: function ( json ) {
  6697. var geometry = new THREE.BufferGeometry();
  6698. var attributes = json.attributes;
  6699. var offsets = json.offsets;
  6700. var boundingSphere = json.boundingSphere;
  6701. for ( var key in attributes ) {
  6702. var attribute = attributes[ key ];
  6703. geometry.attributes[ key ] = {
  6704. itemSize: attribute.itemSize,
  6705. array: new self[ attribute.type ]( attribute.array )
  6706. }
  6707. }
  6708. if ( offsets !== undefined ) {
  6709. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  6710. }
  6711. if ( boundingSphere !== undefined ) {
  6712. geometry.boundingSphere = new THREE.Sphere(
  6713. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  6714. boundingSphere.radius
  6715. );
  6716. }
  6717. return geometry;
  6718. }
  6719. };
  6720. /**
  6721. * @author mrdoob / http://mrdoob.com/
  6722. */
  6723. THREE.GeometryLoader = function ( manager ) {
  6724. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6725. };
  6726. THREE.GeometryLoader.prototype = {
  6727. constructor: THREE.GeometryLoader,
  6728. load: function ( url, onLoad, onProgress, onError ) {
  6729. var scope = this;
  6730. var loader = new THREE.XHRLoader();
  6731. loader.setCrossOrigin( this.crossOrigin );
  6732. loader.load( url, function ( text ) {
  6733. onLoad( scope.parse( JSON.parse( text ) ) );
  6734. } );
  6735. },
  6736. setCrossOrigin: function ( value ) {
  6737. this.crossOrigin = value;
  6738. },
  6739. parse: function ( json ) {
  6740. }
  6741. };
  6742. /**
  6743. * @author mrdoob / http://mrdoob.com/
  6744. */
  6745. THREE.MaterialLoader = function ( manager ) {
  6746. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6747. };
  6748. THREE.MaterialLoader.prototype = {
  6749. constructor: THREE.MaterialLoader,
  6750. load: function ( url, onLoad, onProgress, onError ) {
  6751. var scope = this;
  6752. var loader = new THREE.XHRLoader();
  6753. loader.setCrossOrigin( this.crossOrigin );
  6754. loader.load( url, function ( text ) {
  6755. onLoad( scope.parse( JSON.parse( text ) ) );
  6756. } );
  6757. },
  6758. setCrossOrigin: function ( value ) {
  6759. this.crossOrigin = value;
  6760. },
  6761. parse: function ( json ) {
  6762. var material = new THREE[ json.type ];
  6763. if ( json.color !== undefined ) material.color.setHex( json.color );
  6764. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  6765. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  6766. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  6767. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  6768. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  6769. if ( json.blending !== undefined ) material.blending = json.blending;
  6770. if ( json.side !== undefined ) material.side = json.side;
  6771. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  6772. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  6773. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  6774. if ( json.materials !== undefined ) {
  6775. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  6776. material.materials.push( this.parse( json.materials[ i ] ) );
  6777. }
  6778. }
  6779. return material;
  6780. }
  6781. };
  6782. /**
  6783. * @author mrdoob / http://mrdoob.com/
  6784. */
  6785. THREE.ObjectLoader = function ( manager ) {
  6786. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6787. };
  6788. THREE.ObjectLoader.prototype = {
  6789. constructor: THREE.ObjectLoader,
  6790. load: function ( url, onLoad, onProgress, onError ) {
  6791. var scope = this;
  6792. var loader = new THREE.XHRLoader( scope.manager );
  6793. loader.setCrossOrigin( this.crossOrigin );
  6794. loader.load( url, function ( text ) {
  6795. onLoad( scope.parse( JSON.parse( text ) ) );
  6796. } );
  6797. },
  6798. setCrossOrigin: function ( value ) {
  6799. this.crossOrigin = value;
  6800. },
  6801. parse: function ( json ) {
  6802. var geometries = this.parseGeometries( json.geometries );
  6803. var materials = this.parseMaterials( json.materials );
  6804. var object = this.parseObject( json.object, geometries, materials );
  6805. return object;
  6806. },
  6807. parseGeometries: function ( json ) {
  6808. var geometries = {};
  6809. if ( json !== undefined ) {
  6810. var geometryLoader = new THREE.JSONLoader();
  6811. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  6812. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6813. var geometry;
  6814. var data = json[ i ];
  6815. switch ( data.type ) {
  6816. case 'PlaneGeometry':
  6817. geometry = new THREE.PlaneGeometry(
  6818. data.width,
  6819. data.height,
  6820. data.widthSegments,
  6821. data.heightSegments
  6822. );
  6823. break;
  6824. case 'CircleGeometry':
  6825. geometry = new THREE.CircleGeometry(
  6826. data.radius,
  6827. data.segments
  6828. );
  6829. break;
  6830. case 'CubeGeometry':
  6831. geometry = new THREE.CubeGeometry(
  6832. data.width,
  6833. data.height,
  6834. data.depth,
  6835. data.widthSegments,
  6836. data.heightSegments,
  6837. data.depthSegments
  6838. );
  6839. break;
  6840. case 'CylinderGeometry':
  6841. geometry = new THREE.CylinderGeometry(
  6842. data.radiusTop,
  6843. data.radiusBottom,
  6844. data.height,
  6845. data.radialSegments,
  6846. data.heightSegments,
  6847. data.openEnded
  6848. );
  6849. break;
  6850. case 'SphereGeometry':
  6851. geometry = new THREE.SphereGeometry(
  6852. data.radius,
  6853. data.widthSegments,
  6854. data.heightSegments,
  6855. data.phiStart,
  6856. data.phiLength,
  6857. data.thetaStart,
  6858. data.thetaLength
  6859. );
  6860. break;
  6861. case 'IcosahedronGeometry':
  6862. geometry = new THREE.IcosahedronGeometry(
  6863. data.radius,
  6864. data.detail
  6865. );
  6866. break;
  6867. case 'TorusGeometry':
  6868. geometry = new THREE.TorusGeometry(
  6869. data.radius,
  6870. data.tube,
  6871. data.radialSegments,
  6872. data.tubularSegments,
  6873. data.arc
  6874. );
  6875. break;
  6876. case 'TorusKnotGeometry':
  6877. geometry = new THREE.TorusKnotGeometry(
  6878. data.radius,
  6879. data.tube,
  6880. data.radialSegments,
  6881. data.tubularSegments,
  6882. data.p,
  6883. data.q,
  6884. data.heightScale
  6885. );
  6886. break;
  6887. case 'BufferGeometry':
  6888. geometry = bufferGeometryLoader.parse( data.data );
  6889. break;
  6890. case 'Geometry':
  6891. geometry = geometryLoader.parse( data.data ).geometry;
  6892. break;
  6893. }
  6894. geometry.uuid = data.uuid;
  6895. if ( data.name !== undefined ) geometry.name = data.name;
  6896. geometries[ data.uuid ] = geometry;
  6897. }
  6898. }
  6899. return geometries;
  6900. },
  6901. parseMaterials: function ( json ) {
  6902. var materials = {};
  6903. if ( json !== undefined ) {
  6904. var loader = new THREE.MaterialLoader();
  6905. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6906. var data = json[ i ];
  6907. var material = loader.parse( data );
  6908. material.uuid = data.uuid;
  6909. if ( data.name !== undefined ) material.name = data.name;
  6910. materials[ data.uuid ] = material;
  6911. }
  6912. }
  6913. return materials;
  6914. },
  6915. parseObject: function () {
  6916. var matrix = new THREE.Matrix4();
  6917. return function ( data, geometries, materials ) {
  6918. var object;
  6919. switch ( data.type ) {
  6920. case 'Scene':
  6921. object = new THREE.Scene();
  6922. break;
  6923. case 'PerspectiveCamera':
  6924. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6925. break;
  6926. case 'OrthographicCamera':
  6927. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6928. break;
  6929. case 'AmbientLight':
  6930. object = new THREE.AmbientLight( data.color );
  6931. break;
  6932. case 'DirectionalLight':
  6933. object = new THREE.DirectionalLight( data.color, data.intensity );
  6934. break;
  6935. case 'PointLight':
  6936. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6937. break;
  6938. case 'SpotLight':
  6939. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6940. break;
  6941. case 'HemisphereLight':
  6942. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6943. break;
  6944. case 'Mesh':
  6945. var geometry = geometries[ data.geometry ];
  6946. var material = materials[ data.material ];
  6947. if ( geometry === undefined ) {
  6948. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  6949. }
  6950. if ( material === undefined ) {
  6951. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  6952. }
  6953. object = new THREE.Mesh( geometry, material );
  6954. break;
  6955. case 'Sprite':
  6956. var material = materials[ data.material ];
  6957. if ( material === undefined ) {
  6958. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  6959. }
  6960. object = new THREE.Sprite( material );
  6961. break;
  6962. default:
  6963. object = new THREE.Object3D();
  6964. }
  6965. object.uuid = data.uuid;
  6966. if ( data.name !== undefined ) object.name = data.name;
  6967. if ( data.matrix !== undefined ) {
  6968. matrix.fromArray( data.matrix );
  6969. matrix.decompose( object.position, object.quaternion, object.scale );
  6970. } else {
  6971. if ( data.position !== undefined ) object.position.fromArray( data.position );
  6972. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  6973. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  6974. }
  6975. if ( data.visible !== undefined ) object.visible = data.visible;
  6976. if ( data.userData !== undefined ) object.userData = data.userData;
  6977. if ( data.children !== undefined ) {
  6978. for ( var child in data.children ) {
  6979. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6980. }
  6981. }
  6982. return object;
  6983. }
  6984. }()
  6985. };
  6986. /**
  6987. * @author alteredq / http://alteredqualia.com/
  6988. */
  6989. THREE.SceneLoader = function () {
  6990. this.onLoadStart = function () {};
  6991. this.onLoadProgress = function() {};
  6992. this.onLoadComplete = function () {};
  6993. this.callbackSync = function () {};
  6994. this.callbackProgress = function () {};
  6995. this.geometryHandlers = {};
  6996. this.hierarchyHandlers = {};
  6997. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6998. };
  6999. THREE.SceneLoader.prototype = {
  7000. constructor: THREE.SceneLoader,
  7001. load: function ( url, onLoad, onProgress, onError ) {
  7002. var scope = this;
  7003. var loader = new THREE.XHRLoader( scope.manager );
  7004. loader.setCrossOrigin( this.crossOrigin );
  7005. loader.load( url, function ( text ) {
  7006. scope.parse( JSON.parse( text ), onLoad, url );
  7007. } );
  7008. },
  7009. setCrossOrigin: function ( value ) {
  7010. this.crossOrigin = value;
  7011. },
  7012. addGeometryHandler: function ( typeID, loaderClass ) {
  7013. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  7014. },
  7015. addHierarchyHandler: function ( typeID, loaderClass ) {
  7016. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7017. },
  7018. parse: function ( json, callbackFinished, url ) {
  7019. var scope = this;
  7020. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7021. var geometry, material, camera, fog,
  7022. texture, images, color,
  7023. light, hex, intensity,
  7024. counter_models, counter_textures,
  7025. total_models, total_textures,
  7026. result;
  7027. var target_array = [];
  7028. var data = json;
  7029. // async geometry loaders
  7030. for ( var typeID in this.geometryHandlers ) {
  7031. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7032. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7033. }
  7034. // async hierachy loaders
  7035. for ( var typeID in this.hierarchyHandlers ) {
  7036. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7037. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7038. }
  7039. counter_models = 0;
  7040. counter_textures = 0;
  7041. result = {
  7042. scene: new THREE.Scene(),
  7043. geometries: {},
  7044. face_materials: {},
  7045. materials: {},
  7046. textures: {},
  7047. objects: {},
  7048. cameras: {},
  7049. lights: {},
  7050. fogs: {},
  7051. empties: {},
  7052. groups: {}
  7053. };
  7054. if ( data.transform ) {
  7055. var position = data.transform.position,
  7056. rotation = data.transform.rotation,
  7057. scale = data.transform.scale;
  7058. if ( position ) {
  7059. result.scene.position.fromArray( position );
  7060. }
  7061. if ( rotation ) {
  7062. result.scene.rotation.fromArray( rotation );
  7063. }
  7064. if ( scale ) {
  7065. result.scene.scale.fromArray( scale );
  7066. }
  7067. if ( position || rotation || scale ) {
  7068. result.scene.updateMatrix();
  7069. result.scene.updateMatrixWorld();
  7070. }
  7071. }
  7072. function get_url( source_url, url_type ) {
  7073. if ( url_type == "relativeToHTML" ) {
  7074. return source_url;
  7075. } else {
  7076. return urlBase + "/" + source_url;
  7077. }
  7078. };
  7079. // toplevel loader function, delegates to handle_children
  7080. function handle_objects() {
  7081. handle_children( result.scene, data.objects );
  7082. }
  7083. // handle all the children from the loaded json and attach them to given parent
  7084. function handle_children( parent, children ) {
  7085. var mat, dst, pos, rot, scl, quat;
  7086. for ( var objID in children ) {
  7087. // check by id if child has already been handled,
  7088. // if not, create new object
  7089. var object = result.objects[ objID ];
  7090. var objJSON = children[ objID ];
  7091. if ( object === undefined ) {
  7092. // meshes
  7093. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7094. if ( objJSON.loading === undefined ) {
  7095. var reservedTypes = {
  7096. "type": 1, "url": 1, "material": 1,
  7097. "position": 1, "rotation": 1, "scale" : 1,
  7098. "visible": 1, "children": 1, "userData": 1,
  7099. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7100. };
  7101. var loaderParameters = {};
  7102. for ( var parType in objJSON ) {
  7103. if ( ! ( parType in reservedTypes ) ) {
  7104. loaderParameters[ parType ] = objJSON[ parType ];
  7105. }
  7106. }
  7107. material = result.materials[ objJSON.material ];
  7108. objJSON.loading = true;
  7109. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7110. // ColladaLoader
  7111. if ( loader.options ) {
  7112. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7113. // UTF8Loader
  7114. // OBJLoader
  7115. } else {
  7116. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7117. }
  7118. }
  7119. } else if ( objJSON.geometry !== undefined ) {
  7120. geometry = result.geometries[ objJSON.geometry ];
  7121. // geometry already loaded
  7122. if ( geometry ) {
  7123. var needsTangents = false;
  7124. material = result.materials[ objJSON.material ];
  7125. needsTangents = material instanceof THREE.ShaderMaterial;
  7126. pos = objJSON.position;
  7127. rot = objJSON.rotation;
  7128. scl = objJSON.scale;
  7129. mat = objJSON.matrix;
  7130. quat = objJSON.quaternion;
  7131. // use materials from the model file
  7132. // if there is no material specified in the object
  7133. if ( ! objJSON.material ) {
  7134. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7135. }
  7136. // use materials from the model file
  7137. // if there is just empty face material
  7138. // (must create new material as each model has its own face material)
  7139. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7140. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7141. }
  7142. if ( material instanceof THREE.MeshFaceMaterial ) {
  7143. for ( var i = 0; i < material.materials.length; i ++ ) {
  7144. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7145. }
  7146. }
  7147. if ( needsTangents ) {
  7148. geometry.computeTangents();
  7149. }
  7150. if ( objJSON.skin ) {
  7151. object = new THREE.SkinnedMesh( geometry, material );
  7152. } else if ( objJSON.morph ) {
  7153. object = new THREE.MorphAnimMesh( geometry, material );
  7154. if ( objJSON.duration !== undefined ) {
  7155. object.duration = objJSON.duration;
  7156. }
  7157. if ( objJSON.time !== undefined ) {
  7158. object.time = objJSON.time;
  7159. }
  7160. if ( objJSON.mirroredLoop !== undefined ) {
  7161. object.mirroredLoop = objJSON.mirroredLoop;
  7162. }
  7163. if ( material.morphNormals ) {
  7164. geometry.computeMorphNormals();
  7165. }
  7166. } else {
  7167. object = new THREE.Mesh( geometry, material );
  7168. }
  7169. object.name = objID;
  7170. if ( mat ) {
  7171. object.matrixAutoUpdate = false;
  7172. object.matrix.set(
  7173. mat[0], mat[1], mat[2], mat[3],
  7174. mat[4], mat[5], mat[6], mat[7],
  7175. mat[8], mat[9], mat[10], mat[11],
  7176. mat[12], mat[13], mat[14], mat[15]
  7177. );
  7178. } else {
  7179. object.position.fromArray( pos );
  7180. if ( quat ) {
  7181. object.quaternion.fromArray( quat );
  7182. } else {
  7183. object.rotation.fromArray( rot );
  7184. }
  7185. object.scale.fromArray( scl );
  7186. }
  7187. object.visible = objJSON.visible;
  7188. object.castShadow = objJSON.castShadow;
  7189. object.receiveShadow = objJSON.receiveShadow;
  7190. parent.add( object );
  7191. result.objects[ objID ] = object;
  7192. }
  7193. // lights
  7194. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7195. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  7196. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  7197. var color = objJSON.color;
  7198. var intensity = objJSON.intensity;
  7199. var distance = objJSON.distance;
  7200. var position = objJSON.position;
  7201. var rotation = objJSON.rotation;
  7202. switch ( objJSON.type ) {
  7203. case 'AmbientLight':
  7204. light = new THREE.AmbientLight( color );
  7205. break;
  7206. case 'PointLight':
  7207. light = new THREE.PointLight( color, intensity, distance );
  7208. light.position.fromArray( position );
  7209. break;
  7210. case 'DirectionalLight':
  7211. light = new THREE.DirectionalLight( color, intensity );
  7212. light.position.fromArray( objJSON.direction );
  7213. break;
  7214. case 'SpotLight':
  7215. light = new THREE.SpotLight( color, intensity, distance, 1 );
  7216. light.angle = objJSON.angle;
  7217. light.position.fromArray( position );
  7218. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7219. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7220. break;
  7221. case 'HemisphereLight':
  7222. light = new THREE.DirectionalLight( color, intensity, distance );
  7223. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7224. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7225. break;
  7226. case 'AreaLight':
  7227. light = new THREE.AreaLight(color, intensity);
  7228. light.position.fromArray( position );
  7229. light.width = objJSON.size;
  7230. light.height = objJSON.size_y;
  7231. break;
  7232. }
  7233. parent.add( light );
  7234. light.name = objID;
  7235. result.lights[ objID ] = light;
  7236. result.objects[ objID ] = light;
  7237. // cameras
  7238. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7239. pos = objJSON.position;
  7240. rot = objJSON.rotation;
  7241. quat = objJSON.quaternion;
  7242. if ( objJSON.type === "PerspectiveCamera" ) {
  7243. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7244. } else if ( objJSON.type === "OrthographicCamera" ) {
  7245. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7246. }
  7247. camera.name = objID;
  7248. camera.position.fromArray( pos );
  7249. if ( quat !== undefined ) {
  7250. camera.quaternion.fromArray( quat );
  7251. } else if ( rot !== undefined ) {
  7252. camera.rotation.fromArray( rot );
  7253. }
  7254. parent.add( camera );
  7255. result.cameras[ objID ] = camera;
  7256. result.objects[ objID ] = camera;
  7257. // pure Object3D
  7258. } else {
  7259. pos = objJSON.position;
  7260. rot = objJSON.rotation;
  7261. scl = objJSON.scale;
  7262. quat = objJSON.quaternion;
  7263. object = new THREE.Object3D();
  7264. object.name = objID;
  7265. object.position.fromArray( pos );
  7266. if ( quat ) {
  7267. object.quaternion.fromArray( quat );
  7268. } else {
  7269. object.rotation.fromArray( rot );
  7270. }
  7271. object.scale.fromArray( scl );
  7272. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7273. parent.add( object );
  7274. result.objects[ objID ] = object;
  7275. result.empties[ objID ] = object;
  7276. }
  7277. if ( object ) {
  7278. if ( objJSON.userData !== undefined ) {
  7279. for ( var key in objJSON.userData ) {
  7280. var value = objJSON.userData[ key ];
  7281. object.userData[ key ] = value;
  7282. }
  7283. }
  7284. if ( objJSON.groups !== undefined ) {
  7285. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7286. var groupID = objJSON.groups[ i ];
  7287. if ( result.groups[ groupID ] === undefined ) {
  7288. result.groups[ groupID ] = [];
  7289. }
  7290. result.groups[ groupID ].push( objID );
  7291. }
  7292. }
  7293. }
  7294. }
  7295. if ( object !== undefined && objJSON.children !== undefined ) {
  7296. handle_children( object, objJSON.children );
  7297. }
  7298. }
  7299. };
  7300. function handle_mesh( geo, mat, id ) {
  7301. result.geometries[ id ] = geo;
  7302. result.face_materials[ id ] = mat;
  7303. handle_objects();
  7304. };
  7305. function handle_hierarchy( node, id, parent, material, obj ) {
  7306. var p = obj.position;
  7307. var r = obj.rotation;
  7308. var q = obj.quaternion;
  7309. var s = obj.scale;
  7310. node.position.fromArray( p );
  7311. if ( q ) {
  7312. node.quaternion.fromArray( q );
  7313. } else {
  7314. node.rotation.fromArray( r );
  7315. }
  7316. node.scale.fromArray( s );
  7317. // override children materials
  7318. // if object material was specified in JSON explicitly
  7319. if ( material ) {
  7320. node.traverse( function ( child ) {
  7321. child.material = material;
  7322. } );
  7323. }
  7324. // override children visibility
  7325. // with root node visibility as specified in JSON
  7326. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7327. node.traverse( function ( child ) {
  7328. child.visible = visible;
  7329. } );
  7330. parent.add( node );
  7331. node.name = id;
  7332. result.objects[ id ] = node;
  7333. handle_objects();
  7334. };
  7335. function create_callback_geometry( id ) {
  7336. return function ( geo, mat ) {
  7337. geo.name = id;
  7338. handle_mesh( geo, mat, id );
  7339. counter_models -= 1;
  7340. scope.onLoadComplete();
  7341. async_callback_gate();
  7342. }
  7343. };
  7344. function create_callback_hierachy( id, parent, material, obj ) {
  7345. return function ( event ) {
  7346. var result;
  7347. // loaders which use EventDispatcher
  7348. if ( event.content ) {
  7349. result = event.content;
  7350. // ColladaLoader
  7351. } else if ( event.dae ) {
  7352. result = event.scene;
  7353. // UTF8Loader
  7354. } else {
  7355. result = event;
  7356. }
  7357. handle_hierarchy( result, id, parent, material, obj );
  7358. counter_models -= 1;
  7359. scope.onLoadComplete();
  7360. async_callback_gate();
  7361. }
  7362. };
  7363. function create_callback_embed( id ) {
  7364. return function ( geo, mat ) {
  7365. geo.name = id;
  7366. result.geometries[ id ] = geo;
  7367. result.face_materials[ id ] = mat;
  7368. }
  7369. };
  7370. function async_callback_gate() {
  7371. var progress = {
  7372. totalModels : total_models,
  7373. totalTextures : total_textures,
  7374. loadedModels : total_models - counter_models,
  7375. loadedTextures : total_textures - counter_textures
  7376. };
  7377. scope.callbackProgress( progress, result );
  7378. scope.onLoadProgress();
  7379. if ( counter_models === 0 && counter_textures === 0 ) {
  7380. finalize();
  7381. callbackFinished( result );
  7382. }
  7383. };
  7384. function finalize() {
  7385. // take care of targets which could be asynchronously loaded objects
  7386. for ( var i = 0; i < target_array.length; i ++ ) {
  7387. var ta = target_array[ i ];
  7388. var target = result.objects[ ta.targetName ];
  7389. if ( target ) {
  7390. ta.object.target = target;
  7391. } else {
  7392. // if there was error and target of specified name doesn't exist in the scene file
  7393. // create instead dummy target
  7394. // (target must be added to scene explicitly as parent is already added)
  7395. ta.object.target = new THREE.Object3D();
  7396. result.scene.add( ta.object.target );
  7397. }
  7398. ta.object.target.userData.targetInverse = ta.object;
  7399. }
  7400. };
  7401. var callbackTexture = function ( count ) {
  7402. counter_textures -= count;
  7403. async_callback_gate();
  7404. scope.onLoadComplete();
  7405. };
  7406. // must use this instead of just directly calling callbackTexture
  7407. // because of closure in the calling context loop
  7408. var generateTextureCallback = function ( count ) {
  7409. return function () {
  7410. callbackTexture( count );
  7411. };
  7412. };
  7413. function traverse_json_hierarchy( objJSON, callback ) {
  7414. callback( objJSON );
  7415. if ( objJSON.children !== undefined ) {
  7416. for ( var objChildID in objJSON.children ) {
  7417. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7418. }
  7419. }
  7420. };
  7421. // first go synchronous elements
  7422. // fogs
  7423. var fogID, fogJSON;
  7424. for ( fogID in data.fogs ) {
  7425. fogJSON = data.fogs[ fogID ];
  7426. if ( fogJSON.type === "linear" ) {
  7427. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7428. } else if ( fogJSON.type === "exp2" ) {
  7429. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7430. }
  7431. color = fogJSON.color;
  7432. fog.color.setRGB( color[0], color[1], color[2] );
  7433. result.fogs[ fogID ] = fog;
  7434. }
  7435. // now come potentially asynchronous elements
  7436. // geometries
  7437. // count how many geometries will be loaded asynchronously
  7438. var geoID, geoJSON;
  7439. for ( geoID in data.geometries ) {
  7440. geoJSON = data.geometries[ geoID ];
  7441. if ( geoJSON.type in this.geometryHandlers ) {
  7442. counter_models += 1;
  7443. scope.onLoadStart();
  7444. }
  7445. }
  7446. // count how many hierarchies will be loaded asynchronously
  7447. for ( var objID in data.objects ) {
  7448. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7449. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7450. counter_models += 1;
  7451. scope.onLoadStart();
  7452. }
  7453. });
  7454. }
  7455. total_models = counter_models;
  7456. for ( geoID in data.geometries ) {
  7457. geoJSON = data.geometries[ geoID ];
  7458. if ( geoJSON.type === "cube" ) {
  7459. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7460. geometry.name = geoID;
  7461. result.geometries[ geoID ] = geometry;
  7462. } else if ( geoJSON.type === "plane" ) {
  7463. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7464. geometry.name = geoID;
  7465. result.geometries[ geoID ] = geometry;
  7466. } else if ( geoJSON.type === "sphere" ) {
  7467. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7468. geometry.name = geoID;
  7469. result.geometries[ geoID ] = geometry;
  7470. } else if ( geoJSON.type === "cylinder" ) {
  7471. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7472. geometry.name = geoID;
  7473. result.geometries[ geoID ] = geometry;
  7474. } else if ( geoJSON.type === "torus" ) {
  7475. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7476. geometry.name = geoID;
  7477. result.geometries[ geoID ] = geometry;
  7478. } else if ( geoJSON.type === "icosahedron" ) {
  7479. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7480. geometry.name = geoID;
  7481. result.geometries[ geoID ] = geometry;
  7482. } else if ( geoJSON.type in this.geometryHandlers ) {
  7483. var loaderParameters = {};
  7484. for ( var parType in geoJSON ) {
  7485. if ( parType !== "type" && parType !== "url" ) {
  7486. loaderParameters[ parType ] = geoJSON[ parType ];
  7487. }
  7488. }
  7489. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7490. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7491. } else if ( geoJSON.type === "embedded" ) {
  7492. var modelJson = data.embeds[ geoJSON.id ],
  7493. texture_path = "";
  7494. // pass metadata along to jsonLoader so it knows the format version
  7495. modelJson.metadata = data.metadata;
  7496. if ( modelJson ) {
  7497. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7498. var model = jsonLoader.parse( modelJson, texture_path );
  7499. create_callback_embed( geoID )( model.geometry, model.materials );
  7500. }
  7501. }
  7502. }
  7503. // textures
  7504. // count how many textures will be loaded asynchronously
  7505. var textureID, textureJSON;
  7506. for ( textureID in data.textures ) {
  7507. textureJSON = data.textures[ textureID ];
  7508. if ( textureJSON.url instanceof Array ) {
  7509. counter_textures += textureJSON.url.length;
  7510. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7511. scope.onLoadStart();
  7512. }
  7513. } else {
  7514. counter_textures += 1;
  7515. scope.onLoadStart();
  7516. }
  7517. }
  7518. total_textures = counter_textures;
  7519. for ( textureID in data.textures ) {
  7520. textureJSON = data.textures[ textureID ];
  7521. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7522. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7523. }
  7524. if ( textureJSON.url instanceof Array ) {
  7525. var count = textureJSON.url.length;
  7526. var url_array = [];
  7527. for( var i = 0; i < count; i ++ ) {
  7528. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7529. }
  7530. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7531. if ( isCompressed ) {
  7532. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7533. } else {
  7534. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7535. }
  7536. } else {
  7537. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7538. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7539. var textureCallback = generateTextureCallback( 1 );
  7540. if ( isCompressed ) {
  7541. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7542. } else {
  7543. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7544. }
  7545. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7546. texture.minFilter = THREE[ textureJSON.minFilter ];
  7547. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7548. texture.magFilter = THREE[ textureJSON.magFilter ];
  7549. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7550. if ( textureJSON.repeat ) {
  7551. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7552. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7553. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7554. }
  7555. if ( textureJSON.offset ) {
  7556. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7557. }
  7558. // handle wrap after repeat so that default repeat can be overriden
  7559. if ( textureJSON.wrap ) {
  7560. var wrapMap = {
  7561. "repeat": THREE.RepeatWrapping,
  7562. "mirror": THREE.MirroredRepeatWrapping
  7563. }
  7564. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7565. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7566. }
  7567. }
  7568. result.textures[ textureID ] = texture;
  7569. }
  7570. // materials
  7571. var matID, matJSON;
  7572. var parID;
  7573. for ( matID in data.materials ) {
  7574. matJSON = data.materials[ matID ];
  7575. for ( parID in matJSON.parameters ) {
  7576. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7577. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7578. } else if ( parID === "shading" ) {
  7579. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7580. } else if ( parID === "side" ) {
  7581. if ( matJSON.parameters[ parID ] == "double" ) {
  7582. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7583. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7584. matJSON.parameters[ parID ] = THREE.BackSide;
  7585. } else {
  7586. matJSON.parameters[ parID ] = THREE.FrontSide;
  7587. }
  7588. } else if ( parID === "blending" ) {
  7589. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7590. } else if ( parID === "combine" ) {
  7591. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7592. } else if ( parID === "vertexColors" ) {
  7593. if ( matJSON.parameters[ parID ] == "face" ) {
  7594. matJSON.parameters[ parID ] = THREE.FaceColors;
  7595. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7596. } else if ( matJSON.parameters[ parID ] ) {
  7597. matJSON.parameters[ parID ] = THREE.VertexColors;
  7598. }
  7599. } else if ( parID === "wrapRGB" ) {
  7600. var v3 = matJSON.parameters[ parID ];
  7601. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7602. }
  7603. }
  7604. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7605. matJSON.parameters.transparent = true;
  7606. }
  7607. if ( matJSON.parameters.normalMap ) {
  7608. var shader = THREE.ShaderLib[ "normalmap" ];
  7609. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7610. var diffuse = matJSON.parameters.color;
  7611. var specular = matJSON.parameters.specular;
  7612. var ambient = matJSON.parameters.ambient;
  7613. var shininess = matJSON.parameters.shininess;
  7614. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7615. if ( matJSON.parameters.normalScale ) {
  7616. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7617. }
  7618. if ( matJSON.parameters.map ) {
  7619. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7620. uniforms[ "enableDiffuse" ].value = true;
  7621. }
  7622. if ( matJSON.parameters.envMap ) {
  7623. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7624. uniforms[ "enableReflection" ].value = true;
  7625. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7626. }
  7627. if ( matJSON.parameters.lightMap ) {
  7628. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7629. uniforms[ "enableAO" ].value = true;
  7630. }
  7631. if ( matJSON.parameters.specularMap ) {
  7632. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7633. uniforms[ "enableSpecular" ].value = true;
  7634. }
  7635. if ( matJSON.parameters.displacementMap ) {
  7636. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7637. uniforms[ "enableDisplacement" ].value = true;
  7638. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7639. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7640. }
  7641. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7642. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7643. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7644. uniforms[ "uShininess" ].value = shininess;
  7645. if ( matJSON.parameters.opacity ) {
  7646. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7647. }
  7648. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7649. material = new THREE.ShaderMaterial( parameters );
  7650. } else {
  7651. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7652. }
  7653. material.name = matID;
  7654. result.materials[ matID ] = material;
  7655. }
  7656. // second pass through all materials to initialize MeshFaceMaterials
  7657. // that could be referring to other materials out of order
  7658. for ( matID in data.materials ) {
  7659. matJSON = data.materials[ matID ];
  7660. if ( matJSON.parameters.materials ) {
  7661. var materialArray = [];
  7662. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7663. var label = matJSON.parameters.materials[ i ];
  7664. materialArray.push( result.materials[ label ] );
  7665. }
  7666. result.materials[ matID ].materials = materialArray;
  7667. }
  7668. }
  7669. // objects ( synchronous init of procedural primitives )
  7670. handle_objects();
  7671. // defaults
  7672. if ( result.cameras && data.defaults.camera ) {
  7673. result.currentCamera = result.cameras[ data.defaults.camera ];
  7674. }
  7675. if ( result.fogs && data.defaults.fog ) {
  7676. result.scene.fog = result.fogs[ data.defaults.fog ];
  7677. }
  7678. // synchronous callback
  7679. scope.callbackSync( result );
  7680. // just in case there are no async elements
  7681. async_callback_gate();
  7682. }
  7683. }
  7684. /**
  7685. * @author mrdoob / http://mrdoob.com/
  7686. */
  7687. THREE.TextureLoader = function ( manager ) {
  7688. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7689. };
  7690. THREE.TextureLoader.prototype = {
  7691. constructor: THREE.TextureLoader,
  7692. load: function ( url, onLoad, onProgress, onError ) {
  7693. var scope = this;
  7694. var loader = new THREE.ImageLoader( scope.manager );
  7695. loader.setCrossOrigin( this.crossOrigin );
  7696. loader.load( url, function ( image ) {
  7697. var texture = new THREE.Texture( image );
  7698. texture.needsUpdate = true;
  7699. if ( onLoad !== undefined ) {
  7700. onLoad( texture );
  7701. }
  7702. } );
  7703. },
  7704. setCrossOrigin: function ( value ) {
  7705. this.crossOrigin = value;
  7706. }
  7707. };
  7708. /**
  7709. * @author mrdoob / http://mrdoob.com/
  7710. * @author alteredq / http://alteredqualia.com/
  7711. */
  7712. THREE.Material = function () {
  7713. this.id = THREE.MaterialIdCount ++;
  7714. this.uuid = THREE.Math.generateUUID();
  7715. this.name = '';
  7716. this.side = THREE.FrontSide;
  7717. this.opacity = 1;
  7718. this.transparent = false;
  7719. this.blending = THREE.NormalBlending;
  7720. this.blendSrc = THREE.SrcAlphaFactor;
  7721. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7722. this.blendEquation = THREE.AddEquation;
  7723. this.depthTest = true;
  7724. this.depthWrite = true;
  7725. this.polygonOffset = false;
  7726. this.polygonOffsetFactor = 0;
  7727. this.polygonOffsetUnits = 0;
  7728. this.alphaTest = 0;
  7729. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7730. this.visible = true;
  7731. this.needsUpdate = true;
  7732. };
  7733. THREE.Material.prototype = {
  7734. constructor: THREE.Material,
  7735. setValues: function ( values ) {
  7736. if ( values === undefined ) return;
  7737. for ( var key in values ) {
  7738. var newValue = values[ key ];
  7739. if ( newValue === undefined ) {
  7740. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7741. continue;
  7742. }
  7743. if ( key in this ) {
  7744. var currentValue = this[ key ];
  7745. if ( currentValue instanceof THREE.Color ) {
  7746. currentValue.set( newValue );
  7747. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7748. currentValue.copy( newValue );
  7749. } else if ( key == 'overdraw') {
  7750. // ensure overdraw is backwards-compatable with legacy boolean type
  7751. this[ key ] = Number(newValue);
  7752. } else {
  7753. this[ key ] = newValue;
  7754. }
  7755. }
  7756. }
  7757. },
  7758. clone: function ( material ) {
  7759. if ( material === undefined ) material = new THREE.Material();
  7760. material.name = this.name;
  7761. material.side = this.side;
  7762. material.opacity = this.opacity;
  7763. material.transparent = this.transparent;
  7764. material.blending = this.blending;
  7765. material.blendSrc = this.blendSrc;
  7766. material.blendDst = this.blendDst;
  7767. material.blendEquation = this.blendEquation;
  7768. material.depthTest = this.depthTest;
  7769. material.depthWrite = this.depthWrite;
  7770. material.polygonOffset = this.polygonOffset;
  7771. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7772. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7773. material.alphaTest = this.alphaTest;
  7774. material.overdraw = this.overdraw;
  7775. material.visible = this.visible;
  7776. return material;
  7777. },
  7778. dispose: function () {
  7779. this.dispatchEvent( { type: 'dispose' } );
  7780. }
  7781. };
  7782. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7783. THREE.MaterialIdCount = 0;
  7784. /**
  7785. * @author mrdoob / http://mrdoob.com/
  7786. * @author alteredq / http://alteredqualia.com/
  7787. *
  7788. * parameters = {
  7789. * color: <hex>,
  7790. * opacity: <float>,
  7791. *
  7792. * blending: THREE.NormalBlending,
  7793. * depthTest: <bool>,
  7794. * depthWrite: <bool>,
  7795. *
  7796. * linewidth: <float>,
  7797. * linecap: "round",
  7798. * linejoin: "round",
  7799. *
  7800. * vertexColors: <bool>
  7801. *
  7802. * fog: <bool>
  7803. * }
  7804. */
  7805. THREE.LineBasicMaterial = function ( parameters ) {
  7806. THREE.Material.call( this );
  7807. this.color = new THREE.Color( 0xffffff );
  7808. this.linewidth = 1;
  7809. this.linecap = 'round';
  7810. this.linejoin = 'round';
  7811. this.vertexColors = false;
  7812. this.fog = true;
  7813. this.setValues( parameters );
  7814. };
  7815. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7816. THREE.LineBasicMaterial.prototype.clone = function () {
  7817. var material = new THREE.LineBasicMaterial();
  7818. THREE.Material.prototype.clone.call( this, material );
  7819. material.color.copy( this.color );
  7820. material.linewidth = this.linewidth;
  7821. material.linecap = this.linecap;
  7822. material.linejoin = this.linejoin;
  7823. material.vertexColors = this.vertexColors;
  7824. material.fog = this.fog;
  7825. return material;
  7826. };
  7827. /**
  7828. * @author alteredq / http://alteredqualia.com/
  7829. *
  7830. * parameters = {
  7831. * color: <hex>,
  7832. * opacity: <float>,
  7833. *
  7834. * blending: THREE.NormalBlending,
  7835. * depthTest: <bool>,
  7836. * depthWrite: <bool>,
  7837. *
  7838. * linewidth: <float>,
  7839. *
  7840. * scale: <float>,
  7841. * dashSize: <float>,
  7842. * gapSize: <float>,
  7843. *
  7844. * vertexColors: <bool>
  7845. *
  7846. * fog: <bool>
  7847. * }
  7848. */
  7849. THREE.LineDashedMaterial = function ( parameters ) {
  7850. THREE.Material.call( this );
  7851. this.color = new THREE.Color( 0xffffff );
  7852. this.linewidth = 1;
  7853. this.scale = 1;
  7854. this.dashSize = 3;
  7855. this.gapSize = 1;
  7856. this.vertexColors = false;
  7857. this.fog = true;
  7858. this.setValues( parameters );
  7859. };
  7860. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7861. THREE.LineDashedMaterial.prototype.clone = function () {
  7862. var material = new THREE.LineDashedMaterial();
  7863. THREE.Material.prototype.clone.call( this, material );
  7864. material.color.copy( this.color );
  7865. material.linewidth = this.linewidth;
  7866. material.scale = this.scale;
  7867. material.dashSize = this.dashSize;
  7868. material.gapSize = this.gapSize;
  7869. material.vertexColors = this.vertexColors;
  7870. material.fog = this.fog;
  7871. return material;
  7872. };
  7873. /**
  7874. * @author mrdoob / http://mrdoob.com/
  7875. * @author alteredq / http://alteredqualia.com/
  7876. *
  7877. * parameters = {
  7878. * color: <hex>,
  7879. * opacity: <float>,
  7880. * map: new THREE.Texture( <Image> ),
  7881. *
  7882. * lightMap: new THREE.Texture( <Image> ),
  7883. *
  7884. * specularMap: new THREE.Texture( <Image> ),
  7885. *
  7886. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7887. * combine: THREE.Multiply,
  7888. * reflectivity: <float>,
  7889. * refractionRatio: <float>,
  7890. *
  7891. * shading: THREE.SmoothShading,
  7892. * blending: THREE.NormalBlending,
  7893. * depthTest: <bool>,
  7894. * depthWrite: <bool>,
  7895. *
  7896. * wireframe: <boolean>,
  7897. * wireframeLinewidth: <float>,
  7898. *
  7899. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7900. *
  7901. * skinning: <bool>,
  7902. * morphTargets: <bool>,
  7903. *
  7904. * fog: <bool>
  7905. * }
  7906. */
  7907. THREE.MeshBasicMaterial = function ( parameters ) {
  7908. THREE.Material.call( this );
  7909. this.color = new THREE.Color( 0xffffff ); // emissive
  7910. this.map = null;
  7911. this.lightMap = null;
  7912. this.specularMap = null;
  7913. this.envMap = null;
  7914. this.combine = THREE.MultiplyOperation;
  7915. this.reflectivity = 1;
  7916. this.refractionRatio = 0.98;
  7917. this.fog = true;
  7918. this.shading = THREE.SmoothShading;
  7919. this.wireframe = false;
  7920. this.wireframeLinewidth = 1;
  7921. this.wireframeLinecap = 'round';
  7922. this.wireframeLinejoin = 'round';
  7923. this.vertexColors = THREE.NoColors;
  7924. this.skinning = false;
  7925. this.morphTargets = false;
  7926. this.setValues( parameters );
  7927. };
  7928. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7929. THREE.MeshBasicMaterial.prototype.clone = function () {
  7930. var material = new THREE.MeshBasicMaterial();
  7931. THREE.Material.prototype.clone.call( this, material );
  7932. material.color.copy( this.color );
  7933. material.map = this.map;
  7934. material.lightMap = this.lightMap;
  7935. material.specularMap = this.specularMap;
  7936. material.envMap = this.envMap;
  7937. material.combine = this.combine;
  7938. material.reflectivity = this.reflectivity;
  7939. material.refractionRatio = this.refractionRatio;
  7940. material.fog = this.fog;
  7941. material.shading = this.shading;
  7942. material.wireframe = this.wireframe;
  7943. material.wireframeLinewidth = this.wireframeLinewidth;
  7944. material.wireframeLinecap = this.wireframeLinecap;
  7945. material.wireframeLinejoin = this.wireframeLinejoin;
  7946. material.vertexColors = this.vertexColors;
  7947. material.skinning = this.skinning;
  7948. material.morphTargets = this.morphTargets;
  7949. return material;
  7950. };
  7951. /**
  7952. * @author mrdoob / http://mrdoob.com/
  7953. * @author alteredq / http://alteredqualia.com/
  7954. *
  7955. * parameters = {
  7956. * color: <hex>,
  7957. * ambient: <hex>,
  7958. * emissive: <hex>,
  7959. * opacity: <float>,
  7960. *
  7961. * map: new THREE.Texture( <Image> ),
  7962. *
  7963. * lightMap: new THREE.Texture( <Image> ),
  7964. *
  7965. * specularMap: new THREE.Texture( <Image> ),
  7966. *
  7967. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7968. * combine: THREE.Multiply,
  7969. * reflectivity: <float>,
  7970. * refractionRatio: <float>,
  7971. *
  7972. * shading: THREE.SmoothShading,
  7973. * blending: THREE.NormalBlending,
  7974. * depthTest: <bool>,
  7975. * depthWrite: <bool>,
  7976. *
  7977. * wireframe: <boolean>,
  7978. * wireframeLinewidth: <float>,
  7979. *
  7980. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7981. *
  7982. * skinning: <bool>,
  7983. * morphTargets: <bool>,
  7984. * morphNormals: <bool>,
  7985. *
  7986. * fog: <bool>
  7987. * }
  7988. */
  7989. THREE.MeshLambertMaterial = function ( parameters ) {
  7990. THREE.Material.call( this );
  7991. this.color = new THREE.Color( 0xffffff ); // diffuse
  7992. this.ambient = new THREE.Color( 0xffffff );
  7993. this.emissive = new THREE.Color( 0x000000 );
  7994. this.wrapAround = false;
  7995. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7996. this.map = null;
  7997. this.lightMap = null;
  7998. this.specularMap = null;
  7999. this.envMap = null;
  8000. this.combine = THREE.MultiplyOperation;
  8001. this.reflectivity = 1;
  8002. this.refractionRatio = 0.98;
  8003. this.fog = true;
  8004. this.shading = THREE.SmoothShading;
  8005. this.wireframe = false;
  8006. this.wireframeLinewidth = 1;
  8007. this.wireframeLinecap = 'round';
  8008. this.wireframeLinejoin = 'round';
  8009. this.vertexColors = THREE.NoColors;
  8010. this.skinning = false;
  8011. this.morphTargets = false;
  8012. this.morphNormals = false;
  8013. this.setValues( parameters );
  8014. };
  8015. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8016. THREE.MeshLambertMaterial.prototype.clone = function () {
  8017. var material = new THREE.MeshLambertMaterial();
  8018. THREE.Material.prototype.clone.call( this, material );
  8019. material.color.copy( this.color );
  8020. material.ambient.copy( this.ambient );
  8021. material.emissive.copy( this.emissive );
  8022. material.wrapAround = this.wrapAround;
  8023. material.wrapRGB.copy( this.wrapRGB );
  8024. material.map = this.map;
  8025. material.lightMap = this.lightMap;
  8026. material.specularMap = this.specularMap;
  8027. material.envMap = this.envMap;
  8028. material.combine = this.combine;
  8029. material.reflectivity = this.reflectivity;
  8030. material.refractionRatio = this.refractionRatio;
  8031. material.fog = this.fog;
  8032. material.shading = this.shading;
  8033. material.wireframe = this.wireframe;
  8034. material.wireframeLinewidth = this.wireframeLinewidth;
  8035. material.wireframeLinecap = this.wireframeLinecap;
  8036. material.wireframeLinejoin = this.wireframeLinejoin;
  8037. material.vertexColors = this.vertexColors;
  8038. material.skinning = this.skinning;
  8039. material.morphTargets = this.morphTargets;
  8040. material.morphNormals = this.morphNormals;
  8041. return material;
  8042. };
  8043. /**
  8044. * @author mrdoob / http://mrdoob.com/
  8045. * @author alteredq / http://alteredqualia.com/
  8046. *
  8047. * parameters = {
  8048. * color: <hex>,
  8049. * ambient: <hex>,
  8050. * emissive: <hex>,
  8051. * specular: <hex>,
  8052. * shininess: <float>,
  8053. * opacity: <float>,
  8054. *
  8055. * map: new THREE.Texture( <Image> ),
  8056. *
  8057. * lightMap: new THREE.Texture( <Image> ),
  8058. *
  8059. * bumpMap: new THREE.Texture( <Image> ),
  8060. * bumpScale: <float>,
  8061. *
  8062. * normalMap: new THREE.Texture( <Image> ),
  8063. * normalScale: <Vector2>,
  8064. *
  8065. * specularMap: new THREE.Texture( <Image> ),
  8066. *
  8067. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8068. * combine: THREE.Multiply,
  8069. * reflectivity: <float>,
  8070. * refractionRatio: <float>,
  8071. *
  8072. * shading: THREE.SmoothShading,
  8073. * blending: THREE.NormalBlending,
  8074. * depthTest: <bool>,
  8075. * depthWrite: <bool>,
  8076. *
  8077. * wireframe: <boolean>,
  8078. * wireframeLinewidth: <float>,
  8079. *
  8080. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8081. *
  8082. * skinning: <bool>,
  8083. * morphTargets: <bool>,
  8084. * morphNormals: <bool>,
  8085. *
  8086. * fog: <bool>
  8087. * }
  8088. */
  8089. THREE.MeshPhongMaterial = function ( parameters ) {
  8090. THREE.Material.call( this );
  8091. this.color = new THREE.Color( 0xffffff ); // diffuse
  8092. this.ambient = new THREE.Color( 0xffffff );
  8093. this.emissive = new THREE.Color( 0x000000 );
  8094. this.specular = new THREE.Color( 0x111111 );
  8095. this.shininess = 30;
  8096. this.metal = false;
  8097. this.perPixel = true;
  8098. this.wrapAround = false;
  8099. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8100. this.map = null;
  8101. this.lightMap = null;
  8102. this.bumpMap = null;
  8103. this.bumpScale = 1;
  8104. this.normalMap = null;
  8105. this.normalScale = new THREE.Vector2( 1, 1 );
  8106. this.specularMap = null;
  8107. this.envMap = null;
  8108. this.combine = THREE.MultiplyOperation;
  8109. this.reflectivity = 1;
  8110. this.refractionRatio = 0.98;
  8111. this.fog = true;
  8112. this.shading = THREE.SmoothShading;
  8113. this.wireframe = false;
  8114. this.wireframeLinewidth = 1;
  8115. this.wireframeLinecap = 'round';
  8116. this.wireframeLinejoin = 'round';
  8117. this.vertexColors = THREE.NoColors;
  8118. this.skinning = false;
  8119. this.morphTargets = false;
  8120. this.morphNormals = false;
  8121. this.setValues( parameters );
  8122. };
  8123. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8124. THREE.MeshPhongMaterial.prototype.clone = function () {
  8125. var material = new THREE.MeshPhongMaterial();
  8126. THREE.Material.prototype.clone.call( this, material );
  8127. material.color.copy( this.color );
  8128. material.ambient.copy( this.ambient );
  8129. material.emissive.copy( this.emissive );
  8130. material.specular.copy( this.specular );
  8131. material.shininess = this.shininess;
  8132. material.metal = this.metal;
  8133. material.perPixel = this.perPixel;
  8134. material.wrapAround = this.wrapAround;
  8135. material.wrapRGB.copy( this.wrapRGB );
  8136. material.map = this.map;
  8137. material.lightMap = this.lightMap;
  8138. material.bumpMap = this.bumpMap;
  8139. material.bumpScale = this.bumpScale;
  8140. material.normalMap = this.normalMap;
  8141. material.normalScale.copy( this.normalScale );
  8142. material.specularMap = this.specularMap;
  8143. material.envMap = this.envMap;
  8144. material.combine = this.combine;
  8145. material.reflectivity = this.reflectivity;
  8146. material.refractionRatio = this.refractionRatio;
  8147. material.fog = this.fog;
  8148. material.shading = this.shading;
  8149. material.wireframe = this.wireframe;
  8150. material.wireframeLinewidth = this.wireframeLinewidth;
  8151. material.wireframeLinecap = this.wireframeLinecap;
  8152. material.wireframeLinejoin = this.wireframeLinejoin;
  8153. material.vertexColors = this.vertexColors;
  8154. material.skinning = this.skinning;
  8155. material.morphTargets = this.morphTargets;
  8156. material.morphNormals = this.morphNormals;
  8157. return material;
  8158. };
  8159. /**
  8160. * @author mrdoob / http://mrdoob.com/
  8161. * @author alteredq / http://alteredqualia.com/
  8162. *
  8163. * parameters = {
  8164. * opacity: <float>,
  8165. *
  8166. * blending: THREE.NormalBlending,
  8167. * depthTest: <bool>,
  8168. * depthWrite: <bool>,
  8169. *
  8170. * wireframe: <boolean>,
  8171. * wireframeLinewidth: <float>
  8172. * }
  8173. */
  8174. THREE.MeshDepthMaterial = function ( parameters ) {
  8175. THREE.Material.call( this );
  8176. this.wireframe = false;
  8177. this.wireframeLinewidth = 1;
  8178. this.setValues( parameters );
  8179. };
  8180. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8181. THREE.MeshDepthMaterial.prototype.clone = function () {
  8182. var material = new THREE.MeshDepthMaterial();
  8183. THREE.Material.prototype.clone.call( this, material );
  8184. material.wireframe = this.wireframe;
  8185. material.wireframeLinewidth = this.wireframeLinewidth;
  8186. return material;
  8187. };
  8188. /**
  8189. * @author mrdoob / http://mrdoob.com/
  8190. *
  8191. * parameters = {
  8192. * opacity: <float>,
  8193. *
  8194. * shading: THREE.FlatShading,
  8195. * blending: THREE.NormalBlending,
  8196. * depthTest: <bool>,
  8197. * depthWrite: <bool>,
  8198. *
  8199. * wireframe: <boolean>,
  8200. * wireframeLinewidth: <float>
  8201. * }
  8202. */
  8203. THREE.MeshNormalMaterial = function ( parameters ) {
  8204. THREE.Material.call( this, parameters );
  8205. this.shading = THREE.FlatShading;
  8206. this.wireframe = false;
  8207. this.wireframeLinewidth = 1;
  8208. this.morphTargets = false;
  8209. this.setValues( parameters );
  8210. };
  8211. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8212. THREE.MeshNormalMaterial.prototype.clone = function () {
  8213. var material = new THREE.MeshNormalMaterial();
  8214. THREE.Material.prototype.clone.call( this, material );
  8215. material.shading = this.shading;
  8216. material.wireframe = this.wireframe;
  8217. material.wireframeLinewidth = this.wireframeLinewidth;
  8218. return material;
  8219. };
  8220. /**
  8221. * @author mrdoob / http://mrdoob.com/
  8222. */
  8223. THREE.MeshFaceMaterial = function ( materials ) {
  8224. this.materials = materials instanceof Array ? materials : [];
  8225. };
  8226. THREE.MeshFaceMaterial.prototype.clone = function () {
  8227. var material = new THREE.MeshFaceMaterial();
  8228. for ( var i = 0; i < this.materials.length; i ++ ) {
  8229. material.materials.push( this.materials[ i ].clone() );
  8230. }
  8231. return material;
  8232. };
  8233. /**
  8234. * @author mrdoob / http://mrdoob.com/
  8235. * @author alteredq / http://alteredqualia.com/
  8236. *
  8237. * parameters = {
  8238. * color: <hex>,
  8239. * opacity: <float>,
  8240. * map: new THREE.Texture( <Image> ),
  8241. *
  8242. * size: <float>,
  8243. *
  8244. * blending: THREE.NormalBlending,
  8245. * depthTest: <bool>,
  8246. * depthWrite: <bool>,
  8247. *
  8248. * vertexColors: <bool>,
  8249. *
  8250. * fog: <bool>
  8251. * }
  8252. */
  8253. THREE.ParticleSystemMaterial = function ( parameters ) {
  8254. THREE.Material.call( this );
  8255. this.color = new THREE.Color( 0xffffff );
  8256. this.map = null;
  8257. this.size = 1;
  8258. this.sizeAttenuation = true;
  8259. this.vertexColors = false;
  8260. this.fog = true;
  8261. this.setValues( parameters );
  8262. };
  8263. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8264. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8265. var material = new THREE.ParticleSystemMaterial();
  8266. THREE.Material.prototype.clone.call( this, material );
  8267. material.color.copy( this.color );
  8268. material.map = this.map;
  8269. material.size = this.size;
  8270. material.sizeAttenuation = this.sizeAttenuation;
  8271. material.vertexColors = this.vertexColors;
  8272. material.fog = this.fog;
  8273. return material;
  8274. };
  8275. // backwards compatibility
  8276. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8277. /**
  8278. * @author alteredq / http://alteredqualia.com/
  8279. *
  8280. * parameters = {
  8281. * fragmentShader: <string>,
  8282. * vertexShader: <string>,
  8283. *
  8284. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8285. *
  8286. * defines: { "label" : "value" },
  8287. *
  8288. * shading: THREE.SmoothShading,
  8289. * blending: THREE.NormalBlending,
  8290. * depthTest: <bool>,
  8291. * depthWrite: <bool>,
  8292. *
  8293. * wireframe: <boolean>,
  8294. * wireframeLinewidth: <float>,
  8295. *
  8296. * lights: <bool>,
  8297. *
  8298. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8299. *
  8300. * skinning: <bool>,
  8301. * morphTargets: <bool>,
  8302. * morphNormals: <bool>,
  8303. *
  8304. * fog: <bool>
  8305. * }
  8306. */
  8307. THREE.ShaderMaterial = function ( parameters ) {
  8308. THREE.Material.call( this );
  8309. this.fragmentShader = "void main() {}";
  8310. this.vertexShader = "void main() {}";
  8311. this.uniforms = {};
  8312. this.defines = {};
  8313. this.attributes = null;
  8314. this.shading = THREE.SmoothShading;
  8315. this.linewidth = 1;
  8316. this.wireframe = false;
  8317. this.wireframeLinewidth = 1;
  8318. this.fog = false; // set to use scene fog
  8319. this.lights = false; // set to use scene lights
  8320. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8321. this.skinning = false; // set to use skinning attribute streams
  8322. this.morphTargets = false; // set to use morph targets
  8323. this.morphNormals = false; // set to use morph normals
  8324. // When rendered geometry doesn't include these attributes but the material does,
  8325. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8326. this.defaultAttributeValues = {
  8327. "color" : [ 1, 1, 1],
  8328. "uv" : [ 0, 0 ],
  8329. "uv2" : [ 0, 0 ]
  8330. };
  8331. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8332. // should always be used to avoid potentially expensive emulation.
  8333. this.index0AttributeName = "position";
  8334. this.setValues( parameters );
  8335. };
  8336. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8337. THREE.ShaderMaterial.prototype.clone = function () {
  8338. var material = new THREE.ShaderMaterial();
  8339. THREE.Material.prototype.clone.call( this, material );
  8340. material.fragmentShader = this.fragmentShader;
  8341. material.vertexShader = this.vertexShader;
  8342. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8343. material.attributes = this.attributes;
  8344. material.defines = this.defines;
  8345. material.shading = this.shading;
  8346. material.wireframe = this.wireframe;
  8347. material.wireframeLinewidth = this.wireframeLinewidth;
  8348. material.fog = this.fog;
  8349. material.lights = this.lights;
  8350. material.vertexColors = this.vertexColors;
  8351. material.skinning = this.skinning;
  8352. material.morphTargets = this.morphTargets;
  8353. material.morphNormals = this.morphNormals;
  8354. return material;
  8355. };
  8356. /**
  8357. * @author alteredq / http://alteredqualia.com/
  8358. *
  8359. * parameters = {
  8360. * color: <hex>,
  8361. * opacity: <float>,
  8362. * map: new THREE.Texture( <Image> ),
  8363. *
  8364. * blending: THREE.NormalBlending,
  8365. * depthTest: <bool>,
  8366. * depthWrite: <bool>,
  8367. *
  8368. * uvOffset: new THREE.Vector2(),
  8369. * uvScale: new THREE.Vector2(),
  8370. *
  8371. * fog: <bool>
  8372. * }
  8373. */
  8374. THREE.SpriteMaterial = function ( parameters ) {
  8375. THREE.Material.call( this );
  8376. // defaults
  8377. this.color = new THREE.Color( 0xffffff );
  8378. this.map = null;
  8379. this.rotation = 0;
  8380. this.fog = false;
  8381. this.uvOffset = new THREE.Vector2( 0, 0 );
  8382. this.uvScale = new THREE.Vector2( 1, 1 );
  8383. // set parameters
  8384. this.setValues( parameters );
  8385. };
  8386. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8387. THREE.SpriteMaterial.prototype.clone = function () {
  8388. var material = new THREE.SpriteMaterial();
  8389. THREE.Material.prototype.clone.call( this, material );
  8390. material.color.copy( this.color );
  8391. material.map = this.map;
  8392. material.rotation = this.rotation;
  8393. material.uvOffset.copy( this.uvOffset );
  8394. material.uvScale.copy( this.uvScale );
  8395. material.fog = this.fog;
  8396. return material;
  8397. };
  8398. /**
  8399. * @author mrdoob / http://mrdoob.com/
  8400. *
  8401. * parameters = {
  8402. * color: <hex>,
  8403. * program: <function>,
  8404. * opacity: <float>,
  8405. * blending: THREE.NormalBlending
  8406. * }
  8407. */
  8408. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8409. THREE.Material.call( this );
  8410. this.color = new THREE.Color( 0xffffff );
  8411. this.program = function ( context, color ) {};
  8412. this.setValues( parameters );
  8413. };
  8414. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8415. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8416. var material = new THREE.SpriteCanvasMaterial();
  8417. THREE.Material.prototype.clone.call( this, material );
  8418. material.color.copy( this.color );
  8419. material.program = this.program;
  8420. return material;
  8421. };
  8422. // backwards compatibility
  8423. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8424. /**
  8425. * @author mrdoob / http://mrdoob.com/
  8426. * @author alteredq / http://alteredqualia.com/
  8427. * @author szimek / https://github.com/szimek/
  8428. */
  8429. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8430. this.id = THREE.TextureIdCount ++;
  8431. this.uuid = THREE.Math.generateUUID();
  8432. this.name = '';
  8433. this.image = image;
  8434. this.mipmaps = [];
  8435. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8436. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8437. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8438. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8439. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8440. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8441. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8442. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8443. this.offset = new THREE.Vector2( 0, 0 );
  8444. this.repeat = new THREE.Vector2( 1, 1 );
  8445. this.generateMipmaps = true;
  8446. this.premultiplyAlpha = false;
  8447. this.flipY = true;
  8448. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8449. this.needsUpdate = false;
  8450. this.onUpdate = null;
  8451. };
  8452. THREE.Texture.prototype = {
  8453. constructor: THREE.Texture,
  8454. clone: function ( texture ) {
  8455. if ( texture === undefined ) texture = new THREE.Texture();
  8456. texture.image = this.image;
  8457. texture.mipmaps = this.mipmaps.slice(0);
  8458. texture.mapping = this.mapping;
  8459. texture.wrapS = this.wrapS;
  8460. texture.wrapT = this.wrapT;
  8461. texture.magFilter = this.magFilter;
  8462. texture.minFilter = this.minFilter;
  8463. texture.anisotropy = this.anisotropy;
  8464. texture.format = this.format;
  8465. texture.type = this.type;
  8466. texture.offset.copy( this.offset );
  8467. texture.repeat.copy( this.repeat );
  8468. texture.generateMipmaps = this.generateMipmaps;
  8469. texture.premultiplyAlpha = this.premultiplyAlpha;
  8470. texture.flipY = this.flipY;
  8471. texture.unpackAlignment = this.unpackAlignment;
  8472. return texture;
  8473. },
  8474. dispose: function () {
  8475. this.dispatchEvent( { type: 'dispose' } );
  8476. }
  8477. };
  8478. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8479. THREE.TextureIdCount = 0;
  8480. /**
  8481. * @author alteredq / http://alteredqualia.com/
  8482. */
  8483. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8484. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8485. this.image = { width: width, height: height };
  8486. this.mipmaps = mipmaps;
  8487. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8488. };
  8489. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8490. THREE.CompressedTexture.prototype.clone = function () {
  8491. var texture = new THREE.CompressedTexture();
  8492. THREE.Texture.prototype.clone.call( this, texture );
  8493. return texture;
  8494. };
  8495. /**
  8496. * @author alteredq / http://alteredqualia.com/
  8497. */
  8498. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8499. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8500. this.image = { data: data, width: width, height: height };
  8501. };
  8502. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8503. THREE.DataTexture.prototype.clone = function () {
  8504. var texture = new THREE.DataTexture();
  8505. THREE.Texture.prototype.clone.call( this, texture );
  8506. return texture;
  8507. };
  8508. /**
  8509. * @author alteredq / http://alteredqualia.com/
  8510. */
  8511. THREE.ParticleSystem = function ( geometry, material ) {
  8512. THREE.Object3D.call( this );
  8513. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8514. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  8515. this.sortParticles = false;
  8516. this.frustumCulled = false;
  8517. };
  8518. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8519. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8520. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8521. object.sortParticles = this.sortParticles;
  8522. THREE.Object3D.prototype.clone.call( this, object );
  8523. return object;
  8524. };
  8525. /**
  8526. * @author mrdoob / http://mrdoob.com/
  8527. */
  8528. THREE.Line = function ( geometry, material, type ) {
  8529. THREE.Object3D.call( this );
  8530. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8531. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8532. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8533. };
  8534. THREE.LineStrip = 0;
  8535. THREE.LinePieces = 1;
  8536. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8537. THREE.Line.prototype.clone = function ( object ) {
  8538. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8539. THREE.Object3D.prototype.clone.call( this, object );
  8540. return object;
  8541. };
  8542. /**
  8543. * @author mrdoob / http://mrdoob.com/
  8544. * @author alteredq / http://alteredqualia.com/
  8545. * @author mikael emtinger / http://gomo.se/
  8546. * @author jonobr1 / http://jonobr1.com/
  8547. */
  8548. THREE.Mesh = function ( geometry, material ) {
  8549. THREE.Object3D.call( this );
  8550. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8551. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8552. this.updateMorphTargets();
  8553. };
  8554. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8555. THREE.Mesh.prototype.updateMorphTargets = function () {
  8556. if ( this.geometry.morphTargets.length > 0 ) {
  8557. this.morphTargetBase = -1;
  8558. this.morphTargetForcedOrder = [];
  8559. this.morphTargetInfluences = [];
  8560. this.morphTargetDictionary = {};
  8561. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8562. this.morphTargetInfluences.push( 0 );
  8563. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8564. }
  8565. }
  8566. };
  8567. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8568. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8569. return this.morphTargetDictionary[ name ];
  8570. }
  8571. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8572. return 0;
  8573. };
  8574. THREE.Mesh.prototype.clone = function ( object ) {
  8575. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8576. THREE.Object3D.prototype.clone.call( this, object );
  8577. return object;
  8578. };
  8579. /**
  8580. * @author mikael emtinger / http://gomo.se/
  8581. * @author alteredq / http://alteredqualia.com/
  8582. */
  8583. THREE.Bone = function( belongsToSkin ) {
  8584. THREE.Object3D.call( this );
  8585. this.skin = belongsToSkin;
  8586. this.skinMatrix = new THREE.Matrix4();
  8587. };
  8588. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8589. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8590. // update local
  8591. if ( this.matrixAutoUpdate ) {
  8592. forceUpdate |= this.updateMatrix();
  8593. }
  8594. // update skin matrix
  8595. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8596. if( parentSkinMatrix ) {
  8597. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8598. } else {
  8599. this.skinMatrix.copy( this.matrix );
  8600. }
  8601. this.matrixWorldNeedsUpdate = false;
  8602. forceUpdate = true;
  8603. }
  8604. // update children
  8605. var child, i, l = this.children.length;
  8606. for ( i = 0; i < l; i ++ ) {
  8607. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8608. }
  8609. };
  8610. /**
  8611. * @author mikael emtinger / http://gomo.se/
  8612. * @author alteredq / http://alteredqualia.com/
  8613. */
  8614. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8615. THREE.Mesh.call( this, geometry, material );
  8616. //
  8617. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8618. // init bones
  8619. this.identityMatrix = new THREE.Matrix4();
  8620. this.bones = [];
  8621. this.boneMatrices = [];
  8622. var b, bone, gbone, p, q, s;
  8623. if ( this.geometry && this.geometry.bones !== undefined ) {
  8624. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8625. gbone = this.geometry.bones[ b ];
  8626. p = gbone.pos;
  8627. q = gbone.rotq;
  8628. s = gbone.scl;
  8629. bone = this.addBone();
  8630. bone.name = gbone.name;
  8631. bone.position.set( p[0], p[1], p[2] );
  8632. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8633. if ( s !== undefined ) {
  8634. bone.scale.set( s[0], s[1], s[2] );
  8635. } else {
  8636. bone.scale.set( 1, 1, 1 );
  8637. }
  8638. }
  8639. for ( b = 0; b < this.bones.length; b ++ ) {
  8640. gbone = this.geometry.bones[ b ];
  8641. bone = this.bones[ b ];
  8642. if ( gbone.parent === -1 ) {
  8643. this.add( bone );
  8644. } else {
  8645. this.bones[ gbone.parent ].add( bone );
  8646. }
  8647. }
  8648. //
  8649. var nBones = this.bones.length;
  8650. if ( this.useVertexTexture ) {
  8651. // layout (1 matrix = 4 pixels)
  8652. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8653. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8654. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8655. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8656. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8657. var size;
  8658. if ( nBones > 256 )
  8659. size = 64;
  8660. else if ( nBones > 64 )
  8661. size = 32;
  8662. else if ( nBones > 16 )
  8663. size = 16;
  8664. else
  8665. size = 8;
  8666. this.boneTextureWidth = size;
  8667. this.boneTextureHeight = size;
  8668. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8669. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8670. this.boneTexture.minFilter = THREE.NearestFilter;
  8671. this.boneTexture.magFilter = THREE.NearestFilter;
  8672. this.boneTexture.generateMipmaps = false;
  8673. this.boneTexture.flipY = false;
  8674. } else {
  8675. this.boneMatrices = new Float32Array( 16 * nBones );
  8676. }
  8677. this.pose();
  8678. }
  8679. };
  8680. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8681. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8682. if ( bone === undefined ) {
  8683. bone = new THREE.Bone( this );
  8684. }
  8685. this.bones.push( bone );
  8686. return bone;
  8687. };
  8688. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8689. var offsetMatrix = new THREE.Matrix4();
  8690. return function ( force ) {
  8691. this.matrixAutoUpdate && this.updateMatrix();
  8692. // update matrixWorld
  8693. if ( this.matrixWorldNeedsUpdate || force ) {
  8694. if ( this.parent ) {
  8695. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8696. } else {
  8697. this.matrixWorld.copy( this.matrix );
  8698. }
  8699. this.matrixWorldNeedsUpdate = false;
  8700. force = true;
  8701. }
  8702. // update children
  8703. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8704. var child = this.children[ i ];
  8705. if ( child instanceof THREE.Bone ) {
  8706. child.update( this.identityMatrix, false );
  8707. } else {
  8708. child.updateMatrixWorld( true );
  8709. }
  8710. }
  8711. // make a snapshot of the bones' rest position
  8712. if ( this.boneInverses == undefined ) {
  8713. this.boneInverses = [];
  8714. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8715. var inverse = new THREE.Matrix4();
  8716. inverse.getInverse( this.bones[ b ].skinMatrix );
  8717. this.boneInverses.push( inverse );
  8718. }
  8719. }
  8720. // flatten bone matrices to array
  8721. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8722. // compute the offset between the current and the original transform;
  8723. // TODO: we could get rid of this multiplication step if the skinMatrix
  8724. // was already representing the offset; however, this requires some
  8725. // major changes to the animation system
  8726. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8727. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8728. }
  8729. if ( this.useVertexTexture ) {
  8730. this.boneTexture.needsUpdate = true;
  8731. }
  8732. };
  8733. }();
  8734. THREE.SkinnedMesh.prototype.pose = function () {
  8735. this.updateMatrixWorld( true );
  8736. this.normalizeSkinWeights();
  8737. };
  8738. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8739. if ( this.geometry instanceof THREE.Geometry ) {
  8740. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8741. var sw = this.geometry.skinWeights[ i ];
  8742. var scale = 1.0 / sw.lengthManhattan();
  8743. if ( scale !== Infinity ) {
  8744. sw.multiplyScalar( scale );
  8745. } else {
  8746. sw.set( 1 ); // this will be normalized by the shader anyway
  8747. }
  8748. }
  8749. } else {
  8750. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8751. }
  8752. };
  8753. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8754. if ( object === undefined ) {
  8755. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8756. }
  8757. THREE.Mesh.prototype.clone.call( this, object );
  8758. return object;
  8759. };
  8760. /**
  8761. * @author alteredq / http://alteredqualia.com/
  8762. */
  8763. THREE.MorphAnimMesh = function ( geometry, material ) {
  8764. THREE.Mesh.call( this, geometry, material );
  8765. // API
  8766. this.duration = 1000; // milliseconds
  8767. this.mirroredLoop = false;
  8768. this.time = 0;
  8769. // internals
  8770. this.lastKeyframe = 0;
  8771. this.currentKeyframe = 0;
  8772. this.direction = 1;
  8773. this.directionBackwards = false;
  8774. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8775. };
  8776. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8777. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8778. this.startKeyframe = start;
  8779. this.endKeyframe = end;
  8780. this.length = this.endKeyframe - this.startKeyframe + 1;
  8781. };
  8782. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8783. this.direction = 1;
  8784. this.directionBackwards = false;
  8785. };
  8786. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8787. this.direction = -1;
  8788. this.directionBackwards = true;
  8789. };
  8790. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8791. var geometry = this.geometry;
  8792. if ( ! geometry.animations ) geometry.animations = {};
  8793. var firstAnimation, animations = geometry.animations;
  8794. var pattern = /([a-z]+)(\d+)/;
  8795. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8796. var morph = geometry.morphTargets[ i ];
  8797. var parts = morph.name.match( pattern );
  8798. if ( parts && parts.length > 1 ) {
  8799. var label = parts[ 1 ];
  8800. var num = parts[ 2 ];
  8801. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8802. var animation = animations[ label ];
  8803. if ( i < animation.start ) animation.start = i;
  8804. if ( i > animation.end ) animation.end = i;
  8805. if ( ! firstAnimation ) firstAnimation = label;
  8806. }
  8807. }
  8808. geometry.firstAnimation = firstAnimation;
  8809. };
  8810. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8811. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8812. this.geometry.animations[ label ] = { start: start, end: end };
  8813. };
  8814. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8815. var animation = this.geometry.animations[ label ];
  8816. if ( animation ) {
  8817. this.setFrameRange( animation.start, animation.end );
  8818. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8819. this.time = 0;
  8820. } else {
  8821. console.warn( "animation[" + label + "] undefined" );
  8822. }
  8823. };
  8824. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8825. var frameTime = this.duration / this.length;
  8826. this.time += this.direction * delta;
  8827. if ( this.mirroredLoop ) {
  8828. if ( this.time > this.duration || this.time < 0 ) {
  8829. this.direction *= -1;
  8830. if ( this.time > this.duration ) {
  8831. this.time = this.duration;
  8832. this.directionBackwards = true;
  8833. }
  8834. if ( this.time < 0 ) {
  8835. this.time = 0;
  8836. this.directionBackwards = false;
  8837. }
  8838. }
  8839. } else {
  8840. this.time = this.time % this.duration;
  8841. if ( this.time < 0 ) this.time += this.duration;
  8842. }
  8843. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8844. if ( keyframe !== this.currentKeyframe ) {
  8845. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8846. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8847. this.morphTargetInfluences[ keyframe ] = 0;
  8848. this.lastKeyframe = this.currentKeyframe;
  8849. this.currentKeyframe = keyframe;
  8850. }
  8851. var mix = ( this.time % frameTime ) / frameTime;
  8852. if ( this.directionBackwards ) {
  8853. mix = 1 - mix;
  8854. }
  8855. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8856. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8857. };
  8858. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8859. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8860. object.duration = this.duration;
  8861. object.mirroredLoop = this.mirroredLoop;
  8862. object.time = this.time;
  8863. object.lastKeyframe = this.lastKeyframe;
  8864. object.currentKeyframe = this.currentKeyframe;
  8865. object.direction = this.direction;
  8866. object.directionBackwards = this.directionBackwards;
  8867. THREE.Mesh.prototype.clone.call( this, object );
  8868. return object;
  8869. };
  8870. /**
  8871. * @author mikael emtinger / http://gomo.se/
  8872. * @author alteredq / http://alteredqualia.com/
  8873. * @author mrdoob / http://mrdoob.com/
  8874. */
  8875. THREE.LOD = function () {
  8876. THREE.Object3D.call( this );
  8877. this.objects = [];
  8878. };
  8879. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8880. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8881. if ( distance === undefined ) distance = 0;
  8882. distance = Math.abs( distance );
  8883. for ( var l = 0; l < this.objects.length; l ++ ) {
  8884. if ( distance < this.objects[ l ].distance ) {
  8885. break;
  8886. }
  8887. }
  8888. this.objects.splice( l, 0, { distance: distance, object: object } );
  8889. this.add( object );
  8890. };
  8891. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8892. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8893. if ( distance < this.objects[ i ].distance ) {
  8894. break;
  8895. }
  8896. }
  8897. return this.objects[ i - 1 ].object;
  8898. };
  8899. THREE.LOD.prototype.update = function () {
  8900. var v1 = new THREE.Vector3();
  8901. var v2 = new THREE.Vector3();
  8902. return function ( camera ) {
  8903. if ( this.objects.length > 1 ) {
  8904. v1.setFromMatrixPosition( camera.matrixWorld );
  8905. v2.setFromMatrixPosition( this.matrixWorld );
  8906. var distance = v1.distanceTo( v2 );
  8907. this.objects[ 0 ].object.visible = true;
  8908. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8909. if ( distance >= this.objects[ i ].distance ) {
  8910. this.objects[ i - 1 ].object.visible = false;
  8911. this.objects[ i ].object.visible = true;
  8912. } else {
  8913. break;
  8914. }
  8915. }
  8916. for( ; i < l; i ++ ) {
  8917. this.objects[ i ].object.visible = false;
  8918. }
  8919. }
  8920. };
  8921. }();
  8922. THREE.LOD.prototype.clone = function () {
  8923. // TODO
  8924. };
  8925. /**
  8926. * @author mikael emtinger / http://gomo.se/
  8927. * @author alteredq / http://alteredqualia.com/
  8928. */
  8929. THREE.Sprite = function ( material ) {
  8930. THREE.Object3D.call( this );
  8931. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8932. };
  8933. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8934. /*
  8935. * Custom update matrix
  8936. */
  8937. THREE.Sprite.prototype.updateMatrix = function () {
  8938. this.matrix.compose( this.position, this.quaternion, this.scale );
  8939. this.matrixWorldNeedsUpdate = true;
  8940. };
  8941. THREE.Sprite.prototype.clone = function ( object ) {
  8942. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8943. THREE.Object3D.prototype.clone.call( this, object );
  8944. return object;
  8945. };
  8946. // Backwards compatibility
  8947. THREE.Particle = THREE.Sprite;
  8948. /**
  8949. * @author mrdoob / http://mrdoob.com/
  8950. */
  8951. THREE.Scene = function () {
  8952. THREE.Object3D.call( this );
  8953. this.fog = null;
  8954. this.overrideMaterial = null;
  8955. this.autoUpdate = true; // checked by the renderer
  8956. this.matrixAutoUpdate = false;
  8957. this.__lights = [];
  8958. this.__objectsAdded = [];
  8959. this.__objectsRemoved = [];
  8960. };
  8961. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8962. THREE.Scene.prototype.__addObject = function ( object ) {
  8963. if ( object instanceof THREE.Light ) {
  8964. if ( this.__lights.indexOf( object ) === - 1 ) {
  8965. this.__lights.push( object );
  8966. }
  8967. if ( object.target && object.target.parent === undefined ) {
  8968. this.add( object.target );
  8969. }
  8970. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8971. this.__objectsAdded.push( object );
  8972. // check if previously removed
  8973. var i = this.__objectsRemoved.indexOf( object );
  8974. if ( i !== -1 ) {
  8975. this.__objectsRemoved.splice( i, 1 );
  8976. }
  8977. }
  8978. for ( var c = 0; c < object.children.length; c ++ ) {
  8979. this.__addObject( object.children[ c ] );
  8980. }
  8981. };
  8982. THREE.Scene.prototype.__removeObject = function ( object ) {
  8983. if ( object instanceof THREE.Light ) {
  8984. var i = this.__lights.indexOf( object );
  8985. if ( i !== -1 ) {
  8986. this.__lights.splice( i, 1 );
  8987. }
  8988. if ( object.shadowCascadeArray ) {
  8989. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  8990. this.__removeObject( object.shadowCascadeArray[ x ] );
  8991. }
  8992. }
  8993. } else if ( !( object instanceof THREE.Camera ) ) {
  8994. this.__objectsRemoved.push( object );
  8995. // check if previously added
  8996. var i = this.__objectsAdded.indexOf( object );
  8997. if ( i !== -1 ) {
  8998. this.__objectsAdded.splice( i, 1 );
  8999. }
  9000. }
  9001. for ( var c = 0; c < object.children.length; c ++ ) {
  9002. this.__removeObject( object.children[ c ] );
  9003. }
  9004. };
  9005. THREE.Scene.prototype.clone = function ( object ) {
  9006. if ( object === undefined ) object = new THREE.Scene();
  9007. THREE.Object3D.prototype.clone.call(this, object);
  9008. if ( this.fog !== null ) object.fog = this.fog.clone();
  9009. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9010. object.autoUpdate = this.autoUpdate;
  9011. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9012. return object;
  9013. };
  9014. /**
  9015. * @author mrdoob / http://mrdoob.com/
  9016. * @author alteredq / http://alteredqualia.com/
  9017. */
  9018. THREE.Fog = function ( hex, near, far ) {
  9019. this.name = '';
  9020. this.color = new THREE.Color( hex );
  9021. this.near = ( near !== undefined ) ? near : 1;
  9022. this.far = ( far !== undefined ) ? far : 1000;
  9023. };
  9024. THREE.Fog.prototype.clone = function () {
  9025. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9026. };
  9027. /**
  9028. * @author mrdoob / http://mrdoob.com/
  9029. * @author alteredq / http://alteredqualia.com/
  9030. */
  9031. THREE.FogExp2 = function ( hex, density ) {
  9032. this.name = '';
  9033. this.color = new THREE.Color( hex );
  9034. this.density = ( density !== undefined ) ? density : 0.00025;
  9035. };
  9036. THREE.FogExp2.prototype.clone = function () {
  9037. return new THREE.FogExp2( this.color.getHex(), this.density );
  9038. };
  9039. /**
  9040. * @author mrdoob / http://mrdoob.com/
  9041. */
  9042. THREE.CanvasRenderer = function ( parameters ) {
  9043. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9044. var smoothstep = THREE.Math.smoothstep;
  9045. parameters = parameters || {};
  9046. var _this = this,
  9047. _renderData, _elements, _lights,
  9048. _projector = new THREE.Projector(),
  9049. _canvas = parameters.canvas !== undefined
  9050. ? parameters.canvas
  9051. : document.createElement( 'canvas' ),
  9052. _canvasWidth = _canvas.width,
  9053. _canvasHeight = _canvas.height,
  9054. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9055. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9056. _context = _canvas.getContext( '2d' ),
  9057. _clearColor = new THREE.Color( 0x000000 ),
  9058. _clearAlpha = 0,
  9059. _contextGlobalAlpha = 1,
  9060. _contextGlobalCompositeOperation = 0,
  9061. _contextStrokeStyle = null,
  9062. _contextFillStyle = null,
  9063. _contextLineWidth = null,
  9064. _contextLineCap = null,
  9065. _contextLineJoin = null,
  9066. _contextDashSize = null,
  9067. _contextGapSize = 0,
  9068. _camera,
  9069. _v1, _v2, _v3, _v4,
  9070. _v5 = new THREE.RenderableVertex(),
  9071. _v6 = new THREE.RenderableVertex(),
  9072. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9073. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9074. _color = new THREE.Color(),
  9075. _color1 = new THREE.Color(),
  9076. _color2 = new THREE.Color(),
  9077. _color3 = new THREE.Color(),
  9078. _color4 = new THREE.Color(),
  9079. _diffuseColor = new THREE.Color(),
  9080. _emissiveColor = new THREE.Color(),
  9081. _lightColor = new THREE.Color(),
  9082. _patterns = {}, _imagedatas = {},
  9083. _near, _far,
  9084. _image, _uvs,
  9085. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9086. _clipBox = new THREE.Box2(),
  9087. _clearBox = new THREE.Box2(),
  9088. _elemBox = new THREE.Box2(),
  9089. _ambientLight = new THREE.Color(),
  9090. _directionalLights = new THREE.Color(),
  9091. _pointLights = new THREE.Color(),
  9092. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9093. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  9094. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  9095. _pixelMap = document.createElement( 'canvas' );
  9096. _pixelMap.width = _pixelMap.height = 2;
  9097. _pixelMapContext = _pixelMap.getContext( '2d' );
  9098. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  9099. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  9100. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  9101. _pixelMapData = _pixelMapImage.data;
  9102. _gradientMap = document.createElement( 'canvas' );
  9103. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  9104. _gradientMapContext = _gradientMap.getContext( '2d' );
  9105. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  9106. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  9107. _gradientMapQuality --; // Fix UVs
  9108. // dash+gap fallbacks for Firefox and everything else
  9109. if ( _context.setLineDash === undefined ) {
  9110. if ( _context.mozDash !== undefined ) {
  9111. _context.setLineDash = function ( values ) {
  9112. _context.mozDash = values[ 0 ] !== null ? values : null;
  9113. }
  9114. } else {
  9115. _context.setLineDash = function () {}
  9116. }
  9117. }
  9118. this.domElement = _canvas;
  9119. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9120. ? parameters.devicePixelRatio
  9121. : self.devicePixelRatio !== undefined
  9122. ? self.devicePixelRatio
  9123. : 1;
  9124. this.autoClear = true;
  9125. this.sortObjects = true;
  9126. this.sortElements = true;
  9127. this.info = {
  9128. render: {
  9129. vertices: 0,
  9130. faces: 0
  9131. }
  9132. }
  9133. // WebGLRenderer compatibility
  9134. this.supportsVertexTextures = function () {};
  9135. this.setFaceCulling = function () {};
  9136. this.setSize = function ( width, height, updateStyle ) {
  9137. _canvasWidth = width * this.devicePixelRatio;
  9138. _canvasHeight = height * this.devicePixelRatio;
  9139. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9140. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9141. _canvas.width = _canvasWidth;
  9142. _canvas.height = _canvasHeight;
  9143. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9144. _canvas.style.width = width + 'px';
  9145. _canvas.style.height = height + 'px';
  9146. }
  9147. _clipBox.set(
  9148. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9149. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9150. );
  9151. _clearBox.set(
  9152. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9153. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9154. );
  9155. _contextGlobalAlpha = 1;
  9156. _contextGlobalCompositeOperation = 0;
  9157. _contextStrokeStyle = null;
  9158. _contextFillStyle = null;
  9159. _contextLineWidth = null;
  9160. _contextLineCap = null;
  9161. _contextLineJoin = null;
  9162. };
  9163. this.setClearColor = function ( color, alpha ) {
  9164. _clearColor.set( color );
  9165. _clearAlpha = alpha !== undefined ? alpha : 1;
  9166. _clearBox.set(
  9167. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  9168. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  9169. );
  9170. };
  9171. this.setClearColorHex = function ( hex, alpha ) {
  9172. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9173. this.setClearColor( hex, alpha );
  9174. };
  9175. this.getMaxAnisotropy = function () {
  9176. return 0;
  9177. };
  9178. this.clear = function () {
  9179. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9180. if ( _clearBox.empty() === false ) {
  9181. _clearBox.intersect( _clipBox );
  9182. _clearBox.expandByScalar( 2 );
  9183. if ( _clearAlpha < 1 ) {
  9184. _context.clearRect(
  9185. _clearBox.min.x | 0,
  9186. _clearBox.min.y | 0,
  9187. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9188. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9189. );
  9190. }
  9191. if ( _clearAlpha > 0 ) {
  9192. setBlending( THREE.NormalBlending );
  9193. setOpacity( 1 );
  9194. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9195. _context.fillRect(
  9196. _clearBox.min.x | 0,
  9197. _clearBox.min.y | 0,
  9198. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9199. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9200. );
  9201. }
  9202. _clearBox.makeEmpty();
  9203. }
  9204. };
  9205. // compatibility
  9206. this.clearColor = function () {};
  9207. this.clearDepth = function () {};
  9208. this.clearStencil = function () {};
  9209. this.render = function ( scene, camera ) {
  9210. if ( camera instanceof THREE.Camera === false ) {
  9211. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9212. return;
  9213. }
  9214. if ( this.autoClear === true ) this.clear();
  9215. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9216. _this.info.render.vertices = 0;
  9217. _this.info.render.faces = 0;
  9218. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9219. _elements = _renderData.elements;
  9220. _lights = _renderData.lights;
  9221. _camera = camera;
  9222. /* DEBUG
  9223. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9224. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9225. */
  9226. calculateLights();
  9227. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  9228. var element = _elements[ e ];
  9229. var material = element.material;
  9230. if ( material === undefined || material.visible === false ) continue;
  9231. _elemBox.makeEmpty();
  9232. if ( element instanceof THREE.RenderableSprite ) {
  9233. _v1 = element;
  9234. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9235. renderSprite( _v1, element, material );
  9236. } else if ( element instanceof THREE.RenderableLine ) {
  9237. _v1 = element.v1; _v2 = element.v2;
  9238. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9239. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9240. _elemBox.setFromPoints( [
  9241. _v1.positionScreen,
  9242. _v2.positionScreen
  9243. ] );
  9244. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9245. renderLine( _v1, _v2, element, material );
  9246. }
  9247. } else if ( element instanceof THREE.RenderableFace3 ) {
  9248. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9249. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9250. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9251. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9252. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9253. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9254. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9255. if ( material.overdraw > 0 ) {
  9256. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9257. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9258. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9259. }
  9260. _elemBox.setFromPoints( [
  9261. _v1.positionScreen,
  9262. _v2.positionScreen,
  9263. _v3.positionScreen
  9264. ] );
  9265. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9266. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9267. }
  9268. }
  9269. /* DEBUG
  9270. setLineWidth( 1 );
  9271. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9272. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9273. */
  9274. _clearBox.union( _elemBox );
  9275. }
  9276. /* DEBUG
  9277. setLineWidth( 1 );
  9278. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9279. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9280. */
  9281. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9282. };
  9283. //
  9284. function calculateLights() {
  9285. _ambientLight.setRGB( 0, 0, 0 );
  9286. _directionalLights.setRGB( 0, 0, 0 );
  9287. _pointLights.setRGB( 0, 0, 0 );
  9288. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9289. var light = _lights[ l ];
  9290. var lightColor = light.color;
  9291. if ( light instanceof THREE.AmbientLight ) {
  9292. _ambientLight.add( lightColor );
  9293. } else if ( light instanceof THREE.DirectionalLight ) {
  9294. // for sprites
  9295. _directionalLights.add( lightColor );
  9296. } else if ( light instanceof THREE.PointLight ) {
  9297. // for sprites
  9298. _pointLights.add( lightColor );
  9299. }
  9300. }
  9301. }
  9302. function calculateLight( position, normal, color ) {
  9303. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9304. var light = _lights[ l ];
  9305. _lightColor.copy( light.color );
  9306. if ( light instanceof THREE.DirectionalLight ) {
  9307. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9308. var amount = normal.dot( lightPosition );
  9309. if ( amount <= 0 ) continue;
  9310. amount *= light.intensity;
  9311. color.add( _lightColor.multiplyScalar( amount ) );
  9312. } else if ( light instanceof THREE.PointLight ) {
  9313. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9314. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9315. if ( amount <= 0 ) continue;
  9316. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9317. if ( amount == 0 ) continue;
  9318. amount *= light.intensity;
  9319. color.add( _lightColor.multiplyScalar( amount ) );
  9320. }
  9321. }
  9322. }
  9323. function renderSprite( v1, element, material ) {
  9324. setOpacity( material.opacity );
  9325. setBlending( material.blending );
  9326. var scaleX = element.scale.x * _canvasWidthHalf;
  9327. var scaleY = element.scale.y * _canvasHeightHalf;
  9328. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9329. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9330. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9331. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9332. _elemBox.makeEmpty();
  9333. return;
  9334. }
  9335. if ( material instanceof THREE.SpriteMaterial ||
  9336. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  9337. if ( material.map !== null ) {
  9338. var bitmap = material.map.image;
  9339. _context.save();
  9340. _context.translate( v1.x, v1.y );
  9341. _context.rotate( material.rotation );
  9342. _context.scale( scaleX, - scaleY );
  9343. _context.drawImage( bitmap, 0, 0, bitmap.width, bitmap.height, - 0.5, - 0.5, 1, 1 );
  9344. _context.restore();
  9345. } else {
  9346. setFillStyle( material.color.getStyle() );
  9347. _context.save();
  9348. _context.translate( v1.x, v1.y );
  9349. _context.rotate( material.rotation );
  9350. _context.scale( scaleX, - scaleY );
  9351. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9352. _context.restore();
  9353. }
  9354. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9355. setStrokeStyle( material.color.getStyle() );
  9356. setFillStyle( material.color.getStyle() );
  9357. _context.save();
  9358. _context.translate( v1.x, v1.y );
  9359. _context.rotate( - element.rotation );
  9360. _context.scale( scaleX, scaleY );
  9361. material.program( _context );
  9362. _context.restore();
  9363. }
  9364. /* DEBUG
  9365. setStrokeStyle( 'rgb(255,255,0)' );
  9366. _context.beginPath();
  9367. _context.moveTo( v1.x - 10, v1.y );
  9368. _context.lineTo( v1.x + 10, v1.y );
  9369. _context.moveTo( v1.x, v1.y - 10 );
  9370. _context.lineTo( v1.x, v1.y + 10 );
  9371. _context.stroke();
  9372. */
  9373. }
  9374. function renderLine( v1, v2, element, material ) {
  9375. setOpacity( material.opacity );
  9376. setBlending( material.blending );
  9377. _context.beginPath();
  9378. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9379. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9380. if ( material instanceof THREE.LineBasicMaterial ) {
  9381. setLineWidth( material.linewidth );
  9382. setLineCap( material.linecap );
  9383. setLineJoin( material.linejoin );
  9384. if ( material.vertexColors !== THREE.VertexColors ) {
  9385. setStrokeStyle( material.color.getStyle() );
  9386. } else {
  9387. var colorStyle1 = element.vertexColors[0].getStyle();
  9388. var colorStyle2 = element.vertexColors[1].getStyle();
  9389. if ( colorStyle1 === colorStyle2 ) {
  9390. setStrokeStyle( colorStyle1 );
  9391. } else {
  9392. try {
  9393. var grad = _context.createLinearGradient(
  9394. v1.positionScreen.x,
  9395. v1.positionScreen.y,
  9396. v2.positionScreen.x,
  9397. v2.positionScreen.y
  9398. );
  9399. grad.addColorStop( 0, colorStyle1 );
  9400. grad.addColorStop( 1, colorStyle2 );
  9401. } catch ( exception ) {
  9402. grad = colorStyle1;
  9403. }
  9404. setStrokeStyle( grad );
  9405. }
  9406. }
  9407. _context.stroke();
  9408. _elemBox.expandByScalar( material.linewidth * 2 );
  9409. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9410. setLineWidth( material.linewidth );
  9411. setLineCap( material.linecap );
  9412. setLineJoin( material.linejoin );
  9413. setStrokeStyle( material.color.getStyle() );
  9414. setDashAndGap( material.dashSize, material.gapSize );
  9415. _context.stroke();
  9416. _elemBox.expandByScalar( material.linewidth * 2 );
  9417. setDashAndGap( null, null );
  9418. }
  9419. }
  9420. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9421. _this.info.render.vertices += 3;
  9422. _this.info.render.faces ++;
  9423. setOpacity( material.opacity );
  9424. setBlending( material.blending );
  9425. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9426. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9427. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9428. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9429. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9430. _diffuseColor.copy( material.color );
  9431. _emissiveColor.copy( material.emissive );
  9432. if ( material.vertexColors === THREE.FaceColors ) {
  9433. _diffuseColor.multiply( element.color );
  9434. }
  9435. if ( material.wireframe === false && material.shading === THREE.SmoothShading && element.vertexNormalsLength === 3 ) {
  9436. _color1.copy( _ambientLight );
  9437. _color2.copy( _ambientLight );
  9438. _color3.copy( _ambientLight );
  9439. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9440. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9441. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9442. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9443. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9444. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9445. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9446. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9447. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9448. } else {
  9449. _color.copy( _ambientLight );
  9450. calculateLight( element.centroidModel, element.normalModel, _color );
  9451. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9452. material.wireframe === true
  9453. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9454. : fillPath( _color );
  9455. }
  9456. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9457. if ( material.map !== null ) {
  9458. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9459. _uvs = element.uvs[ 0 ];
  9460. 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 );
  9461. }
  9462. } else if ( material.envMap !== null ) {
  9463. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9464. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9465. _uv1x = 0.5 * _vector3.x + 0.5;
  9466. _uv1y = 0.5 * _vector3.y + 0.5;
  9467. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9468. _uv2x = 0.5 * _vector3.x + 0.5;
  9469. _uv2y = 0.5 * _vector3.y + 0.5;
  9470. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9471. _uv3x = 0.5 * _vector3.x + 0.5;
  9472. _uv3y = 0.5 * _vector3.y + 0.5;
  9473. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9474. }/* else if ( material.envMap.mapping === THREE.SphericalRefractionMapping ) {
  9475. }*/
  9476. } else {
  9477. _color.copy( material.color );
  9478. if ( material.vertexColors === THREE.FaceColors ) {
  9479. _color.multiply( element.color );
  9480. }
  9481. material.wireframe === true
  9482. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9483. : fillPath( _color );
  9484. }
  9485. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9486. _near = _camera.near;
  9487. _far = _camera.far;
  9488. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9489. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9490. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9491. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9492. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9493. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9494. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9495. var normal;
  9496. if ( material.shading === THREE.FlatShading ) {
  9497. normal = element.normalModelView;
  9498. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9499. material.wireframe === true
  9500. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9501. : fillPath( _color );
  9502. } else if ( material.shading === THREE.SmoothShading ) {
  9503. normal = element.vertexNormalsModelView[ uv1 ];
  9504. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9505. normal = element.vertexNormalsModelView[ uv2 ];
  9506. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9507. normal = element.vertexNormalsModelView[ uv3 ];
  9508. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9509. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9510. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9511. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9512. }
  9513. }
  9514. }
  9515. //
  9516. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9517. _context.beginPath();
  9518. _context.moveTo( x0, y0 );
  9519. _context.lineTo( x1, y1 );
  9520. _context.lineTo( x2, y2 );
  9521. _context.closePath();
  9522. }
  9523. function strokePath( color, linewidth, linecap, linejoin ) {
  9524. setLineWidth( linewidth );
  9525. setLineCap( linecap );
  9526. setLineJoin( linejoin );
  9527. setStrokeStyle( color.getStyle() );
  9528. _context.stroke();
  9529. _elemBox.expandByScalar( linewidth * 2 );
  9530. }
  9531. function fillPath( color ) {
  9532. setFillStyle( color.getStyle() );
  9533. _context.fill();
  9534. }
  9535. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9536. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width === 0 ) return;
  9537. if ( texture.needsUpdate === true ) {
  9538. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  9539. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  9540. _patterns[ texture.id ] = _context.createPattern(
  9541. texture.image, repeatX === true && repeatY === true
  9542. ? 'repeat'
  9543. : repeatX === true && repeatY === false
  9544. ? 'repeat-x'
  9545. : repeatX === false && repeatY === true
  9546. ? 'repeat-y'
  9547. : 'no-repeat'
  9548. );
  9549. texture.needsUpdate = false;
  9550. }
  9551. _patterns[ texture.id ] === undefined
  9552. ? setFillStyle( 'rgba(0,0,0,1)' )
  9553. : setFillStyle( _patterns[ texture.id ] );
  9554. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9555. var a, b, c, d, e, f, det, idet,
  9556. offsetX = texture.offset.x / texture.repeat.x,
  9557. offsetY = texture.offset.y / texture.repeat.y,
  9558. width = texture.image.width * texture.repeat.x,
  9559. height = texture.image.height * texture.repeat.y;
  9560. u0 = ( u0 + offsetX ) * width;
  9561. v0 = ( 1.0 - v0 + offsetY ) * height;
  9562. u1 = ( u1 + offsetX ) * width;
  9563. v1 = ( 1.0 - v1 + offsetY ) * height;
  9564. u2 = ( u2 + offsetX ) * width;
  9565. v2 = ( 1.0 - v2 + offsetY ) * height;
  9566. x1 -= x0; y1 -= y0;
  9567. x2 -= x0; y2 -= y0;
  9568. u1 -= u0; v1 -= v0;
  9569. u2 -= u0; v2 -= v0;
  9570. det = u1 * v2 - u2 * v1;
  9571. if ( det === 0 ) {
  9572. if ( _imagedatas[ texture.id ] === undefined ) {
  9573. var canvas = document.createElement( 'canvas' )
  9574. canvas.width = texture.image.width;
  9575. canvas.height = texture.image.height;
  9576. var context = canvas.getContext( '2d' );
  9577. context.drawImage( texture.image, 0, 0 );
  9578. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9579. }
  9580. var data = _imagedatas[ texture.id ];
  9581. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9582. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9583. fillPath( _color );
  9584. return;
  9585. }
  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.fill();
  9596. _context.restore();
  9597. }
  9598. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9599. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9600. var a, b, c, d, e, f, det, idet,
  9601. width = image.width - 1,
  9602. height = image.height - 1;
  9603. u0 *= width; v0 *= height;
  9604. u1 *= width; v1 *= height;
  9605. u2 *= width; v2 *= height;
  9606. x1 -= x0; y1 -= y0;
  9607. x2 -= x0; y2 -= y0;
  9608. u1 -= u0; v1 -= v0;
  9609. u2 -= u0; v2 -= v0;
  9610. det = u1 * v2 - u2 * v1;
  9611. idet = 1 / det;
  9612. a = ( v2 * x1 - v1 * x2 ) * idet;
  9613. b = ( v2 * y1 - v1 * y2 ) * idet;
  9614. c = ( u1 * x2 - u2 * x1 ) * idet;
  9615. d = ( u1 * y2 - u2 * y1 ) * idet;
  9616. e = x0 - a * u0 - c * v0;
  9617. f = y0 - b * u0 - d * v0;
  9618. _context.save();
  9619. _context.transform( a, b, c, d, e, f );
  9620. _context.clip();
  9621. _context.drawImage( image, 0, 0 );
  9622. _context.restore();
  9623. }
  9624. function getGradientTexture( color1, color2, color3, color4 ) {
  9625. // http://mrdoob.com/blog/post/710
  9626. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9627. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9628. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9629. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9630. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9631. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9632. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9633. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9634. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9635. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9636. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9637. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9638. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9639. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9640. return _gradientMap;
  9641. }
  9642. // Hide anti-alias gaps
  9643. function expand( v1, v2, pixels ) {
  9644. var x = v2.x - v1.x, y = v2.y - v1.y,
  9645. det = x * x + y * y, idet;
  9646. if ( det === 0 ) return;
  9647. idet = pixels / Math.sqrt( det );
  9648. x *= idet; y *= idet;
  9649. v2.x += x; v2.y += y;
  9650. v1.x -= x; v1.y -= y;
  9651. }
  9652. // Context cached methods.
  9653. function setOpacity( value ) {
  9654. if ( _contextGlobalAlpha !== value ) {
  9655. _context.globalAlpha = value;
  9656. _contextGlobalAlpha = value;
  9657. }
  9658. }
  9659. function setBlending( value ) {
  9660. if ( _contextGlobalCompositeOperation !== value ) {
  9661. if ( value === THREE.NormalBlending ) {
  9662. _context.globalCompositeOperation = 'source-over';
  9663. } else if ( value === THREE.AdditiveBlending ) {
  9664. _context.globalCompositeOperation = 'lighter';
  9665. } else if ( value === THREE.SubtractiveBlending ) {
  9666. _context.globalCompositeOperation = 'darker';
  9667. }
  9668. _contextGlobalCompositeOperation = value;
  9669. }
  9670. }
  9671. function setLineWidth( value ) {
  9672. if ( _contextLineWidth !== value ) {
  9673. _context.lineWidth = value;
  9674. _contextLineWidth = value;
  9675. }
  9676. }
  9677. function setLineCap( value ) {
  9678. // "butt", "round", "square"
  9679. if ( _contextLineCap !== value ) {
  9680. _context.lineCap = value;
  9681. _contextLineCap = value;
  9682. }
  9683. }
  9684. function setLineJoin( value ) {
  9685. // "round", "bevel", "miter"
  9686. if ( _contextLineJoin !== value ) {
  9687. _context.lineJoin = value;
  9688. _contextLineJoin = value;
  9689. }
  9690. }
  9691. function setStrokeStyle( value ) {
  9692. if ( _contextStrokeStyle !== value ) {
  9693. _context.strokeStyle = value;
  9694. _contextStrokeStyle = value;
  9695. }
  9696. }
  9697. function setFillStyle( value ) {
  9698. if ( _contextFillStyle !== value ) {
  9699. _context.fillStyle = value;
  9700. _contextFillStyle = value;
  9701. }
  9702. }
  9703. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9704. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9705. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9706. _contextDashSize = dashSizeValue;
  9707. _contextGapSize = gapSizeValue;
  9708. }
  9709. }
  9710. };
  9711. /**
  9712. * Shader chunks for WebLG Shader library
  9713. *
  9714. * @author alteredq / http://alteredqualia.com/
  9715. * @author mrdoob / http://mrdoob.com/
  9716. * @author mikael emtinger / http://gomo.se/
  9717. */
  9718. THREE.ShaderChunk = {
  9719. // FOG
  9720. fog_pars_fragment: [
  9721. "#ifdef USE_FOG",
  9722. "uniform vec3 fogColor;",
  9723. "#ifdef FOG_EXP2",
  9724. "uniform float fogDensity;",
  9725. "#else",
  9726. "uniform float fogNear;",
  9727. "uniform float fogFar;",
  9728. "#endif",
  9729. "#endif"
  9730. ].join("\n"),
  9731. fog_fragment: [
  9732. "#ifdef USE_FOG",
  9733. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9734. "#ifdef FOG_EXP2",
  9735. "const float LOG2 = 1.442695;",
  9736. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9737. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9738. "#else",
  9739. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9740. "#endif",
  9741. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9742. "#endif"
  9743. ].join("\n"),
  9744. // ENVIRONMENT MAP
  9745. envmap_pars_fragment: [
  9746. "#ifdef USE_ENVMAP",
  9747. "uniform float reflectivity;",
  9748. "uniform samplerCube envMap;",
  9749. "uniform float flipEnvMap;",
  9750. "uniform int combine;",
  9751. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9752. "uniform bool useRefract;",
  9753. "uniform float refractionRatio;",
  9754. "#else",
  9755. "varying vec3 vReflect;",
  9756. "#endif",
  9757. "#endif"
  9758. ].join("\n"),
  9759. envmap_fragment: [
  9760. "#ifdef USE_ENVMAP",
  9761. "vec3 reflectVec;",
  9762. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9763. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9764. "if ( useRefract ) {",
  9765. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9766. "} else { ",
  9767. "reflectVec = reflect( cameraToVertex, normal );",
  9768. "}",
  9769. "#else",
  9770. "reflectVec = vReflect;",
  9771. "#endif",
  9772. "#ifdef DOUBLE_SIDED",
  9773. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9774. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9775. "#else",
  9776. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9777. "#endif",
  9778. "#ifdef GAMMA_INPUT",
  9779. "cubeColor.xyz *= cubeColor.xyz;",
  9780. "#endif",
  9781. "if ( combine == 1 ) {",
  9782. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9783. "} else if ( combine == 2 ) {",
  9784. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9785. "} else {",
  9786. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9787. "}",
  9788. "#endif"
  9789. ].join("\n"),
  9790. envmap_pars_vertex: [
  9791. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9792. "varying vec3 vReflect;",
  9793. "uniform float refractionRatio;",
  9794. "uniform bool useRefract;",
  9795. "#endif"
  9796. ].join("\n"),
  9797. worldpos_vertex : [
  9798. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9799. "#ifdef USE_SKINNING",
  9800. "vec4 worldPosition = modelMatrix * skinned;",
  9801. "#endif",
  9802. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9803. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9804. "#endif",
  9805. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9806. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9807. "#endif",
  9808. "#endif"
  9809. ].join("\n"),
  9810. envmap_vertex : [
  9811. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9812. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9813. "worldNormal = normalize( worldNormal );",
  9814. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9815. "if ( useRefract ) {",
  9816. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9817. "} else {",
  9818. "vReflect = reflect( cameraToVertex, worldNormal );",
  9819. "}",
  9820. "#endif"
  9821. ].join("\n"),
  9822. // COLOR MAP (particles)
  9823. map_particle_pars_fragment: [
  9824. "#ifdef USE_MAP",
  9825. "uniform sampler2D map;",
  9826. "#endif"
  9827. ].join("\n"),
  9828. map_particle_fragment: [
  9829. "#ifdef USE_MAP",
  9830. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9831. "#endif"
  9832. ].join("\n"),
  9833. // COLOR MAP (triangles)
  9834. map_pars_vertex: [
  9835. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9836. "varying vec2 vUv;",
  9837. "uniform vec4 offsetRepeat;",
  9838. "#endif"
  9839. ].join("\n"),
  9840. map_pars_fragment: [
  9841. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9842. "varying vec2 vUv;",
  9843. "#endif",
  9844. "#ifdef USE_MAP",
  9845. "uniform sampler2D map;",
  9846. "#endif"
  9847. ].join("\n"),
  9848. map_vertex: [
  9849. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9850. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9851. "#endif"
  9852. ].join("\n"),
  9853. map_fragment: [
  9854. "#ifdef USE_MAP",
  9855. "vec4 texelColor = texture2D( map, vUv );",
  9856. "#ifdef GAMMA_INPUT",
  9857. "texelColor.xyz *= texelColor.xyz;",
  9858. "#endif",
  9859. "gl_FragColor = gl_FragColor * texelColor;",
  9860. "#endif"
  9861. ].join("\n"),
  9862. // LIGHT MAP
  9863. lightmap_pars_fragment: [
  9864. "#ifdef USE_LIGHTMAP",
  9865. "varying vec2 vUv2;",
  9866. "uniform sampler2D lightMap;",
  9867. "#endif"
  9868. ].join("\n"),
  9869. lightmap_pars_vertex: [
  9870. "#ifdef USE_LIGHTMAP",
  9871. "varying vec2 vUv2;",
  9872. "#endif"
  9873. ].join("\n"),
  9874. lightmap_fragment: [
  9875. "#ifdef USE_LIGHTMAP",
  9876. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9877. "#endif"
  9878. ].join("\n"),
  9879. lightmap_vertex: [
  9880. "#ifdef USE_LIGHTMAP",
  9881. "vUv2 = uv2;",
  9882. "#endif"
  9883. ].join("\n"),
  9884. // BUMP MAP
  9885. bumpmap_pars_fragment: [
  9886. "#ifdef USE_BUMPMAP",
  9887. "uniform sampler2D bumpMap;",
  9888. "uniform float bumpScale;",
  9889. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9890. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9891. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9892. "vec2 dHdxy_fwd() {",
  9893. "vec2 dSTdx = dFdx( vUv );",
  9894. "vec2 dSTdy = dFdy( vUv );",
  9895. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9896. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9897. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9898. "return vec2( dBx, dBy );",
  9899. "}",
  9900. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9901. "vec3 vSigmaX = dFdx( surf_pos );",
  9902. "vec3 vSigmaY = dFdy( surf_pos );",
  9903. "vec3 vN = surf_norm;", // normalized
  9904. "vec3 R1 = cross( vSigmaY, vN );",
  9905. "vec3 R2 = cross( vN, vSigmaX );",
  9906. "float fDet = dot( vSigmaX, R1 );",
  9907. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9908. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9909. "}",
  9910. "#endif"
  9911. ].join("\n"),
  9912. // NORMAL MAP
  9913. normalmap_pars_fragment: [
  9914. "#ifdef USE_NORMALMAP",
  9915. "uniform sampler2D normalMap;",
  9916. "uniform vec2 normalScale;",
  9917. // Per-Pixel Tangent Space Normal Mapping
  9918. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9919. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9920. "vec3 q0 = dFdx( eye_pos.xyz );",
  9921. "vec3 q1 = dFdy( eye_pos.xyz );",
  9922. "vec2 st0 = dFdx( vUv.st );",
  9923. "vec2 st1 = dFdy( vUv.st );",
  9924. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9925. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9926. "vec3 N = normalize( surf_norm );",
  9927. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9928. "mapN.xy = normalScale * mapN.xy;",
  9929. "mat3 tsn = mat3( S, T, N );",
  9930. "return normalize( tsn * mapN );",
  9931. "}",
  9932. "#endif"
  9933. ].join("\n"),
  9934. // SPECULAR MAP
  9935. specularmap_pars_fragment: [
  9936. "#ifdef USE_SPECULARMAP",
  9937. "uniform sampler2D specularMap;",
  9938. "#endif"
  9939. ].join("\n"),
  9940. specularmap_fragment: [
  9941. "float specularStrength;",
  9942. "#ifdef USE_SPECULARMAP",
  9943. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9944. "specularStrength = texelSpecular.r;",
  9945. "#else",
  9946. "specularStrength = 1.0;",
  9947. "#endif"
  9948. ].join("\n"),
  9949. // LIGHTS LAMBERT
  9950. lights_lambert_pars_vertex: [
  9951. "uniform vec3 ambient;",
  9952. "uniform vec3 diffuse;",
  9953. "uniform vec3 emissive;",
  9954. "uniform vec3 ambientLightColor;",
  9955. "#if MAX_DIR_LIGHTS > 0",
  9956. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9957. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9958. "#endif",
  9959. "#if MAX_HEMI_LIGHTS > 0",
  9960. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9961. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9962. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9963. "#endif",
  9964. "#if MAX_POINT_LIGHTS > 0",
  9965. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9966. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9967. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9968. "#endif",
  9969. "#if MAX_SPOT_LIGHTS > 0",
  9970. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9971. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9972. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9973. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9974. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9975. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9976. "#endif",
  9977. "#ifdef WRAP_AROUND",
  9978. "uniform vec3 wrapRGB;",
  9979. "#endif"
  9980. ].join("\n"),
  9981. lights_lambert_vertex: [
  9982. "vLightFront = vec3( 0.0 );",
  9983. "#ifdef DOUBLE_SIDED",
  9984. "vLightBack = vec3( 0.0 );",
  9985. "#endif",
  9986. "transformedNormal = normalize( transformedNormal );",
  9987. "#if MAX_DIR_LIGHTS > 0",
  9988. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9989. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9990. "vec3 dirVector = normalize( lDirection.xyz );",
  9991. "float dotProduct = dot( transformedNormal, dirVector );",
  9992. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9993. "#ifdef DOUBLE_SIDED",
  9994. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9995. "#ifdef WRAP_AROUND",
  9996. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9997. "#endif",
  9998. "#endif",
  9999. "#ifdef WRAP_AROUND",
  10000. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10001. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10002. "#ifdef DOUBLE_SIDED",
  10003. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10004. "#endif",
  10005. "#endif",
  10006. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10007. "#ifdef DOUBLE_SIDED",
  10008. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10009. "#endif",
  10010. "}",
  10011. "#endif",
  10012. "#if MAX_POINT_LIGHTS > 0",
  10013. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10014. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10015. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10016. "float lDistance = 1.0;",
  10017. "if ( pointLightDistance[ i ] > 0.0 )",
  10018. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10019. "lVector = normalize( lVector );",
  10020. "float dotProduct = dot( transformedNormal, lVector );",
  10021. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10022. "#ifdef DOUBLE_SIDED",
  10023. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10024. "#ifdef WRAP_AROUND",
  10025. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10026. "#endif",
  10027. "#endif",
  10028. "#ifdef WRAP_AROUND",
  10029. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10030. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10031. "#ifdef DOUBLE_SIDED",
  10032. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10033. "#endif",
  10034. "#endif",
  10035. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10036. "#ifdef DOUBLE_SIDED",
  10037. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10038. "#endif",
  10039. "}",
  10040. "#endif",
  10041. "#if MAX_SPOT_LIGHTS > 0",
  10042. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10043. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10044. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10045. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10046. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10047. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10048. "float lDistance = 1.0;",
  10049. "if ( spotLightDistance[ i ] > 0.0 )",
  10050. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10051. "lVector = normalize( lVector );",
  10052. "float dotProduct = dot( transformedNormal, lVector );",
  10053. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10054. "#ifdef DOUBLE_SIDED",
  10055. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10056. "#ifdef WRAP_AROUND",
  10057. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10058. "#endif",
  10059. "#endif",
  10060. "#ifdef WRAP_AROUND",
  10061. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10062. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10063. "#ifdef DOUBLE_SIDED",
  10064. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10065. "#endif",
  10066. "#endif",
  10067. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10068. "#ifdef DOUBLE_SIDED",
  10069. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10070. "#endif",
  10071. "}",
  10072. "}",
  10073. "#endif",
  10074. "#if MAX_HEMI_LIGHTS > 0",
  10075. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10076. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10077. "vec3 lVector = normalize( lDirection.xyz );",
  10078. "float dotProduct = dot( transformedNormal, lVector );",
  10079. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10080. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10081. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10082. "#ifdef DOUBLE_SIDED",
  10083. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10084. "#endif",
  10085. "}",
  10086. "#endif",
  10087. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10088. "#ifdef DOUBLE_SIDED",
  10089. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10090. "#endif"
  10091. ].join("\n"),
  10092. // LIGHTS PHONG
  10093. lights_phong_pars_vertex: [
  10094. "#ifndef PHONG_PER_PIXEL",
  10095. "#if MAX_POINT_LIGHTS > 0",
  10096. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10097. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10098. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10099. "#endif",
  10100. "#if MAX_SPOT_LIGHTS > 0",
  10101. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10102. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10103. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10104. "#endif",
  10105. "#endif",
  10106. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10107. "varying vec3 vWorldPosition;",
  10108. "#endif"
  10109. ].join("\n"),
  10110. lights_phong_vertex: [
  10111. "#ifndef PHONG_PER_PIXEL",
  10112. "#if MAX_POINT_LIGHTS > 0",
  10113. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10114. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10115. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10116. "float lDistance = 1.0;",
  10117. "if ( pointLightDistance[ i ] > 0.0 )",
  10118. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10119. "vPointLight[ i ] = vec4( lVector, lDistance );",
  10120. "}",
  10121. "#endif",
  10122. "#if MAX_SPOT_LIGHTS > 0",
  10123. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10124. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10125. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10126. "float lDistance = 1.0;",
  10127. "if ( spotLightDistance[ i ] > 0.0 )",
  10128. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10129. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  10130. "}",
  10131. "#endif",
  10132. "#endif",
  10133. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10134. "vWorldPosition = worldPosition.xyz;",
  10135. "#endif"
  10136. ].join("\n"),
  10137. lights_phong_pars_fragment: [
  10138. "uniform vec3 ambientLightColor;",
  10139. "#if MAX_DIR_LIGHTS > 0",
  10140. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10141. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10142. "#endif",
  10143. "#if MAX_HEMI_LIGHTS > 0",
  10144. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10145. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10146. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10147. "#endif",
  10148. "#if MAX_POINT_LIGHTS > 0",
  10149. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10150. "#ifdef PHONG_PER_PIXEL",
  10151. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10152. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10153. "#else",
  10154. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10155. "#endif",
  10156. "#endif",
  10157. "#if MAX_SPOT_LIGHTS > 0",
  10158. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10159. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10160. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10161. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10162. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10163. "#ifdef PHONG_PER_PIXEL",
  10164. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10165. "#else",
  10166. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10167. "#endif",
  10168. "#endif",
  10169. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10170. "varying vec3 vWorldPosition;",
  10171. "#endif",
  10172. "#ifdef WRAP_AROUND",
  10173. "uniform vec3 wrapRGB;",
  10174. "#endif",
  10175. "varying vec3 vViewPosition;",
  10176. "varying vec3 vNormal;"
  10177. ].join("\n"),
  10178. lights_phong_fragment: [
  10179. "vec3 normal = normalize( vNormal );",
  10180. "vec3 viewPosition = normalize( vViewPosition );",
  10181. "#ifdef DOUBLE_SIDED",
  10182. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10183. "#endif",
  10184. "#ifdef USE_NORMALMAP",
  10185. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10186. "#elif defined( USE_BUMPMAP )",
  10187. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10188. "#endif",
  10189. "#if MAX_POINT_LIGHTS > 0",
  10190. "vec3 pointDiffuse = vec3( 0.0 );",
  10191. "vec3 pointSpecular = vec3( 0.0 );",
  10192. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10193. "#ifdef PHONG_PER_PIXEL",
  10194. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10195. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10196. "float lDistance = 1.0;",
  10197. "if ( pointLightDistance[ i ] > 0.0 )",
  10198. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10199. "lVector = normalize( lVector );",
  10200. "#else",
  10201. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10202. "float lDistance = vPointLight[ i ].w;",
  10203. "#endif",
  10204. // diffuse
  10205. "float dotProduct = dot( normal, lVector );",
  10206. "#ifdef WRAP_AROUND",
  10207. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10208. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10209. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10210. "#else",
  10211. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10212. "#endif",
  10213. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10214. // specular
  10215. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10216. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10217. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10218. "#ifdef PHYSICALLY_BASED_SHADING",
  10219. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10220. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10221. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10222. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10223. "#else",
  10224. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  10225. "#endif",
  10226. "}",
  10227. "#endif",
  10228. "#if MAX_SPOT_LIGHTS > 0",
  10229. "vec3 spotDiffuse = vec3( 0.0 );",
  10230. "vec3 spotSpecular = vec3( 0.0 );",
  10231. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10232. "#ifdef PHONG_PER_PIXEL",
  10233. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10234. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10235. "float lDistance = 1.0;",
  10236. "if ( spotLightDistance[ i ] > 0.0 )",
  10237. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10238. "lVector = normalize( lVector );",
  10239. "#else",
  10240. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10241. "float lDistance = vSpotLight[ i ].w;",
  10242. "#endif",
  10243. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10244. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10245. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10246. // diffuse
  10247. "float dotProduct = dot( normal, lVector );",
  10248. "#ifdef WRAP_AROUND",
  10249. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10250. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10251. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10252. "#else",
  10253. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10254. "#endif",
  10255. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10256. // specular
  10257. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10258. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10259. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10260. "#ifdef PHYSICALLY_BASED_SHADING",
  10261. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10262. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10263. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10264. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10265. "#else",
  10266. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10267. "#endif",
  10268. "}",
  10269. "}",
  10270. "#endif",
  10271. "#if MAX_DIR_LIGHTS > 0",
  10272. "vec3 dirDiffuse = vec3( 0.0 );",
  10273. "vec3 dirSpecular = vec3( 0.0 );" ,
  10274. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10275. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10276. "vec3 dirVector = normalize( lDirection.xyz );",
  10277. // diffuse
  10278. "float dotProduct = dot( normal, dirVector );",
  10279. "#ifdef WRAP_AROUND",
  10280. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10281. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10282. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10283. "#else",
  10284. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10285. "#endif",
  10286. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10287. // specular
  10288. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10289. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10290. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10291. "#ifdef PHYSICALLY_BASED_SHADING",
  10292. /*
  10293. // fresnel term from skin shader
  10294. "const float F0 = 0.128;",
  10295. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10296. "float exponential = pow( base, 5.0 );",
  10297. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10298. */
  10299. /*
  10300. // fresnel term from fresnel shader
  10301. "const float mFresnelBias = 0.08;",
  10302. "const float mFresnelScale = 0.3;",
  10303. "const float mFresnelPower = 5.0;",
  10304. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10305. */
  10306. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10307. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10308. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10309. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10310. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10311. "#else",
  10312. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10313. "#endif",
  10314. "}",
  10315. "#endif",
  10316. "#if MAX_HEMI_LIGHTS > 0",
  10317. "vec3 hemiDiffuse = vec3( 0.0 );",
  10318. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10319. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10320. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10321. "vec3 lVector = normalize( lDirection.xyz );",
  10322. // diffuse
  10323. "float dotProduct = dot( normal, lVector );",
  10324. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10325. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10326. "hemiDiffuse += diffuse * hemiColor;",
  10327. // specular (sky light)
  10328. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10329. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10330. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10331. // specular (ground light)
  10332. "vec3 lVectorGround = -lVector;",
  10333. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10334. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10335. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10336. "#ifdef PHYSICALLY_BASED_SHADING",
  10337. "float dotProductGround = dot( normal, lVectorGround );",
  10338. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10339. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10340. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10341. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10342. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10343. "#else",
  10344. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10345. "#endif",
  10346. "}",
  10347. "#endif",
  10348. "vec3 totalDiffuse = vec3( 0.0 );",
  10349. "vec3 totalSpecular = vec3( 0.0 );",
  10350. "#if MAX_DIR_LIGHTS > 0",
  10351. "totalDiffuse += dirDiffuse;",
  10352. "totalSpecular += dirSpecular;",
  10353. "#endif",
  10354. "#if MAX_HEMI_LIGHTS > 0",
  10355. "totalDiffuse += hemiDiffuse;",
  10356. "totalSpecular += hemiSpecular;",
  10357. "#endif",
  10358. "#if MAX_POINT_LIGHTS > 0",
  10359. "totalDiffuse += pointDiffuse;",
  10360. "totalSpecular += pointSpecular;",
  10361. "#endif",
  10362. "#if MAX_SPOT_LIGHTS > 0",
  10363. "totalDiffuse += spotDiffuse;",
  10364. "totalSpecular += spotSpecular;",
  10365. "#endif",
  10366. "#ifdef METAL",
  10367. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10368. "#else",
  10369. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10370. "#endif"
  10371. ].join("\n"),
  10372. // VERTEX COLORS
  10373. color_pars_fragment: [
  10374. "#ifdef USE_COLOR",
  10375. "varying vec3 vColor;",
  10376. "#endif"
  10377. ].join("\n"),
  10378. color_fragment: [
  10379. "#ifdef USE_COLOR",
  10380. "gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10381. "#endif"
  10382. ].join("\n"),
  10383. color_pars_vertex: [
  10384. "#ifdef USE_COLOR",
  10385. "varying vec3 vColor;",
  10386. "#endif"
  10387. ].join("\n"),
  10388. color_vertex: [
  10389. "#ifdef USE_COLOR",
  10390. "#ifdef GAMMA_INPUT",
  10391. "vColor = color * color;",
  10392. "#else",
  10393. "vColor = color;",
  10394. "#endif",
  10395. "#endif"
  10396. ].join("\n"),
  10397. // SKINNING
  10398. skinning_pars_vertex: [
  10399. "#ifdef USE_SKINNING",
  10400. "#ifdef BONE_TEXTURE",
  10401. "uniform sampler2D boneTexture;",
  10402. "uniform int boneTextureWidth;",
  10403. "uniform int boneTextureHeight;",
  10404. "mat4 getBoneMatrix( const in float i ) {",
  10405. "float j = i * 4.0;",
  10406. "float x = mod( j, float( boneTextureWidth ) );",
  10407. "float y = floor( j / float( boneTextureWidth ) );",
  10408. "float dx = 1.0 / float( boneTextureWidth );",
  10409. "float dy = 1.0 / float( boneTextureHeight );",
  10410. "y = dy * ( y + 0.5 );",
  10411. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10412. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10413. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10414. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10415. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10416. "return bone;",
  10417. "}",
  10418. "#else",
  10419. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10420. "mat4 getBoneMatrix( const in float i ) {",
  10421. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10422. "return bone;",
  10423. "}",
  10424. "#endif",
  10425. "#endif"
  10426. ].join("\n"),
  10427. skinbase_vertex: [
  10428. "#ifdef USE_SKINNING",
  10429. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10430. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10431. "#endif"
  10432. ].join("\n"),
  10433. skinning_vertex: [
  10434. "#ifdef USE_SKINNING",
  10435. "#ifdef USE_MORPHTARGETS",
  10436. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10437. "#else",
  10438. "vec4 skinVertex = vec4( position, 1.0 );",
  10439. "#endif",
  10440. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10441. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10442. "#endif"
  10443. ].join("\n"),
  10444. // MORPHING
  10445. morphtarget_pars_vertex: [
  10446. "#ifdef USE_MORPHTARGETS",
  10447. "#ifndef USE_MORPHNORMALS",
  10448. "uniform float morphTargetInfluences[ 8 ];",
  10449. "#else",
  10450. "uniform float morphTargetInfluences[ 4 ];",
  10451. "#endif",
  10452. "#endif"
  10453. ].join("\n"),
  10454. morphtarget_vertex: [
  10455. "#ifdef USE_MORPHTARGETS",
  10456. "vec3 morphed = vec3( 0.0 );",
  10457. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10458. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10459. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10460. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10461. "#ifndef USE_MORPHNORMALS",
  10462. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10463. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10464. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10465. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10466. "#endif",
  10467. "morphed += position;",
  10468. "#endif"
  10469. ].join("\n"),
  10470. default_vertex : [
  10471. "vec4 mvPosition;",
  10472. "#ifdef USE_SKINNING",
  10473. "mvPosition = modelViewMatrix * skinned;",
  10474. "#endif",
  10475. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10476. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10477. "#endif",
  10478. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10479. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10480. "#endif",
  10481. "gl_Position = projectionMatrix * mvPosition;"
  10482. ].join("\n"),
  10483. morphnormal_vertex: [
  10484. "#ifdef USE_MORPHNORMALS",
  10485. "vec3 morphedNormal = vec3( 0.0 );",
  10486. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10487. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10488. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10489. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10490. "morphedNormal += normal;",
  10491. "#endif"
  10492. ].join("\n"),
  10493. skinnormal_vertex: [
  10494. "#ifdef USE_SKINNING",
  10495. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10496. "skinMatrix += skinWeight.y * boneMatY;",
  10497. "#ifdef USE_MORPHNORMALS",
  10498. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10499. "#else",
  10500. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10501. "#endif",
  10502. "#endif"
  10503. ].join("\n"),
  10504. defaultnormal_vertex: [
  10505. "vec3 objectNormal;",
  10506. "#ifdef USE_SKINNING",
  10507. "objectNormal = skinnedNormal.xyz;",
  10508. "#endif",
  10509. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10510. "objectNormal = morphedNormal;",
  10511. "#endif",
  10512. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10513. "objectNormal = normal;",
  10514. "#endif",
  10515. "#ifdef FLIP_SIDED",
  10516. "objectNormal = -objectNormal;",
  10517. "#endif",
  10518. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10519. ].join("\n"),
  10520. // SHADOW MAP
  10521. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10522. // http://spidergl.org/example.php?id=6
  10523. // http://fabiensanglard.net/shadowmapping
  10524. shadowmap_pars_fragment: [
  10525. "#ifdef USE_SHADOWMAP",
  10526. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10527. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10528. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10529. "uniform float shadowBias[ MAX_SHADOWS ];",
  10530. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10531. "float unpackDepth( const in vec4 rgba_depth ) {",
  10532. "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 );",
  10533. "float depth = dot( rgba_depth, bit_shift );",
  10534. "return depth;",
  10535. "}",
  10536. "#endif"
  10537. ].join("\n"),
  10538. shadowmap_fragment: [
  10539. "#ifdef USE_SHADOWMAP",
  10540. "#ifdef SHADOWMAP_DEBUG",
  10541. "vec3 frustumColors[3];",
  10542. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10543. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10544. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10545. "#endif",
  10546. "#ifdef SHADOWMAP_CASCADE",
  10547. "int inFrustumCount = 0;",
  10548. "#endif",
  10549. "float fDepth;",
  10550. "vec3 shadowColor = vec3( 1.0 );",
  10551. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10552. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10553. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10554. // "if ( all( something, something ) )" using this instead
  10555. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10556. "bool inFrustum = all( inFrustumVec );",
  10557. // don't shadow pixels outside of light frustum
  10558. // use just first frustum (for cascades)
  10559. // don't shadow pixels behind far plane of light frustum
  10560. "#ifdef SHADOWMAP_CASCADE",
  10561. "inFrustumCount += int( inFrustum );",
  10562. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10563. "#else",
  10564. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10565. "#endif",
  10566. "bool frustumTest = all( frustumTestVec );",
  10567. "if ( frustumTest ) {",
  10568. "shadowCoord.z += shadowBias[ i ];",
  10569. "#if defined( SHADOWMAP_TYPE_PCF )",
  10570. // Percentage-close filtering
  10571. // (9 pixel kernel)
  10572. // http://fabiensanglard.net/shadowmappingPCF/
  10573. "float shadow = 0.0;",
  10574. /*
  10575. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10576. // must enroll loop manually
  10577. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10578. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10579. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10580. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10581. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10582. "float fDepth = unpackDepth( rgbaDepth );",
  10583. "if ( fDepth < shadowCoord.z )",
  10584. "shadow += 1.0;",
  10585. "}",
  10586. "shadow /= 9.0;",
  10587. */
  10588. "const float shadowDelta = 1.0 / 9.0;",
  10589. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10590. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10591. "float dx0 = -1.25 * xPixelOffset;",
  10592. "float dy0 = -1.25 * yPixelOffset;",
  10593. "float dx1 = 1.25 * xPixelOffset;",
  10594. "float dy1 = 1.25 * yPixelOffset;",
  10595. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10596. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10597. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10598. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10599. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10600. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10601. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10602. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10603. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10604. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10605. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10606. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10607. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10608. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10609. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10610. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10611. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10612. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10613. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10614. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10615. // Percentage-close filtering
  10616. // (9 pixel kernel)
  10617. // http://fabiensanglard.net/shadowmappingPCF/
  10618. "float shadow = 0.0;",
  10619. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10620. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10621. "float dx0 = -1.0 * xPixelOffset;",
  10622. "float dy0 = -1.0 * yPixelOffset;",
  10623. "float dx1 = 1.0 * xPixelOffset;",
  10624. "float dy1 = 1.0 * yPixelOffset;",
  10625. "mat3 shadowKernel;",
  10626. "mat3 depthKernel;",
  10627. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10628. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10629. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10630. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10631. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10632. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10633. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10634. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10635. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10636. "vec3 shadowZ = vec3( shadowCoord.z );",
  10637. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10638. "shadowKernel[0] *= vec3(0.25);",
  10639. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10640. "shadowKernel[1] *= vec3(0.25);",
  10641. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10642. "shadowKernel[2] *= vec3(0.25);",
  10643. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10644. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10645. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10646. "vec4 shadowValues;",
  10647. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10648. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10649. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10650. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10651. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10652. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10653. "#else",
  10654. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10655. "float fDepth = unpackDepth( rgbaDepth );",
  10656. "if ( fDepth < shadowCoord.z )",
  10657. // spot with multiple shadows is darker
  10658. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10659. // spot with multiple shadows has the same color as single shadow spot
  10660. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10661. "#endif",
  10662. "}",
  10663. "#ifdef SHADOWMAP_DEBUG",
  10664. "#ifdef SHADOWMAP_CASCADE",
  10665. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10666. "#else",
  10667. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10668. "#endif",
  10669. "#endif",
  10670. "}",
  10671. "#ifdef GAMMA_OUTPUT",
  10672. "shadowColor *= shadowColor;",
  10673. "#endif",
  10674. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10675. "#endif"
  10676. ].join("\n"),
  10677. shadowmap_pars_vertex: [
  10678. "#ifdef USE_SHADOWMAP",
  10679. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10680. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10681. "#endif"
  10682. ].join("\n"),
  10683. shadowmap_vertex: [
  10684. "#ifdef USE_SHADOWMAP",
  10685. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10686. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10687. "}",
  10688. "#endif"
  10689. ].join("\n"),
  10690. // ALPHATEST
  10691. alphatest_fragment: [
  10692. "#ifdef ALPHATEST",
  10693. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10694. "#endif"
  10695. ].join("\n"),
  10696. // LINEAR SPACE
  10697. linear_to_gamma_fragment: [
  10698. "#ifdef GAMMA_OUTPUT",
  10699. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10700. "#endif"
  10701. ].join("\n")
  10702. };
  10703. /**
  10704. * Uniform Utilities
  10705. */
  10706. THREE.UniformsUtils = {
  10707. merge: function ( uniforms ) {
  10708. var u, p, tmp, merged = {};
  10709. for ( u = 0; u < uniforms.length; u ++ ) {
  10710. tmp = this.clone( uniforms[ u ] );
  10711. for ( p in tmp ) {
  10712. merged[ p ] = tmp[ p ];
  10713. }
  10714. }
  10715. return merged;
  10716. },
  10717. clone: function ( uniforms_src ) {
  10718. var u, p, parameter, parameter_src, uniforms_dst = {};
  10719. for ( u in uniforms_src ) {
  10720. uniforms_dst[ u ] = {};
  10721. for ( p in uniforms_src[ u ] ) {
  10722. parameter_src = uniforms_src[ u ][ p ];
  10723. if ( parameter_src instanceof THREE.Color ||
  10724. parameter_src instanceof THREE.Vector2 ||
  10725. parameter_src instanceof THREE.Vector3 ||
  10726. parameter_src instanceof THREE.Vector4 ||
  10727. parameter_src instanceof THREE.Matrix4 ||
  10728. parameter_src instanceof THREE.Texture ) {
  10729. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10730. } else if ( parameter_src instanceof Array ) {
  10731. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10732. } else {
  10733. uniforms_dst[ u ][ p ] = parameter_src;
  10734. }
  10735. }
  10736. }
  10737. return uniforms_dst;
  10738. }
  10739. };
  10740. /**
  10741. * Uniforms library for shared webgl shaders
  10742. */
  10743. THREE.UniformsLib = {
  10744. common: {
  10745. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10746. "opacity" : { type: "f", value: 1.0 },
  10747. "map" : { type: "t", value: null },
  10748. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10749. "lightMap" : { type: "t", value: null },
  10750. "specularMap" : { type: "t", value: null },
  10751. "envMap" : { type: "t", value: null },
  10752. "flipEnvMap" : { type: "f", value: -1 },
  10753. "useRefract" : { type: "i", value: 0 },
  10754. "reflectivity" : { type: "f", value: 1.0 },
  10755. "refractionRatio" : { type: "f", value: 0.98 },
  10756. "combine" : { type: "i", value: 0 },
  10757. "morphTargetInfluences" : { type: "f", value: 0 }
  10758. },
  10759. bump: {
  10760. "bumpMap" : { type: "t", value: null },
  10761. "bumpScale" : { type: "f", value: 1 }
  10762. },
  10763. normalmap: {
  10764. "normalMap" : { type: "t", value: null },
  10765. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10766. },
  10767. fog : {
  10768. "fogDensity" : { type: "f", value: 0.00025 },
  10769. "fogNear" : { type: "f", value: 1 },
  10770. "fogFar" : { type: "f", value: 2000 },
  10771. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10772. },
  10773. lights: {
  10774. "ambientLightColor" : { type: "fv", value: [] },
  10775. "directionalLightDirection" : { type: "fv", value: [] },
  10776. "directionalLightColor" : { type: "fv", value: [] },
  10777. "hemisphereLightDirection" : { type: "fv", value: [] },
  10778. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10779. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10780. "pointLightColor" : { type: "fv", value: [] },
  10781. "pointLightPosition" : { type: "fv", value: [] },
  10782. "pointLightDistance" : { type: "fv1", value: [] },
  10783. "spotLightColor" : { type: "fv", value: [] },
  10784. "spotLightPosition" : { type: "fv", value: [] },
  10785. "spotLightDirection" : { type: "fv", value: [] },
  10786. "spotLightDistance" : { type: "fv1", value: [] },
  10787. "spotLightAngleCos" : { type: "fv1", value: [] },
  10788. "spotLightExponent" : { type: "fv1", value: [] }
  10789. },
  10790. particle: {
  10791. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10792. "opacity" : { type: "f", value: 1.0 },
  10793. "size" : { type: "f", value: 1.0 },
  10794. "scale" : { type: "f", value: 1.0 },
  10795. "map" : { type: "t", value: null },
  10796. "fogDensity" : { type: "f", value: 0.00025 },
  10797. "fogNear" : { type: "f", value: 1 },
  10798. "fogFar" : { type: "f", value: 2000 },
  10799. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10800. },
  10801. shadowmap: {
  10802. "shadowMap": { type: "tv", value: [] },
  10803. "shadowMapSize": { type: "v2v", value: [] },
  10804. "shadowBias" : { type: "fv1", value: [] },
  10805. "shadowDarkness": { type: "fv1", value: [] },
  10806. "shadowMatrix" : { type: "m4v", value: [] }
  10807. }
  10808. };
  10809. /**
  10810. * Webgl Shader Library for three.js
  10811. *
  10812. * @author alteredq / http://alteredqualia.com/
  10813. * @author mrdoob / http://mrdoob.com/
  10814. * @author mikael emtinger / http://gomo.se/
  10815. */
  10816. THREE.ShaderLib = {
  10817. 'basic': {
  10818. uniforms: THREE.UniformsUtils.merge( [
  10819. THREE.UniformsLib[ "common" ],
  10820. THREE.UniformsLib[ "fog" ],
  10821. THREE.UniformsLib[ "shadowmap" ]
  10822. ] ),
  10823. vertexShader: [
  10824. THREE.ShaderChunk[ "map_pars_vertex" ],
  10825. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10826. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10827. THREE.ShaderChunk[ "color_pars_vertex" ],
  10828. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10829. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10830. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10831. "void main() {",
  10832. THREE.ShaderChunk[ "map_vertex" ],
  10833. THREE.ShaderChunk[ "lightmap_vertex" ],
  10834. THREE.ShaderChunk[ "color_vertex" ],
  10835. THREE.ShaderChunk[ "skinbase_vertex" ],
  10836. "#ifdef USE_ENVMAP",
  10837. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10838. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10839. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10840. "#endif",
  10841. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10842. THREE.ShaderChunk[ "skinning_vertex" ],
  10843. THREE.ShaderChunk[ "default_vertex" ],
  10844. THREE.ShaderChunk[ "worldpos_vertex" ],
  10845. THREE.ShaderChunk[ "envmap_vertex" ],
  10846. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10847. "}"
  10848. ].join("\n"),
  10849. fragmentShader: [
  10850. "uniform vec3 diffuse;",
  10851. "uniform float opacity;",
  10852. THREE.ShaderChunk[ "color_pars_fragment" ],
  10853. THREE.ShaderChunk[ "map_pars_fragment" ],
  10854. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10855. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10856. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10857. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10858. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10859. "void main() {",
  10860. "gl_FragColor = vec4( diffuse, opacity );",
  10861. THREE.ShaderChunk[ "map_fragment" ],
  10862. THREE.ShaderChunk[ "alphatest_fragment" ],
  10863. THREE.ShaderChunk[ "specularmap_fragment" ],
  10864. THREE.ShaderChunk[ "lightmap_fragment" ],
  10865. THREE.ShaderChunk[ "color_fragment" ],
  10866. THREE.ShaderChunk[ "envmap_fragment" ],
  10867. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10868. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10869. THREE.ShaderChunk[ "fog_fragment" ],
  10870. "}"
  10871. ].join("\n")
  10872. },
  10873. 'lambert': {
  10874. uniforms: THREE.UniformsUtils.merge( [
  10875. THREE.UniformsLib[ "common" ],
  10876. THREE.UniformsLib[ "fog" ],
  10877. THREE.UniformsLib[ "lights" ],
  10878. THREE.UniformsLib[ "shadowmap" ],
  10879. {
  10880. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10881. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10882. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10883. }
  10884. ] ),
  10885. vertexShader: [
  10886. "#define LAMBERT",
  10887. "varying vec3 vLightFront;",
  10888. "#ifdef DOUBLE_SIDED",
  10889. "varying vec3 vLightBack;",
  10890. "#endif",
  10891. THREE.ShaderChunk[ "map_pars_vertex" ],
  10892. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10893. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10894. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10895. THREE.ShaderChunk[ "color_pars_vertex" ],
  10896. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10897. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10898. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10899. "void main() {",
  10900. THREE.ShaderChunk[ "map_vertex" ],
  10901. THREE.ShaderChunk[ "lightmap_vertex" ],
  10902. THREE.ShaderChunk[ "color_vertex" ],
  10903. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10904. THREE.ShaderChunk[ "skinbase_vertex" ],
  10905. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10906. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10907. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10908. THREE.ShaderChunk[ "skinning_vertex" ],
  10909. THREE.ShaderChunk[ "default_vertex" ],
  10910. THREE.ShaderChunk[ "worldpos_vertex" ],
  10911. THREE.ShaderChunk[ "envmap_vertex" ],
  10912. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10913. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10914. "}"
  10915. ].join("\n"),
  10916. fragmentShader: [
  10917. "uniform float opacity;",
  10918. "varying vec3 vLightFront;",
  10919. "#ifdef DOUBLE_SIDED",
  10920. "varying vec3 vLightBack;",
  10921. "#endif",
  10922. THREE.ShaderChunk[ "color_pars_fragment" ],
  10923. THREE.ShaderChunk[ "map_pars_fragment" ],
  10924. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10925. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10926. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10927. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10928. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10929. "void main() {",
  10930. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10931. THREE.ShaderChunk[ "map_fragment" ],
  10932. THREE.ShaderChunk[ "alphatest_fragment" ],
  10933. THREE.ShaderChunk[ "specularmap_fragment" ],
  10934. "#ifdef DOUBLE_SIDED",
  10935. //"float isFront = float( gl_FrontFacing );",
  10936. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10937. "if ( gl_FrontFacing )",
  10938. "gl_FragColor.xyz *= vLightFront;",
  10939. "else",
  10940. "gl_FragColor.xyz *= vLightBack;",
  10941. "#else",
  10942. "gl_FragColor.xyz *= vLightFront;",
  10943. "#endif",
  10944. THREE.ShaderChunk[ "lightmap_fragment" ],
  10945. THREE.ShaderChunk[ "color_fragment" ],
  10946. THREE.ShaderChunk[ "envmap_fragment" ],
  10947. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10948. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10949. THREE.ShaderChunk[ "fog_fragment" ],
  10950. "}"
  10951. ].join("\n")
  10952. },
  10953. 'phong': {
  10954. uniforms: THREE.UniformsUtils.merge( [
  10955. THREE.UniformsLib[ "common" ],
  10956. THREE.UniformsLib[ "bump" ],
  10957. THREE.UniformsLib[ "normalmap" ],
  10958. THREE.UniformsLib[ "fog" ],
  10959. THREE.UniformsLib[ "lights" ],
  10960. THREE.UniformsLib[ "shadowmap" ],
  10961. {
  10962. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10963. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10964. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10965. "shininess": { type: "f", value: 30 },
  10966. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10967. }
  10968. ] ),
  10969. vertexShader: [
  10970. "#define PHONG",
  10971. "varying vec3 vViewPosition;",
  10972. "varying vec3 vNormal;",
  10973. THREE.ShaderChunk[ "map_pars_vertex" ],
  10974. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10975. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10976. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10977. THREE.ShaderChunk[ "color_pars_vertex" ],
  10978. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10979. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10980. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10981. "void main() {",
  10982. THREE.ShaderChunk[ "map_vertex" ],
  10983. THREE.ShaderChunk[ "lightmap_vertex" ],
  10984. THREE.ShaderChunk[ "color_vertex" ],
  10985. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10986. THREE.ShaderChunk[ "skinbase_vertex" ],
  10987. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10988. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10989. "vNormal = normalize( transformedNormal );",
  10990. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10991. THREE.ShaderChunk[ "skinning_vertex" ],
  10992. THREE.ShaderChunk[ "default_vertex" ],
  10993. "vViewPosition = -mvPosition.xyz;",
  10994. THREE.ShaderChunk[ "worldpos_vertex" ],
  10995. THREE.ShaderChunk[ "envmap_vertex" ],
  10996. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10997. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10998. "}"
  10999. ].join("\n"),
  11000. fragmentShader: [
  11001. "uniform vec3 diffuse;",
  11002. "uniform float opacity;",
  11003. "uniform vec3 ambient;",
  11004. "uniform vec3 emissive;",
  11005. "uniform vec3 specular;",
  11006. "uniform float shininess;",
  11007. THREE.ShaderChunk[ "color_pars_fragment" ],
  11008. THREE.ShaderChunk[ "map_pars_fragment" ],
  11009. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11010. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11011. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11012. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11013. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11014. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11015. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11016. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11017. "void main() {",
  11018. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11019. THREE.ShaderChunk[ "map_fragment" ],
  11020. THREE.ShaderChunk[ "alphatest_fragment" ],
  11021. THREE.ShaderChunk[ "specularmap_fragment" ],
  11022. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11023. THREE.ShaderChunk[ "lightmap_fragment" ],
  11024. THREE.ShaderChunk[ "color_fragment" ],
  11025. THREE.ShaderChunk[ "envmap_fragment" ],
  11026. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11027. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11028. THREE.ShaderChunk[ "fog_fragment" ],
  11029. "}"
  11030. ].join("\n")
  11031. },
  11032. 'particle_basic': {
  11033. uniforms: THREE.UniformsUtils.merge( [
  11034. THREE.UniformsLib[ "particle" ],
  11035. THREE.UniformsLib[ "shadowmap" ]
  11036. ] ),
  11037. vertexShader: [
  11038. "uniform float size;",
  11039. "uniform float scale;",
  11040. THREE.ShaderChunk[ "color_pars_vertex" ],
  11041. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11042. "void main() {",
  11043. THREE.ShaderChunk[ "color_vertex" ],
  11044. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11045. "#ifdef USE_SIZEATTENUATION",
  11046. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11047. "#else",
  11048. "gl_PointSize = size;",
  11049. "#endif",
  11050. "gl_Position = projectionMatrix * mvPosition;",
  11051. THREE.ShaderChunk[ "worldpos_vertex" ],
  11052. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11053. "}"
  11054. ].join("\n"),
  11055. fragmentShader: [
  11056. "uniform vec3 psColor;",
  11057. "uniform float opacity;",
  11058. THREE.ShaderChunk[ "color_pars_fragment" ],
  11059. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11060. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11061. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11062. "void main() {",
  11063. "gl_FragColor = vec4( psColor, opacity );",
  11064. THREE.ShaderChunk[ "map_particle_fragment" ],
  11065. THREE.ShaderChunk[ "alphatest_fragment" ],
  11066. THREE.ShaderChunk[ "color_fragment" ],
  11067. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11068. THREE.ShaderChunk[ "fog_fragment" ],
  11069. "}"
  11070. ].join("\n")
  11071. },
  11072. 'dashed': {
  11073. uniforms: THREE.UniformsUtils.merge( [
  11074. THREE.UniformsLib[ "common" ],
  11075. THREE.UniformsLib[ "fog" ],
  11076. {
  11077. "scale": { type: "f", value: 1 },
  11078. "dashSize": { type: "f", value: 1 },
  11079. "totalSize": { type: "f", value: 2 }
  11080. }
  11081. ] ),
  11082. vertexShader: [
  11083. "uniform float scale;",
  11084. "attribute float lineDistance;",
  11085. "varying float vLineDistance;",
  11086. THREE.ShaderChunk[ "color_pars_vertex" ],
  11087. "void main() {",
  11088. THREE.ShaderChunk[ "color_vertex" ],
  11089. "vLineDistance = scale * lineDistance;",
  11090. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11091. "gl_Position = projectionMatrix * mvPosition;",
  11092. "}"
  11093. ].join("\n"),
  11094. fragmentShader: [
  11095. "uniform vec3 diffuse;",
  11096. "uniform float opacity;",
  11097. "uniform float dashSize;",
  11098. "uniform float totalSize;",
  11099. "varying float vLineDistance;",
  11100. THREE.ShaderChunk[ "color_pars_fragment" ],
  11101. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11102. "void main() {",
  11103. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11104. "discard;",
  11105. "}",
  11106. "gl_FragColor = vec4( diffuse, opacity );",
  11107. THREE.ShaderChunk[ "color_fragment" ],
  11108. THREE.ShaderChunk[ "fog_fragment" ],
  11109. "}"
  11110. ].join("\n")
  11111. },
  11112. 'depth': {
  11113. uniforms: {
  11114. "mNear": { type: "f", value: 1.0 },
  11115. "mFar" : { type: "f", value: 2000.0 },
  11116. "opacity" : { type: "f", value: 1.0 }
  11117. },
  11118. vertexShader: [
  11119. "void main() {",
  11120. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11121. "}"
  11122. ].join("\n"),
  11123. fragmentShader: [
  11124. "uniform float mNear;",
  11125. "uniform float mFar;",
  11126. "uniform float opacity;",
  11127. "void main() {",
  11128. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11129. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11130. "gl_FragColor = vec4( vec3( color ), opacity );",
  11131. "}"
  11132. ].join("\n")
  11133. },
  11134. 'normal': {
  11135. uniforms: {
  11136. "opacity" : { type: "f", value: 1.0 }
  11137. },
  11138. vertexShader: [
  11139. "varying vec3 vNormal;",
  11140. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11141. "void main() {",
  11142. "vNormal = normalize( normalMatrix * normal );",
  11143. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11144. THREE.ShaderChunk[ "default_vertex" ],
  11145. "}"
  11146. ].join("\n"),
  11147. fragmentShader: [
  11148. "uniform float opacity;",
  11149. "varying vec3 vNormal;",
  11150. "void main() {",
  11151. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11152. "}"
  11153. ].join("\n")
  11154. },
  11155. /* -------------------------------------------------------------------------
  11156. // Normal map shader
  11157. // - Blinn-Phong
  11158. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11159. // - point and directional lights (use with "lights: true" material option)
  11160. ------------------------------------------------------------------------- */
  11161. 'normalmap' : {
  11162. uniforms: THREE.UniformsUtils.merge( [
  11163. THREE.UniformsLib[ "fog" ],
  11164. THREE.UniformsLib[ "lights" ],
  11165. THREE.UniformsLib[ "shadowmap" ],
  11166. {
  11167. "enableAO" : { type: "i", value: 0 },
  11168. "enableDiffuse" : { type: "i", value: 0 },
  11169. "enableSpecular" : { type: "i", value: 0 },
  11170. "enableReflection": { type: "i", value: 0 },
  11171. "enableDisplacement": { type: "i", value: 0 },
  11172. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11173. "tDiffuse" : { type: "t", value: null },
  11174. "tCube" : { type: "t", value: null },
  11175. "tNormal" : { type: "t", value: null },
  11176. "tSpecular" : { type: "t", value: null },
  11177. "tAO" : { type: "t", value: null },
  11178. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11179. "uDisplacementBias": { type: "f", value: 0.0 },
  11180. "uDisplacementScale": { type: "f", value: 1.0 },
  11181. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11182. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11183. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11184. "uShininess": { type: "f", value: 30 },
  11185. "uOpacity": { type: "f", value: 1 },
  11186. "useRefract": { type: "i", value: 0 },
  11187. "uRefractionRatio": { type: "f", value: 0.98 },
  11188. "uReflectivity": { type: "f", value: 0.5 },
  11189. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11190. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11191. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11192. }
  11193. ] ),
  11194. fragmentShader: [
  11195. "uniform vec3 uAmbientColor;",
  11196. "uniform vec3 uDiffuseColor;",
  11197. "uniform vec3 uSpecularColor;",
  11198. "uniform float uShininess;",
  11199. "uniform float uOpacity;",
  11200. "uniform bool enableDiffuse;",
  11201. "uniform bool enableSpecular;",
  11202. "uniform bool enableAO;",
  11203. "uniform bool enableReflection;",
  11204. "uniform sampler2D tDiffuse;",
  11205. "uniform sampler2D tNormal;",
  11206. "uniform sampler2D tSpecular;",
  11207. "uniform sampler2D tAO;",
  11208. "uniform samplerCube tCube;",
  11209. "uniform vec2 uNormalScale;",
  11210. "uniform bool useRefract;",
  11211. "uniform float uRefractionRatio;",
  11212. "uniform float uReflectivity;",
  11213. "varying vec3 vTangent;",
  11214. "varying vec3 vBinormal;",
  11215. "varying vec3 vNormal;",
  11216. "varying vec2 vUv;",
  11217. "uniform vec3 ambientLightColor;",
  11218. "#if MAX_DIR_LIGHTS > 0",
  11219. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11220. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11221. "#endif",
  11222. "#if MAX_HEMI_LIGHTS > 0",
  11223. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11224. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11225. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11226. "#endif",
  11227. "#if MAX_POINT_LIGHTS > 0",
  11228. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11229. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11230. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11231. "#endif",
  11232. "#if MAX_SPOT_LIGHTS > 0",
  11233. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11234. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11235. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11236. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11237. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11238. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11239. "#endif",
  11240. "#ifdef WRAP_AROUND",
  11241. "uniform vec3 wrapRGB;",
  11242. "#endif",
  11243. "varying vec3 vWorldPosition;",
  11244. "varying vec3 vViewPosition;",
  11245. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11246. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11247. "void main() {",
  11248. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11249. "vec3 specularTex = vec3( 1.0 );",
  11250. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11251. "normalTex.xy *= uNormalScale;",
  11252. "normalTex = normalize( normalTex );",
  11253. "if( enableDiffuse ) {",
  11254. "#ifdef GAMMA_INPUT",
  11255. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11256. "texelColor.xyz *= texelColor.xyz;",
  11257. "gl_FragColor = gl_FragColor * texelColor;",
  11258. "#else",
  11259. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11260. "#endif",
  11261. "}",
  11262. "if( enableAO ) {",
  11263. "#ifdef GAMMA_INPUT",
  11264. "vec4 aoColor = texture2D( tAO, vUv );",
  11265. "aoColor.xyz *= aoColor.xyz;",
  11266. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11267. "#else",
  11268. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11269. "#endif",
  11270. "}",
  11271. "if( enableSpecular )",
  11272. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11273. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11274. "vec3 finalNormal = tsb * normalTex;",
  11275. "#ifdef FLIP_SIDED",
  11276. "finalNormal = -finalNormal;",
  11277. "#endif",
  11278. "vec3 normal = normalize( finalNormal );",
  11279. "vec3 viewPosition = normalize( vViewPosition );",
  11280. // point lights
  11281. "#if MAX_POINT_LIGHTS > 0",
  11282. "vec3 pointDiffuse = vec3( 0.0 );",
  11283. "vec3 pointSpecular = vec3( 0.0 );",
  11284. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11285. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11286. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11287. "float pointDistance = 1.0;",
  11288. "if ( pointLightDistance[ i ] > 0.0 )",
  11289. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11290. "pointVector = normalize( pointVector );",
  11291. // diffuse
  11292. "#ifdef WRAP_AROUND",
  11293. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11294. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11295. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11296. "#else",
  11297. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11298. "#endif",
  11299. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11300. // specular
  11301. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11302. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11303. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11304. "#ifdef PHYSICALLY_BASED_SHADING",
  11305. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11306. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11307. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11308. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11309. "#else",
  11310. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11311. "#endif",
  11312. "}",
  11313. "#endif",
  11314. // spot lights
  11315. "#if MAX_SPOT_LIGHTS > 0",
  11316. "vec3 spotDiffuse = vec3( 0.0 );",
  11317. "vec3 spotSpecular = vec3( 0.0 );",
  11318. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11319. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11320. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11321. "float spotDistance = 1.0;",
  11322. "if ( spotLightDistance[ i ] > 0.0 )",
  11323. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11324. "spotVector = normalize( spotVector );",
  11325. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11326. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11327. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11328. // diffuse
  11329. "#ifdef WRAP_AROUND",
  11330. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11331. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11332. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11333. "#else",
  11334. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11335. "#endif",
  11336. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11337. // specular
  11338. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11339. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11340. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11341. "#ifdef PHYSICALLY_BASED_SHADING",
  11342. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11343. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11344. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11345. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11346. "#else",
  11347. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11348. "#endif",
  11349. "}",
  11350. "}",
  11351. "#endif",
  11352. // directional lights
  11353. "#if MAX_DIR_LIGHTS > 0",
  11354. "vec3 dirDiffuse = vec3( 0.0 );",
  11355. "vec3 dirSpecular = vec3( 0.0 );",
  11356. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11357. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11358. "vec3 dirVector = normalize( lDirection.xyz );",
  11359. // diffuse
  11360. "#ifdef WRAP_AROUND",
  11361. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11362. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11363. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11364. "#else",
  11365. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11366. "#endif",
  11367. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11368. // specular
  11369. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11370. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11371. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11372. "#ifdef PHYSICALLY_BASED_SHADING",
  11373. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11374. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11375. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11376. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11377. "#else",
  11378. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11379. "#endif",
  11380. "}",
  11381. "#endif",
  11382. // hemisphere lights
  11383. "#if MAX_HEMI_LIGHTS > 0",
  11384. "vec3 hemiDiffuse = vec3( 0.0 );",
  11385. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11386. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11387. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11388. "vec3 lVector = normalize( lDirection.xyz );",
  11389. // diffuse
  11390. "float dotProduct = dot( normal, lVector );",
  11391. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11392. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11393. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11394. // specular (sky light)
  11395. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11396. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11397. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11398. // specular (ground light)
  11399. "vec3 lVectorGround = -lVector;",
  11400. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11401. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11402. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11403. "#ifdef PHYSICALLY_BASED_SHADING",
  11404. "float dotProductGround = dot( normal, lVectorGround );",
  11405. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11406. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11407. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11408. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11409. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11410. "#else",
  11411. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11412. "#endif",
  11413. "}",
  11414. "#endif",
  11415. // all lights contribution summation
  11416. "vec3 totalDiffuse = vec3( 0.0 );",
  11417. "vec3 totalSpecular = vec3( 0.0 );",
  11418. "#if MAX_DIR_LIGHTS > 0",
  11419. "totalDiffuse += dirDiffuse;",
  11420. "totalSpecular += dirSpecular;",
  11421. "#endif",
  11422. "#if MAX_HEMI_LIGHTS > 0",
  11423. "totalDiffuse += hemiDiffuse;",
  11424. "totalSpecular += hemiSpecular;",
  11425. "#endif",
  11426. "#if MAX_POINT_LIGHTS > 0",
  11427. "totalDiffuse += pointDiffuse;",
  11428. "totalSpecular += pointSpecular;",
  11429. "#endif",
  11430. "#if MAX_SPOT_LIGHTS > 0",
  11431. "totalDiffuse += spotDiffuse;",
  11432. "totalSpecular += spotSpecular;",
  11433. "#endif",
  11434. "#ifdef METAL",
  11435. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11436. "#else",
  11437. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11438. "#endif",
  11439. "if ( enableReflection ) {",
  11440. "vec3 vReflect;",
  11441. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11442. "if ( useRefract ) {",
  11443. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11444. "} else {",
  11445. "vReflect = reflect( cameraToVertex, normal );",
  11446. "}",
  11447. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11448. "#ifdef GAMMA_INPUT",
  11449. "cubeColor.xyz *= cubeColor.xyz;",
  11450. "#endif",
  11451. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11452. "}",
  11453. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11454. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11455. THREE.ShaderChunk[ "fog_fragment" ],
  11456. "}"
  11457. ].join("\n"),
  11458. vertexShader: [
  11459. "attribute vec4 tangent;",
  11460. "uniform vec2 uOffset;",
  11461. "uniform vec2 uRepeat;",
  11462. "uniform bool enableDisplacement;",
  11463. "#ifdef VERTEX_TEXTURES",
  11464. "uniform sampler2D tDisplacement;",
  11465. "uniform float uDisplacementScale;",
  11466. "uniform float uDisplacementBias;",
  11467. "#endif",
  11468. "varying vec3 vTangent;",
  11469. "varying vec3 vBinormal;",
  11470. "varying vec3 vNormal;",
  11471. "varying vec2 vUv;",
  11472. "varying vec3 vWorldPosition;",
  11473. "varying vec3 vViewPosition;",
  11474. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11475. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11476. "void main() {",
  11477. THREE.ShaderChunk[ "skinbase_vertex" ],
  11478. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11479. // normal, tangent and binormal vectors
  11480. "#ifdef USE_SKINNING",
  11481. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11482. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11483. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11484. "#else",
  11485. "vNormal = normalize( normalMatrix * normal );",
  11486. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11487. "#endif",
  11488. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11489. "vUv = uv * uRepeat + uOffset;",
  11490. // displacement mapping
  11491. "vec3 displacedPosition;",
  11492. "#ifdef VERTEX_TEXTURES",
  11493. "if ( enableDisplacement ) {",
  11494. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11495. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11496. "displacedPosition = position + normalize( normal ) * df;",
  11497. "} else {",
  11498. "#ifdef USE_SKINNING",
  11499. "vec4 skinVertex = vec4( position, 1.0 );",
  11500. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11501. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11502. "displacedPosition = skinned.xyz;",
  11503. "#else",
  11504. "displacedPosition = position;",
  11505. "#endif",
  11506. "}",
  11507. "#else",
  11508. "#ifdef USE_SKINNING",
  11509. "vec4 skinVertex = vec4( position, 1.0 );",
  11510. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11511. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11512. "displacedPosition = skinned.xyz;",
  11513. "#else",
  11514. "displacedPosition = position;",
  11515. "#endif",
  11516. "#endif",
  11517. //
  11518. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11519. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11520. "gl_Position = projectionMatrix * mvPosition;",
  11521. //
  11522. "vWorldPosition = worldPosition.xyz;",
  11523. "vViewPosition = -mvPosition.xyz;",
  11524. // shadows
  11525. "#ifdef USE_SHADOWMAP",
  11526. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11527. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11528. "}",
  11529. "#endif",
  11530. "}"
  11531. ].join("\n")
  11532. },
  11533. /* -------------------------------------------------------------------------
  11534. // Cube map shader
  11535. ------------------------------------------------------------------------- */
  11536. 'cube': {
  11537. uniforms: { "tCube": { type: "t", value: null },
  11538. "tFlip": { type: "f", value: -1 } },
  11539. vertexShader: [
  11540. "varying vec3 vWorldPosition;",
  11541. "void main() {",
  11542. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11543. "vWorldPosition = worldPosition.xyz;",
  11544. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11545. "}"
  11546. ].join("\n"),
  11547. fragmentShader: [
  11548. "uniform samplerCube tCube;",
  11549. "uniform float tFlip;",
  11550. "varying vec3 vWorldPosition;",
  11551. "void main() {",
  11552. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11553. "}"
  11554. ].join("\n")
  11555. },
  11556. // Depth encoding into RGBA texture
  11557. // based on SpiderGL shadow map example
  11558. // http://spidergl.org/example.php?id=6
  11559. // originally from
  11560. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11561. // see also here:
  11562. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11563. 'depthRGBA': {
  11564. uniforms: {},
  11565. vertexShader: [
  11566. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11567. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11568. "void main() {",
  11569. THREE.ShaderChunk[ "skinbase_vertex" ],
  11570. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11571. THREE.ShaderChunk[ "skinning_vertex" ],
  11572. THREE.ShaderChunk[ "default_vertex" ],
  11573. "}"
  11574. ].join("\n"),
  11575. fragmentShader: [
  11576. "vec4 pack_depth( const in float depth ) {",
  11577. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11578. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11579. "vec4 res = fract( depth * bit_shift );",
  11580. "res -= res.xxyz * bit_mask;",
  11581. "return res;",
  11582. "}",
  11583. "void main() {",
  11584. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11585. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11586. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11587. //"gl_FragData[ 0 ] = pack_depth( z );",
  11588. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11589. "}"
  11590. ].join("\n")
  11591. }
  11592. };
  11593. /**
  11594. * @author supereggbert / http://www.paulbrunt.co.uk/
  11595. * @author mrdoob / http://mrdoob.com/
  11596. * @author alteredq / http://alteredqualia.com/
  11597. * @author szimek / https://github.com/szimek/
  11598. */
  11599. THREE.WebGLRenderer = function ( parameters ) {
  11600. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11601. parameters = parameters || {};
  11602. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11603. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11604. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11605. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11606. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11607. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11608. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11609. _clearColor = new THREE.Color( 0x000000 ),
  11610. _clearAlpha = 0;
  11611. // public properties
  11612. this.domElement = _canvas;
  11613. this.context = null;
  11614. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11615. ? parameters.devicePixelRatio
  11616. : self.devicePixelRatio !== undefined
  11617. ? self.devicePixelRatio
  11618. : 1;
  11619. // clearing
  11620. this.autoClear = true;
  11621. this.autoClearColor = true;
  11622. this.autoClearDepth = true;
  11623. this.autoClearStencil = true;
  11624. // scene graph
  11625. this.sortObjects = true;
  11626. this.autoUpdateObjects = true;
  11627. // physically based shading
  11628. this.gammaInput = false;
  11629. this.gammaOutput = false;
  11630. this.physicallyBasedShading = false;
  11631. // shadow map
  11632. this.shadowMapEnabled = false;
  11633. this.shadowMapAutoUpdate = true;
  11634. this.shadowMapType = THREE.PCFShadowMap;
  11635. this.shadowMapCullFace = THREE.CullFaceFront;
  11636. this.shadowMapDebug = false;
  11637. this.shadowMapCascade = false;
  11638. // morphs
  11639. this.maxMorphTargets = 8;
  11640. this.maxMorphNormals = 4;
  11641. // flags
  11642. this.autoScaleCubemaps = true;
  11643. // custom render plugins
  11644. this.renderPluginsPre = [];
  11645. this.renderPluginsPost = [];
  11646. // info
  11647. this.info = {
  11648. memory: {
  11649. programs: 0,
  11650. geometries: 0,
  11651. textures: 0
  11652. },
  11653. render: {
  11654. calls: 0,
  11655. vertices: 0,
  11656. faces: 0,
  11657. points: 0
  11658. }
  11659. };
  11660. // internal properties
  11661. var _this = this,
  11662. _programs = [],
  11663. _programs_counter = 0,
  11664. // internal state cache
  11665. _currentProgram = null,
  11666. _currentFramebuffer = null,
  11667. _currentMaterialId = -1,
  11668. _currentGeometryGroupHash = null,
  11669. _currentCamera = null,
  11670. _geometryGroupCounter = 0,
  11671. _usedTextureUnits = 0,
  11672. // GL state cache
  11673. _oldDoubleSided = -1,
  11674. _oldFlipSided = -1,
  11675. _oldBlending = -1,
  11676. _oldBlendEquation = -1,
  11677. _oldBlendSrc = -1,
  11678. _oldBlendDst = -1,
  11679. _oldDepthTest = -1,
  11680. _oldDepthWrite = -1,
  11681. _oldPolygonOffset = null,
  11682. _oldPolygonOffsetFactor = null,
  11683. _oldPolygonOffsetUnits = null,
  11684. _oldLineWidth = null,
  11685. _viewportX = 0,
  11686. _viewportY = 0,
  11687. _viewportWidth = _canvas.width,
  11688. _viewportHeight = _canvas.height,
  11689. _currentWidth = 0,
  11690. _currentHeight = 0,
  11691. _enabledAttributes = {},
  11692. // frustum
  11693. _frustum = new THREE.Frustum(),
  11694. // camera matrices cache
  11695. _projScreenMatrix = new THREE.Matrix4(),
  11696. _projScreenMatrixPS = new THREE.Matrix4(),
  11697. _vector3 = new THREE.Vector3(),
  11698. // light arrays cache
  11699. _direction = new THREE.Vector3(),
  11700. _lightsNeedUpdate = true,
  11701. _lights = {
  11702. ambient: [ 0, 0, 0 ],
  11703. directional: { length: 0, colors: new Array(), positions: new Array() },
  11704. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11705. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11706. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11707. };
  11708. // initialize
  11709. var _gl;
  11710. var _glExtensionTextureFloat;
  11711. var _glExtensionTextureFloatLinear;
  11712. var _glExtensionStandardDerivatives;
  11713. var _glExtensionTextureFilterAnisotropic;
  11714. var _glExtensionCompressedTextureS3TC;
  11715. initGL();
  11716. setDefaultGLState();
  11717. this.context = _gl;
  11718. // GPU capabilities
  11719. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11720. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11721. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11722. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11723. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11724. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11725. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11726. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11727. //
  11728. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11729. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11730. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11731. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11732. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11733. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11734. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11735. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11736. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11737. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11738. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11739. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11740. // clamp precision to maximum available
  11741. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11742. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11743. if ( _precision === "highp" && ! highpAvailable ) {
  11744. if ( mediumpAvailable ) {
  11745. _precision = "mediump";
  11746. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11747. } else {
  11748. _precision = "lowp";
  11749. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11750. }
  11751. }
  11752. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11753. _precision = "lowp";
  11754. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11755. }
  11756. // API
  11757. this.getContext = function () {
  11758. return _gl;
  11759. };
  11760. this.supportsVertexTextures = function () {
  11761. return _supportsVertexTextures;
  11762. };
  11763. this.supportsFloatTextures = function () {
  11764. return _glExtensionTextureFloat;
  11765. };
  11766. this.supportsStandardDerivatives = function () {
  11767. return _glExtensionStandardDerivatives;
  11768. };
  11769. this.supportsCompressedTextureS3TC = function () {
  11770. return _glExtensionCompressedTextureS3TC;
  11771. };
  11772. this.getMaxAnisotropy = function () {
  11773. return _maxAnisotropy;
  11774. };
  11775. this.getPrecision = function () {
  11776. return _precision;
  11777. };
  11778. this.setSize = function ( width, height, updateStyle ) {
  11779. _canvas.width = width * this.devicePixelRatio;
  11780. _canvas.height = height * this.devicePixelRatio;
  11781. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11782. _canvas.style.width = width + 'px';
  11783. _canvas.style.height = height + 'px';
  11784. }
  11785. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11786. };
  11787. this.setViewport = function ( x, y, width, height ) {
  11788. _viewportX = x !== undefined ? x : 0;
  11789. _viewportY = y !== undefined ? y : 0;
  11790. _viewportWidth = width !== undefined ? width : _canvas.width;
  11791. _viewportHeight = height !== undefined ? height : _canvas.height;
  11792. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11793. };
  11794. this.setScissor = function ( x, y, width, height ) {
  11795. _gl.scissor( x, y, width, height );
  11796. };
  11797. this.enableScissorTest = function ( enable ) {
  11798. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11799. };
  11800. // Clearing
  11801. this.setClearColor = function ( color, alpha ) {
  11802. _clearColor.set( color );
  11803. _clearAlpha = alpha !== undefined ? alpha : 1;
  11804. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11805. };
  11806. this.setClearColorHex = function ( hex, alpha ) {
  11807. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11808. this.setClearColor( hex, alpha );
  11809. };
  11810. this.getClearColor = function () {
  11811. return _clearColor;
  11812. };
  11813. this.getClearAlpha = function () {
  11814. return _clearAlpha;
  11815. };
  11816. this.clear = function ( color, depth, stencil ) {
  11817. var bits = 0;
  11818. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11819. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11820. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11821. _gl.clear( bits );
  11822. };
  11823. this.clearColor = function () {
  11824. _gl.clear( _gl.COLOR_BUFFER_BIT );
  11825. };
  11826. this.clearDepth = function () {
  11827. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  11828. };
  11829. this.clearStencil = function () {
  11830. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  11831. };
  11832. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11833. this.setRenderTarget( renderTarget );
  11834. this.clear( color, depth, stencil );
  11835. };
  11836. // Plugins
  11837. this.addPostPlugin = function ( plugin ) {
  11838. plugin.init( this );
  11839. this.renderPluginsPost.push( plugin );
  11840. };
  11841. this.addPrePlugin = function ( plugin ) {
  11842. plugin.init( this );
  11843. this.renderPluginsPre.push( plugin );
  11844. };
  11845. // Rendering
  11846. this.updateShadowMap = function ( scene, camera ) {
  11847. _currentProgram = null;
  11848. _oldBlending = -1;
  11849. _oldDepthTest = -1;
  11850. _oldDepthWrite = -1;
  11851. _currentGeometryGroupHash = -1;
  11852. _currentMaterialId = -1;
  11853. _lightsNeedUpdate = true;
  11854. _oldDoubleSided = -1;
  11855. _oldFlipSided = -1;
  11856. this.shadowMapPlugin.update( scene, camera );
  11857. };
  11858. // Internal functions
  11859. // Buffer allocation
  11860. function createParticleBuffers ( geometry ) {
  11861. geometry.__webglVertexBuffer = _gl.createBuffer();
  11862. geometry.__webglColorBuffer = _gl.createBuffer();
  11863. _this.info.memory.geometries ++;
  11864. };
  11865. function createLineBuffers ( geometry ) {
  11866. geometry.__webglVertexBuffer = _gl.createBuffer();
  11867. geometry.__webglColorBuffer = _gl.createBuffer();
  11868. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11869. _this.info.memory.geometries ++;
  11870. };
  11871. function createMeshBuffers ( geometryGroup ) {
  11872. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11873. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11874. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11875. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11876. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11877. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11878. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11879. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11880. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11881. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11882. var m, ml;
  11883. if ( geometryGroup.numMorphTargets ) {
  11884. geometryGroup.__webglMorphTargetsBuffers = [];
  11885. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11886. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11887. }
  11888. }
  11889. if ( geometryGroup.numMorphNormals ) {
  11890. geometryGroup.__webglMorphNormalsBuffers = [];
  11891. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11892. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11893. }
  11894. }
  11895. _this.info.memory.geometries ++;
  11896. };
  11897. // Events
  11898. var onGeometryDispose = function ( event ) {
  11899. var geometry = event.target;
  11900. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11901. deallocateGeometry( geometry );
  11902. };
  11903. var onTextureDispose = function ( event ) {
  11904. var texture = event.target;
  11905. texture.removeEventListener( 'dispose', onTextureDispose );
  11906. deallocateTexture( texture );
  11907. _this.info.memory.textures --;
  11908. };
  11909. var onRenderTargetDispose = function ( event ) {
  11910. var renderTarget = event.target;
  11911. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11912. deallocateRenderTarget( renderTarget );
  11913. _this.info.memory.textures --;
  11914. };
  11915. var onMaterialDispose = function ( event ) {
  11916. var material = event.target;
  11917. material.removeEventListener( 'dispose', onMaterialDispose );
  11918. deallocateMaterial( material );
  11919. };
  11920. // Buffer deallocation
  11921. var deleteBuffers = function ( geometry ) {
  11922. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11923. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11924. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11925. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11926. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11927. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11928. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11929. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11930. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11931. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11932. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11933. // custom attributes
  11934. if ( geometry.__webglCustomAttributesList !== undefined ) {
  11935. for ( var id in geometry.__webglCustomAttributesList ) {
  11936. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11937. }
  11938. }
  11939. _this.info.memory.geometries --;
  11940. };
  11941. var deallocateGeometry = function ( geometry ) {
  11942. geometry.__webglInit = undefined;
  11943. if ( geometry instanceof THREE.BufferGeometry ) {
  11944. var attributes = geometry.attributes;
  11945. for ( var key in attributes ) {
  11946. if ( attributes[ key ].buffer !== undefined ) {
  11947. _gl.deleteBuffer( attributes[ key ].buffer );
  11948. }
  11949. }
  11950. _this.info.memory.geometries --;
  11951. } else {
  11952. if ( geometry.geometryGroups !== undefined ) {
  11953. for ( var g in geometry.geometryGroups ) {
  11954. var geometryGroup = geometry.geometryGroups[ g ];
  11955. if ( geometryGroup.numMorphTargets !== undefined ) {
  11956. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11957. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11958. }
  11959. }
  11960. if ( geometryGroup.numMorphNormals !== undefined ) {
  11961. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11962. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11963. }
  11964. }
  11965. deleteBuffers( geometryGroup );
  11966. }
  11967. } else {
  11968. deleteBuffers( geometry );
  11969. }
  11970. }
  11971. };
  11972. var deallocateTexture = function ( texture ) {
  11973. if ( texture.image && texture.image.__webglTextureCube ) {
  11974. // cube texture
  11975. _gl.deleteTexture( texture.image.__webglTextureCube );
  11976. } else {
  11977. // 2D texture
  11978. if ( ! texture.__webglInit ) return;
  11979. texture.__webglInit = false;
  11980. _gl.deleteTexture( texture.__webglTexture );
  11981. }
  11982. };
  11983. var deallocateRenderTarget = function ( renderTarget ) {
  11984. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11985. _gl.deleteTexture( renderTarget.__webglTexture );
  11986. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11987. for ( var i = 0; i < 6; i ++ ) {
  11988. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11989. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11990. }
  11991. } else {
  11992. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11993. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11994. }
  11995. };
  11996. var deallocateMaterial = function ( material ) {
  11997. var program = material.program;
  11998. if ( program === undefined ) return;
  11999. material.program = undefined;
  12000. // only deallocate GL program if this was the last use of shared program
  12001. // assumed there is only single copy of any program in the _programs list
  12002. // (that's how it's constructed)
  12003. var i, il, programInfo;
  12004. var deleteProgram = false;
  12005. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12006. programInfo = _programs[ i ];
  12007. if ( programInfo.program === program ) {
  12008. programInfo.usedTimes --;
  12009. if ( programInfo.usedTimes === 0 ) {
  12010. deleteProgram = true;
  12011. }
  12012. break;
  12013. }
  12014. }
  12015. if ( deleteProgram === true ) {
  12016. // avoid using array.splice, this is costlier than creating new array from scratch
  12017. var newPrograms = [];
  12018. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12019. programInfo = _programs[ i ];
  12020. if ( programInfo.program !== program ) {
  12021. newPrograms.push( programInfo );
  12022. }
  12023. }
  12024. _programs = newPrograms;
  12025. _gl.deleteProgram( program );
  12026. _this.info.memory.programs --;
  12027. }
  12028. };
  12029. // Buffer initialization
  12030. function initCustomAttributes ( geometry, object ) {
  12031. var nvertices = geometry.vertices.length;
  12032. var material = object.material;
  12033. if ( material.attributes ) {
  12034. if ( geometry.__webglCustomAttributesList === undefined ) {
  12035. geometry.__webglCustomAttributesList = [];
  12036. }
  12037. for ( var a in material.attributes ) {
  12038. var attribute = material.attributes[ a ];
  12039. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12040. attribute.__webglInitialized = true;
  12041. var size = 1; // "f" and "i"
  12042. if ( attribute.type === "v2" ) size = 2;
  12043. else if ( attribute.type === "v3" ) size = 3;
  12044. else if ( attribute.type === "v4" ) size = 4;
  12045. else if ( attribute.type === "c" ) size = 3;
  12046. attribute.size = size;
  12047. attribute.array = new Float32Array( nvertices * size );
  12048. attribute.buffer = _gl.createBuffer();
  12049. attribute.buffer.belongsToAttribute = a;
  12050. attribute.needsUpdate = true;
  12051. }
  12052. geometry.__webglCustomAttributesList.push( attribute );
  12053. }
  12054. }
  12055. };
  12056. function initParticleBuffers ( geometry, object ) {
  12057. var nvertices = geometry.vertices.length;
  12058. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12059. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12060. geometry.__sortArray = [];
  12061. geometry.__webglParticleCount = nvertices;
  12062. initCustomAttributes ( geometry, object );
  12063. };
  12064. function initLineBuffers ( geometry, object ) {
  12065. var nvertices = geometry.vertices.length;
  12066. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12067. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12068. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12069. geometry.__webglLineCount = nvertices;
  12070. initCustomAttributes ( geometry, object );
  12071. };
  12072. function initMeshBuffers ( geometryGroup, object ) {
  12073. var geometry = object.geometry,
  12074. faces3 = geometryGroup.faces3,
  12075. nvertices = faces3.length * 3,
  12076. ntris = faces3.length * 1,
  12077. nlines = faces3.length * 3,
  12078. material = getBufferMaterial( object, geometryGroup ),
  12079. uvType = bufferGuessUVType( material ),
  12080. normalType = bufferGuessNormalType( material ),
  12081. vertexColorType = bufferGuessVertexColorType( material );
  12082. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12083. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12084. if ( normalType ) {
  12085. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12086. }
  12087. if ( geometry.hasTangents ) {
  12088. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12089. }
  12090. if ( vertexColorType ) {
  12091. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12092. }
  12093. if ( uvType ) {
  12094. if ( geometry.faceVertexUvs.length > 0 ) {
  12095. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12096. }
  12097. if ( geometry.faceVertexUvs.length > 1 ) {
  12098. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12099. }
  12100. }
  12101. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12102. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12103. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12104. }
  12105. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  12106. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  12107. var m, ml;
  12108. if ( geometryGroup.numMorphTargets ) {
  12109. geometryGroup.__morphTargetsArrays = [];
  12110. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12111. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12112. }
  12113. }
  12114. if ( geometryGroup.numMorphNormals ) {
  12115. geometryGroup.__morphNormalsArrays = [];
  12116. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12117. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12118. }
  12119. }
  12120. geometryGroup.__webglFaceCount = ntris * 3;
  12121. geometryGroup.__webglLineCount = nlines * 2;
  12122. // custom attributes
  12123. if ( material.attributes ) {
  12124. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12125. geometryGroup.__webglCustomAttributesList = [];
  12126. }
  12127. for ( var a in material.attributes ) {
  12128. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12129. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12130. var originalAttribute = material.attributes[ a ];
  12131. var attribute = {};
  12132. for ( var property in originalAttribute ) {
  12133. attribute[ property ] = originalAttribute[ property ];
  12134. }
  12135. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12136. attribute.__webglInitialized = true;
  12137. var size = 1; // "f" and "i"
  12138. if( attribute.type === "v2" ) size = 2;
  12139. else if( attribute.type === "v3" ) size = 3;
  12140. else if( attribute.type === "v4" ) size = 4;
  12141. else if( attribute.type === "c" ) size = 3;
  12142. attribute.size = size;
  12143. attribute.array = new Float32Array( nvertices * size );
  12144. attribute.buffer = _gl.createBuffer();
  12145. attribute.buffer.belongsToAttribute = a;
  12146. originalAttribute.needsUpdate = true;
  12147. attribute.__original = originalAttribute;
  12148. }
  12149. geometryGroup.__webglCustomAttributesList.push( attribute );
  12150. }
  12151. }
  12152. geometryGroup.__inittedArrays = true;
  12153. };
  12154. function getBufferMaterial( object, geometryGroup ) {
  12155. return object.material instanceof THREE.MeshFaceMaterial
  12156. ? object.material.materials[ geometryGroup.materialIndex ]
  12157. : object.material;
  12158. };
  12159. function materialNeedsSmoothNormals ( material ) {
  12160. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12161. };
  12162. function bufferGuessNormalType ( material ) {
  12163. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12164. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12165. return false;
  12166. }
  12167. if ( materialNeedsSmoothNormals( material ) ) {
  12168. return THREE.SmoothShading;
  12169. } else {
  12170. return THREE.FlatShading;
  12171. }
  12172. };
  12173. function bufferGuessVertexColorType( material ) {
  12174. if ( material.vertexColors ) {
  12175. return material.vertexColors;
  12176. }
  12177. return false;
  12178. };
  12179. function bufferGuessUVType( material ) {
  12180. // material must use some texture to require uvs
  12181. if ( material.map ||
  12182. material.lightMap ||
  12183. material.bumpMap ||
  12184. material.normalMap ||
  12185. material.specularMap ||
  12186. material instanceof THREE.ShaderMaterial ) {
  12187. return true;
  12188. }
  12189. return false;
  12190. };
  12191. //
  12192. function initDirectBuffers( geometry ) {
  12193. var a, attribute, type;
  12194. for ( a in geometry.attributes ) {
  12195. if ( a === "index" ) {
  12196. type = _gl.ELEMENT_ARRAY_BUFFER;
  12197. } else {
  12198. type = _gl.ARRAY_BUFFER;
  12199. }
  12200. attribute = geometry.attributes[ a ];
  12201. if ( attribute.numItems === undefined ) {
  12202. attribute.numItems = attribute.array.length;
  12203. }
  12204. attribute.buffer = _gl.createBuffer();
  12205. _gl.bindBuffer( type, attribute.buffer );
  12206. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12207. }
  12208. };
  12209. // Buffer setting
  12210. function setParticleBuffers ( geometry, hint, object ) {
  12211. var v, c, vertex, offset, index, color,
  12212. vertices = geometry.vertices,
  12213. vl = vertices.length,
  12214. colors = geometry.colors,
  12215. cl = colors.length,
  12216. vertexArray = geometry.__vertexArray,
  12217. colorArray = geometry.__colorArray,
  12218. sortArray = geometry.__sortArray,
  12219. dirtyVertices = geometry.verticesNeedUpdate,
  12220. dirtyElements = geometry.elementsNeedUpdate,
  12221. dirtyColors = geometry.colorsNeedUpdate,
  12222. customAttributes = geometry.__webglCustomAttributesList,
  12223. i, il,
  12224. a, ca, cal, value,
  12225. customAttribute;
  12226. if ( object.sortParticles ) {
  12227. _projScreenMatrixPS.copy( _projScreenMatrix );
  12228. _projScreenMatrixPS.multiply( object.matrixWorld );
  12229. for ( v = 0; v < vl; v ++ ) {
  12230. vertex = vertices[ v ];
  12231. _vector3.copy( vertex );
  12232. _vector3.applyProjection( _projScreenMatrixPS );
  12233. sortArray[ v ] = [ _vector3.z, v ];
  12234. }
  12235. sortArray.sort( numericalSort );
  12236. for ( v = 0; v < vl; v ++ ) {
  12237. vertex = vertices[ sortArray[v][1] ];
  12238. offset = v * 3;
  12239. vertexArray[ offset ] = vertex.x;
  12240. vertexArray[ offset + 1 ] = vertex.y;
  12241. vertexArray[ offset + 2 ] = vertex.z;
  12242. }
  12243. for ( c = 0; c < cl; c ++ ) {
  12244. offset = c * 3;
  12245. color = colors[ sortArray[c][1] ];
  12246. colorArray[ offset ] = color.r;
  12247. colorArray[ offset + 1 ] = color.g;
  12248. colorArray[ offset + 2 ] = color.b;
  12249. }
  12250. if ( customAttributes ) {
  12251. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12252. customAttribute = customAttributes[ i ];
  12253. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12254. offset = 0;
  12255. cal = customAttribute.value.length;
  12256. if ( customAttribute.size === 1 ) {
  12257. for ( ca = 0; ca < cal; ca ++ ) {
  12258. index = sortArray[ ca ][ 1 ];
  12259. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12260. }
  12261. } else if ( customAttribute.size === 2 ) {
  12262. for ( ca = 0; ca < cal; ca ++ ) {
  12263. index = sortArray[ ca ][ 1 ];
  12264. value = customAttribute.value[ index ];
  12265. customAttribute.array[ offset ] = value.x;
  12266. customAttribute.array[ offset + 1 ] = value.y;
  12267. offset += 2;
  12268. }
  12269. } else if ( customAttribute.size === 3 ) {
  12270. if ( customAttribute.type === "c" ) {
  12271. for ( ca = 0; ca < cal; ca ++ ) {
  12272. index = sortArray[ ca ][ 1 ];
  12273. value = customAttribute.value[ index ];
  12274. customAttribute.array[ offset ] = value.r;
  12275. customAttribute.array[ offset + 1 ] = value.g;
  12276. customAttribute.array[ offset + 2 ] = value.b;
  12277. offset += 3;
  12278. }
  12279. } else {
  12280. for ( ca = 0; ca < cal; ca ++ ) {
  12281. index = sortArray[ ca ][ 1 ];
  12282. value = customAttribute.value[ index ];
  12283. customAttribute.array[ offset ] = value.x;
  12284. customAttribute.array[ offset + 1 ] = value.y;
  12285. customAttribute.array[ offset + 2 ] = value.z;
  12286. offset += 3;
  12287. }
  12288. }
  12289. } else if ( customAttribute.size === 4 ) {
  12290. for ( ca = 0; ca < cal; ca ++ ) {
  12291. index = sortArray[ ca ][ 1 ];
  12292. value = customAttribute.value[ index ];
  12293. customAttribute.array[ offset ] = value.x;
  12294. customAttribute.array[ offset + 1 ] = value.y;
  12295. customAttribute.array[ offset + 2 ] = value.z;
  12296. customAttribute.array[ offset + 3 ] = value.w;
  12297. offset += 4;
  12298. }
  12299. }
  12300. }
  12301. }
  12302. } else {
  12303. if ( dirtyVertices ) {
  12304. for ( v = 0; v < vl; v ++ ) {
  12305. vertex = vertices[ v ];
  12306. offset = v * 3;
  12307. vertexArray[ offset ] = vertex.x;
  12308. vertexArray[ offset + 1 ] = vertex.y;
  12309. vertexArray[ offset + 2 ] = vertex.z;
  12310. }
  12311. }
  12312. if ( dirtyColors ) {
  12313. for ( c = 0; c < cl; c ++ ) {
  12314. color = colors[ c ];
  12315. offset = c * 3;
  12316. colorArray[ offset ] = color.r;
  12317. colorArray[ offset + 1 ] = color.g;
  12318. colorArray[ offset + 2 ] = color.b;
  12319. }
  12320. }
  12321. if ( customAttributes ) {
  12322. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12323. customAttribute = customAttributes[ i ];
  12324. if ( customAttribute.needsUpdate &&
  12325. ( customAttribute.boundTo === undefined ||
  12326. customAttribute.boundTo === "vertices") ) {
  12327. cal = customAttribute.value.length;
  12328. offset = 0;
  12329. if ( customAttribute.size === 1 ) {
  12330. for ( ca = 0; ca < cal; ca ++ ) {
  12331. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12332. }
  12333. } else if ( customAttribute.size === 2 ) {
  12334. for ( ca = 0; ca < cal; ca ++ ) {
  12335. value = customAttribute.value[ ca ];
  12336. customAttribute.array[ offset ] = value.x;
  12337. customAttribute.array[ offset + 1 ] = value.y;
  12338. offset += 2;
  12339. }
  12340. } else if ( customAttribute.size === 3 ) {
  12341. if ( customAttribute.type === "c" ) {
  12342. for ( ca = 0; ca < cal; ca ++ ) {
  12343. value = customAttribute.value[ ca ];
  12344. customAttribute.array[ offset ] = value.r;
  12345. customAttribute.array[ offset + 1 ] = value.g;
  12346. customAttribute.array[ offset + 2 ] = value.b;
  12347. offset += 3;
  12348. }
  12349. } else {
  12350. for ( ca = 0; ca < cal; ca ++ ) {
  12351. value = customAttribute.value[ ca ];
  12352. customAttribute.array[ offset ] = value.x;
  12353. customAttribute.array[ offset + 1 ] = value.y;
  12354. customAttribute.array[ offset + 2 ] = value.z;
  12355. offset += 3;
  12356. }
  12357. }
  12358. } else if ( customAttribute.size === 4 ) {
  12359. for ( ca = 0; ca < cal; ca ++ ) {
  12360. value = customAttribute.value[ ca ];
  12361. customAttribute.array[ offset ] = value.x;
  12362. customAttribute.array[ offset + 1 ] = value.y;
  12363. customAttribute.array[ offset + 2 ] = value.z;
  12364. customAttribute.array[ offset + 3 ] = value.w;
  12365. offset += 4;
  12366. }
  12367. }
  12368. }
  12369. }
  12370. }
  12371. }
  12372. if ( dirtyVertices || object.sortParticles ) {
  12373. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12374. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12375. }
  12376. if ( dirtyColors || object.sortParticles ) {
  12377. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12378. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12379. }
  12380. if ( customAttributes ) {
  12381. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12382. customAttribute = customAttributes[ i ];
  12383. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12384. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12385. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12386. }
  12387. }
  12388. }
  12389. };
  12390. function setLineBuffers ( geometry, hint ) {
  12391. var v, c, d, vertex, offset, color,
  12392. vertices = geometry.vertices,
  12393. colors = geometry.colors,
  12394. lineDistances = geometry.lineDistances,
  12395. vl = vertices.length,
  12396. cl = colors.length,
  12397. dl = lineDistances.length,
  12398. vertexArray = geometry.__vertexArray,
  12399. colorArray = geometry.__colorArray,
  12400. lineDistanceArray = geometry.__lineDistanceArray,
  12401. dirtyVertices = geometry.verticesNeedUpdate,
  12402. dirtyColors = geometry.colorsNeedUpdate,
  12403. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12404. customAttributes = geometry.__webglCustomAttributesList,
  12405. i, il,
  12406. a, ca, cal, value,
  12407. customAttribute;
  12408. if ( dirtyVertices ) {
  12409. for ( v = 0; v < vl; v ++ ) {
  12410. vertex = vertices[ v ];
  12411. offset = v * 3;
  12412. vertexArray[ offset ] = vertex.x;
  12413. vertexArray[ offset + 1 ] = vertex.y;
  12414. vertexArray[ offset + 2 ] = vertex.z;
  12415. }
  12416. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12417. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12418. }
  12419. if ( dirtyColors ) {
  12420. for ( c = 0; c < cl; c ++ ) {
  12421. color = colors[ c ];
  12422. offset = c * 3;
  12423. colorArray[ offset ] = color.r;
  12424. colorArray[ offset + 1 ] = color.g;
  12425. colorArray[ offset + 2 ] = color.b;
  12426. }
  12427. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12428. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12429. }
  12430. if ( dirtyLineDistances ) {
  12431. for ( d = 0; d < dl; d ++ ) {
  12432. lineDistanceArray[ d ] = lineDistances[ d ];
  12433. }
  12434. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12435. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12436. }
  12437. if ( customAttributes ) {
  12438. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12439. customAttribute = customAttributes[ i ];
  12440. if ( customAttribute.needsUpdate &&
  12441. ( customAttribute.boundTo === undefined ||
  12442. customAttribute.boundTo === "vertices" ) ) {
  12443. offset = 0;
  12444. cal = customAttribute.value.length;
  12445. if ( customAttribute.size === 1 ) {
  12446. for ( ca = 0; ca < cal; ca ++ ) {
  12447. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12448. }
  12449. } else if ( customAttribute.size === 2 ) {
  12450. for ( ca = 0; ca < cal; ca ++ ) {
  12451. value = customAttribute.value[ ca ];
  12452. customAttribute.array[ offset ] = value.x;
  12453. customAttribute.array[ offset + 1 ] = value.y;
  12454. offset += 2;
  12455. }
  12456. } else if ( customAttribute.size === 3 ) {
  12457. if ( customAttribute.type === "c" ) {
  12458. for ( ca = 0; ca < cal; ca ++ ) {
  12459. value = customAttribute.value[ ca ];
  12460. customAttribute.array[ offset ] = value.r;
  12461. customAttribute.array[ offset + 1 ] = value.g;
  12462. customAttribute.array[ offset + 2 ] = value.b;
  12463. offset += 3;
  12464. }
  12465. } else {
  12466. for ( ca = 0; ca < cal; ca ++ ) {
  12467. value = customAttribute.value[ ca ];
  12468. customAttribute.array[ offset ] = value.x;
  12469. customAttribute.array[ offset + 1 ] = value.y;
  12470. customAttribute.array[ offset + 2 ] = value.z;
  12471. offset += 3;
  12472. }
  12473. }
  12474. } else if ( customAttribute.size === 4 ) {
  12475. for ( ca = 0; ca < cal; ca ++ ) {
  12476. value = customAttribute.value[ ca ];
  12477. customAttribute.array[ offset ] = value.x;
  12478. customAttribute.array[ offset + 1 ] = value.y;
  12479. customAttribute.array[ offset + 2 ] = value.z;
  12480. customAttribute.array[ offset + 3 ] = value.w;
  12481. offset += 4;
  12482. }
  12483. }
  12484. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12485. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12486. }
  12487. }
  12488. }
  12489. };
  12490. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12491. if ( ! geometryGroup.__inittedArrays ) {
  12492. return;
  12493. }
  12494. var normalType = bufferGuessNormalType( material ),
  12495. vertexColorType = bufferGuessVertexColorType( material ),
  12496. uvType = bufferGuessUVType( material ),
  12497. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12498. var f, fl, fi, face,
  12499. vertexNormals, faceNormal, normal,
  12500. vertexColors, faceColor,
  12501. vertexTangents,
  12502. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12503. c1, c2, c3, c4,
  12504. sw1, sw2, sw3, sw4,
  12505. si1, si2, si3, si4,
  12506. sa1, sa2, sa3, sa4,
  12507. sb1, sb2, sb3, sb4,
  12508. m, ml, i, il,
  12509. vn, uvi, uv2i,
  12510. vk, vkl, vka,
  12511. nka, chf, faceVertexNormals,
  12512. a,
  12513. vertexIndex = 0,
  12514. offset = 0,
  12515. offset_uv = 0,
  12516. offset_uv2 = 0,
  12517. offset_face = 0,
  12518. offset_normal = 0,
  12519. offset_tangent = 0,
  12520. offset_line = 0,
  12521. offset_color = 0,
  12522. offset_skin = 0,
  12523. offset_morphTarget = 0,
  12524. offset_custom = 0,
  12525. offset_customSrc = 0,
  12526. value,
  12527. vertexArray = geometryGroup.__vertexArray,
  12528. uvArray = geometryGroup.__uvArray,
  12529. uv2Array = geometryGroup.__uv2Array,
  12530. normalArray = geometryGroup.__normalArray,
  12531. tangentArray = geometryGroup.__tangentArray,
  12532. colorArray = geometryGroup.__colorArray,
  12533. skinIndexArray = geometryGroup.__skinIndexArray,
  12534. skinWeightArray = geometryGroup.__skinWeightArray,
  12535. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12536. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12537. customAttributes = geometryGroup.__webglCustomAttributesList,
  12538. customAttribute,
  12539. faceArray = geometryGroup.__faceArray,
  12540. lineArray = geometryGroup.__lineArray,
  12541. geometry = object.geometry, // this is shared for all chunks
  12542. dirtyVertices = geometry.verticesNeedUpdate,
  12543. dirtyElements = geometry.elementsNeedUpdate,
  12544. dirtyUvs = geometry.uvsNeedUpdate,
  12545. dirtyNormals = geometry.normalsNeedUpdate,
  12546. dirtyTangents = geometry.tangentsNeedUpdate,
  12547. dirtyColors = geometry.colorsNeedUpdate,
  12548. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12549. vertices = geometry.vertices,
  12550. chunk_faces3 = geometryGroup.faces3,
  12551. obj_faces = geometry.faces,
  12552. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12553. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12554. obj_colors = geometry.colors,
  12555. obj_skinIndices = geometry.skinIndices,
  12556. obj_skinWeights = geometry.skinWeights,
  12557. morphTargets = geometry.morphTargets,
  12558. morphNormals = geometry.morphNormals;
  12559. if ( dirtyVertices ) {
  12560. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12561. face = obj_faces[ chunk_faces3[ f ] ];
  12562. v1 = vertices[ face.a ];
  12563. v2 = vertices[ face.b ];
  12564. v3 = vertices[ face.c ];
  12565. vertexArray[ offset ] = v1.x;
  12566. vertexArray[ offset + 1 ] = v1.y;
  12567. vertexArray[ offset + 2 ] = v1.z;
  12568. vertexArray[ offset + 3 ] = v2.x;
  12569. vertexArray[ offset + 4 ] = v2.y;
  12570. vertexArray[ offset + 5 ] = v2.z;
  12571. vertexArray[ offset + 6 ] = v3.x;
  12572. vertexArray[ offset + 7 ] = v3.y;
  12573. vertexArray[ offset + 8 ] = v3.z;
  12574. offset += 9;
  12575. }
  12576. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12577. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12578. }
  12579. if ( dirtyMorphTargets ) {
  12580. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12581. offset_morphTarget = 0;
  12582. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12583. chf = chunk_faces3[ f ];
  12584. face = obj_faces[ chf ];
  12585. // morph positions
  12586. v1 = morphTargets[ vk ].vertices[ face.a ];
  12587. v2 = morphTargets[ vk ].vertices[ face.b ];
  12588. v3 = morphTargets[ vk ].vertices[ face.c ];
  12589. vka = morphTargetsArrays[ vk ];
  12590. vka[ offset_morphTarget ] = v1.x;
  12591. vka[ offset_morphTarget + 1 ] = v1.y;
  12592. vka[ offset_morphTarget + 2 ] = v1.z;
  12593. vka[ offset_morphTarget + 3 ] = v2.x;
  12594. vka[ offset_morphTarget + 4 ] = v2.y;
  12595. vka[ offset_morphTarget + 5 ] = v2.z;
  12596. vka[ offset_morphTarget + 6 ] = v3.x;
  12597. vka[ offset_morphTarget + 7 ] = v3.y;
  12598. vka[ offset_morphTarget + 8 ] = v3.z;
  12599. // morph normals
  12600. if ( material.morphNormals ) {
  12601. if ( needsSmoothNormals ) {
  12602. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12603. n1 = faceVertexNormals.a;
  12604. n2 = faceVertexNormals.b;
  12605. n3 = faceVertexNormals.c;
  12606. } else {
  12607. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12608. n2 = n1;
  12609. n3 = n1;
  12610. }
  12611. nka = morphNormalsArrays[ vk ];
  12612. nka[ offset_morphTarget ] = n1.x;
  12613. nka[ offset_morphTarget + 1 ] = n1.y;
  12614. nka[ offset_morphTarget + 2 ] = n1.z;
  12615. nka[ offset_morphTarget + 3 ] = n2.x;
  12616. nka[ offset_morphTarget + 4 ] = n2.y;
  12617. nka[ offset_morphTarget + 5 ] = n2.z;
  12618. nka[ offset_morphTarget + 6 ] = n3.x;
  12619. nka[ offset_morphTarget + 7 ] = n3.y;
  12620. nka[ offset_morphTarget + 8 ] = n3.z;
  12621. }
  12622. //
  12623. offset_morphTarget += 9;
  12624. }
  12625. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12626. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12627. if ( material.morphNormals ) {
  12628. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12629. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12630. }
  12631. }
  12632. }
  12633. if ( obj_skinWeights.length ) {
  12634. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12635. face = obj_faces[ chunk_faces3[ f ] ];
  12636. // weights
  12637. sw1 = obj_skinWeights[ face.a ];
  12638. sw2 = obj_skinWeights[ face.b ];
  12639. sw3 = obj_skinWeights[ face.c ];
  12640. skinWeightArray[ offset_skin ] = sw1.x;
  12641. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12642. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12643. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12644. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12645. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12646. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12647. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12648. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12649. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12650. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12651. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12652. // indices
  12653. si1 = obj_skinIndices[ face.a ];
  12654. si2 = obj_skinIndices[ face.b ];
  12655. si3 = obj_skinIndices[ face.c ];
  12656. skinIndexArray[ offset_skin ] = si1.x;
  12657. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12658. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12659. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12660. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12661. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12662. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12663. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12664. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12665. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12666. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12667. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12668. offset_skin += 12;
  12669. }
  12670. if ( offset_skin > 0 ) {
  12671. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12672. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12673. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12674. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12675. }
  12676. }
  12677. if ( dirtyColors && vertexColorType ) {
  12678. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12679. face = obj_faces[ chunk_faces3[ f ] ];
  12680. vertexColors = face.vertexColors;
  12681. faceColor = face.color;
  12682. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12683. c1 = vertexColors[ 0 ];
  12684. c2 = vertexColors[ 1 ];
  12685. c3 = vertexColors[ 2 ];
  12686. } else {
  12687. c1 = faceColor;
  12688. c2 = faceColor;
  12689. c3 = faceColor;
  12690. }
  12691. colorArray[ offset_color ] = c1.r;
  12692. colorArray[ offset_color + 1 ] = c1.g;
  12693. colorArray[ offset_color + 2 ] = c1.b;
  12694. colorArray[ offset_color + 3 ] = c2.r;
  12695. colorArray[ offset_color + 4 ] = c2.g;
  12696. colorArray[ offset_color + 5 ] = c2.b;
  12697. colorArray[ offset_color + 6 ] = c3.r;
  12698. colorArray[ offset_color + 7 ] = c3.g;
  12699. colorArray[ offset_color + 8 ] = c3.b;
  12700. offset_color += 9;
  12701. }
  12702. if ( offset_color > 0 ) {
  12703. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12704. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12705. }
  12706. }
  12707. if ( dirtyTangents && geometry.hasTangents ) {
  12708. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12709. face = obj_faces[ chunk_faces3[ f ] ];
  12710. vertexTangents = face.vertexTangents;
  12711. t1 = vertexTangents[ 0 ];
  12712. t2 = vertexTangents[ 1 ];
  12713. t3 = vertexTangents[ 2 ];
  12714. tangentArray[ offset_tangent ] = t1.x;
  12715. tangentArray[ offset_tangent + 1 ] = t1.y;
  12716. tangentArray[ offset_tangent + 2 ] = t1.z;
  12717. tangentArray[ offset_tangent + 3 ] = t1.w;
  12718. tangentArray[ offset_tangent + 4 ] = t2.x;
  12719. tangentArray[ offset_tangent + 5 ] = t2.y;
  12720. tangentArray[ offset_tangent + 6 ] = t2.z;
  12721. tangentArray[ offset_tangent + 7 ] = t2.w;
  12722. tangentArray[ offset_tangent + 8 ] = t3.x;
  12723. tangentArray[ offset_tangent + 9 ] = t3.y;
  12724. tangentArray[ offset_tangent + 10 ] = t3.z;
  12725. tangentArray[ offset_tangent + 11 ] = t3.w;
  12726. offset_tangent += 12;
  12727. }
  12728. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12729. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12730. }
  12731. if ( dirtyNormals && normalType ) {
  12732. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12733. face = obj_faces[ chunk_faces3[ f ] ];
  12734. vertexNormals = face.vertexNormals;
  12735. faceNormal = face.normal;
  12736. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12737. for ( i = 0; i < 3; i ++ ) {
  12738. vn = vertexNormals[ i ];
  12739. normalArray[ offset_normal ] = vn.x;
  12740. normalArray[ offset_normal + 1 ] = vn.y;
  12741. normalArray[ offset_normal + 2 ] = vn.z;
  12742. offset_normal += 3;
  12743. }
  12744. } else {
  12745. for ( i = 0; i < 3; i ++ ) {
  12746. normalArray[ offset_normal ] = faceNormal.x;
  12747. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12748. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12749. offset_normal += 3;
  12750. }
  12751. }
  12752. }
  12753. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12754. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12755. }
  12756. if ( dirtyUvs && obj_uvs && uvType ) {
  12757. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12758. fi = chunk_faces3[ f ];
  12759. uv = obj_uvs[ fi ];
  12760. if ( uv === undefined ) continue;
  12761. for ( i = 0; i < 3; i ++ ) {
  12762. uvi = uv[ i ];
  12763. uvArray[ offset_uv ] = uvi.x;
  12764. uvArray[ offset_uv + 1 ] = uvi.y;
  12765. offset_uv += 2;
  12766. }
  12767. }
  12768. if ( offset_uv > 0 ) {
  12769. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12770. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12771. }
  12772. }
  12773. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12774. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12775. fi = chunk_faces3[ f ];
  12776. uv2 = obj_uvs2[ fi ];
  12777. if ( uv2 === undefined ) continue;
  12778. for ( i = 0; i < 3; i ++ ) {
  12779. uv2i = uv2[ i ];
  12780. uv2Array[ offset_uv2 ] = uv2i.x;
  12781. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12782. offset_uv2 += 2;
  12783. }
  12784. }
  12785. if ( offset_uv2 > 0 ) {
  12786. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12787. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12788. }
  12789. }
  12790. if ( dirtyElements ) {
  12791. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12792. faceArray[ offset_face ] = vertexIndex;
  12793. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12794. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12795. offset_face += 3;
  12796. lineArray[ offset_line ] = vertexIndex;
  12797. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12798. lineArray[ offset_line + 2 ] = vertexIndex;
  12799. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12800. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12801. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12802. offset_line += 6;
  12803. vertexIndex += 3;
  12804. }
  12805. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12806. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12807. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12808. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12809. }
  12810. if ( customAttributes ) {
  12811. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12812. customAttribute = customAttributes[ i ];
  12813. if ( ! customAttribute.__original.needsUpdate ) continue;
  12814. offset_custom = 0;
  12815. offset_customSrc = 0;
  12816. if ( customAttribute.size === 1 ) {
  12817. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12818. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12819. face = obj_faces[ chunk_faces3[ f ] ];
  12820. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12821. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12822. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12823. offset_custom += 3;
  12824. }
  12825. } else if ( customAttribute.boundTo === "faces" ) {
  12826. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12827. value = customAttribute.value[ chunk_faces3[ f ] ];
  12828. customAttribute.array[ offset_custom ] = value;
  12829. customAttribute.array[ offset_custom + 1 ] = value;
  12830. customAttribute.array[ offset_custom + 2 ] = value;
  12831. offset_custom += 3;
  12832. }
  12833. }
  12834. } else if ( customAttribute.size === 2 ) {
  12835. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12836. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12837. face = obj_faces[ chunk_faces3[ f ] ];
  12838. v1 = customAttribute.value[ face.a ];
  12839. v2 = customAttribute.value[ face.b ];
  12840. v3 = customAttribute.value[ face.c ];
  12841. customAttribute.array[ offset_custom ] = v1.x;
  12842. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12843. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12844. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12845. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12846. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12847. offset_custom += 6;
  12848. }
  12849. } else if ( customAttribute.boundTo === "faces" ) {
  12850. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12851. value = customAttribute.value[ chunk_faces3[ f ] ];
  12852. v1 = value;
  12853. v2 = value;
  12854. v3 = value;
  12855. customAttribute.array[ offset_custom ] = v1.x;
  12856. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12857. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12858. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12859. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12860. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12861. offset_custom += 6;
  12862. }
  12863. }
  12864. } else if ( customAttribute.size === 3 ) {
  12865. var pp;
  12866. if ( customAttribute.type === "c" ) {
  12867. pp = [ "r", "g", "b" ];
  12868. } else {
  12869. pp = [ "x", "y", "z" ];
  12870. }
  12871. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12872. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12873. face = obj_faces[ chunk_faces3[ f ] ];
  12874. v1 = customAttribute.value[ face.a ];
  12875. v2 = customAttribute.value[ face.b ];
  12876. v3 = customAttribute.value[ face.c ];
  12877. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12878. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12879. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12880. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12881. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12882. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12883. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12884. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12885. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12886. offset_custom += 9;
  12887. }
  12888. } else if ( customAttribute.boundTo === "faces" ) {
  12889. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12890. value = customAttribute.value[ chunk_faces3[ f ] ];
  12891. v1 = value;
  12892. v2 = value;
  12893. v3 = value;
  12894. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12895. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12896. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12897. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12898. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12899. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12900. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12901. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12902. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12903. offset_custom += 9;
  12904. }
  12905. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12906. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12907. value = customAttribute.value[ chunk_faces3[ f ] ];
  12908. v1 = value[ 0 ];
  12909. v2 = value[ 1 ];
  12910. v3 = value[ 2 ];
  12911. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12912. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12913. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12914. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12915. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12916. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12917. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12918. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12919. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12920. offset_custom += 9;
  12921. }
  12922. }
  12923. } else if ( customAttribute.size === 4 ) {
  12924. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12925. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12926. face = obj_faces[ chunk_faces3[ f ] ];
  12927. v1 = customAttribute.value[ face.a ];
  12928. v2 = customAttribute.value[ face.b ];
  12929. v3 = customAttribute.value[ face.c ];
  12930. customAttribute.array[ offset_custom ] = v1.x;
  12931. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12932. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12933. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12934. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12935. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12936. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12937. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12938. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12939. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12940. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12941. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12942. offset_custom += 12;
  12943. }
  12944. } else if ( customAttribute.boundTo === "faces" ) {
  12945. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12946. value = customAttribute.value[ chunk_faces3[ f ] ];
  12947. v1 = value;
  12948. v2 = value;
  12949. v3 = value;
  12950. customAttribute.array[ offset_custom ] = v1.x;
  12951. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12952. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12953. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12954. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12955. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12956. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12957. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12958. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12959. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12960. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12961. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12962. offset_custom += 12;
  12963. }
  12964. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12965. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12966. value = customAttribute.value[ chunk_faces3[ f ] ];
  12967. v1 = value[ 0 ];
  12968. v2 = value[ 1 ];
  12969. v3 = value[ 2 ];
  12970. customAttribute.array[ offset_custom ] = v1.x;
  12971. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12972. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12973. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12974. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12975. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12976. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12977. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12978. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12979. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12980. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12981. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12982. offset_custom += 12;
  12983. }
  12984. }
  12985. }
  12986. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12987. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12988. }
  12989. }
  12990. if ( dispose ) {
  12991. delete geometryGroup.__inittedArrays;
  12992. delete geometryGroup.__colorArray;
  12993. delete geometryGroup.__normalArray;
  12994. delete geometryGroup.__tangentArray;
  12995. delete geometryGroup.__uvArray;
  12996. delete geometryGroup.__uv2Array;
  12997. delete geometryGroup.__faceArray;
  12998. delete geometryGroup.__vertexArray;
  12999. delete geometryGroup.__lineArray;
  13000. delete geometryGroup.__skinIndexArray;
  13001. delete geometryGroup.__skinWeightArray;
  13002. }
  13003. };
  13004. function setDirectBuffers ( geometry, hint, dispose ) {
  13005. var attributes = geometry.attributes;
  13006. var attributeName, attributeItem;
  13007. for ( attributeName in attributes ) {
  13008. attributeItem = attributes[ attributeName ];
  13009. if ( attributeItem.needsUpdate ) {
  13010. if ( attributeName === 'index' ) {
  13011. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13012. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13013. } else {
  13014. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13015. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13016. }
  13017. attributeItem.needsUpdate = false;
  13018. }
  13019. if ( dispose && ! attributeItem.dynamic ) {
  13020. attributeItem.array = null;
  13021. }
  13022. }
  13023. };
  13024. // Buffer rendering
  13025. this.renderBufferImmediate = function ( object, program, material ) {
  13026. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13027. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13028. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13029. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13030. if ( object.hasPositions ) {
  13031. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13032. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13033. _gl.enableVertexAttribArray( program.attributes.position );
  13034. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13035. }
  13036. if ( object.hasNormals ) {
  13037. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13038. if ( material.shading === THREE.FlatShading ) {
  13039. var nx, ny, nz,
  13040. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13041. normalArray,
  13042. i, il = object.count * 3;
  13043. for( i = 0; i < il; i += 9 ) {
  13044. normalArray = object.normalArray;
  13045. nax = normalArray[ i ];
  13046. nay = normalArray[ i + 1 ];
  13047. naz = normalArray[ i + 2 ];
  13048. nbx = normalArray[ i + 3 ];
  13049. nby = normalArray[ i + 4 ];
  13050. nbz = normalArray[ i + 5 ];
  13051. ncx = normalArray[ i + 6 ];
  13052. ncy = normalArray[ i + 7 ];
  13053. ncz = normalArray[ i + 8 ];
  13054. nx = ( nax + nbx + ncx ) / 3;
  13055. ny = ( nay + nby + ncy ) / 3;
  13056. nz = ( naz + nbz + ncz ) / 3;
  13057. normalArray[ i ] = nx;
  13058. normalArray[ i + 1 ] = ny;
  13059. normalArray[ i + 2 ] = nz;
  13060. normalArray[ i + 3 ] = nx;
  13061. normalArray[ i + 4 ] = ny;
  13062. normalArray[ i + 5 ] = nz;
  13063. normalArray[ i + 6 ] = nx;
  13064. normalArray[ i + 7 ] = ny;
  13065. normalArray[ i + 8 ] = nz;
  13066. }
  13067. }
  13068. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13069. _gl.enableVertexAttribArray( program.attributes.normal );
  13070. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13071. }
  13072. if ( object.hasUvs && material.map ) {
  13073. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13074. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13075. _gl.enableVertexAttribArray( program.attributes.uv );
  13076. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13077. }
  13078. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13079. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13080. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13081. _gl.enableVertexAttribArray( program.attributes.color );
  13082. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13083. }
  13084. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13085. object.count = 0;
  13086. };
  13087. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13088. if ( material.visible === false ) return;
  13089. var linewidth, a, attribute;
  13090. var attributeItem, attributeName, attributePointer, attributeSize;
  13091. var program = setProgram( camera, lights, fog, material, object );
  13092. var programAttributes = program.attributes;
  13093. var geometryAttributes = geometry.attributes;
  13094. var updateBuffers = false,
  13095. wireframeBit = material.wireframe ? 1 : 0,
  13096. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13097. if ( geometryHash !== _currentGeometryGroupHash ) {
  13098. _currentGeometryGroupHash = geometryHash;
  13099. updateBuffers = true;
  13100. }
  13101. if ( updateBuffers ) {
  13102. disableAttributes();
  13103. }
  13104. // render mesh
  13105. if ( object instanceof THREE.Mesh ) {
  13106. var index = geometryAttributes[ "index" ];
  13107. // indexed triangles
  13108. if ( index ) {
  13109. var offsets = geometry.offsets;
  13110. // if there is more than 1 chunk
  13111. // must set attribute pointers to use new offsets for each chunk
  13112. // even if geometry and materials didn't change
  13113. if ( offsets.length > 1 ) updateBuffers = true;
  13114. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13115. var startIndex = offsets[ i ].index;
  13116. if ( updateBuffers ) {
  13117. for ( attributeName in programAttributes ) {
  13118. attributePointer = programAttributes[ attributeName ];
  13119. attributeItem = geometryAttributes[ attributeName ];
  13120. if ( attributePointer >= 0 ) {
  13121. if ( attributeItem ) {
  13122. attributeSize = attributeItem.itemSize;
  13123. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13124. enableAttribute( attributePointer );
  13125. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13126. } else if ( material.defaultAttributeValues ) {
  13127. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13128. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13129. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13130. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13131. }
  13132. }
  13133. }
  13134. }
  13135. // indices
  13136. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13137. }
  13138. // render indexed triangles
  13139. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13140. _this.info.render.calls ++;
  13141. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13142. _this.info.render.faces += offsets[ i ].count / 3;
  13143. }
  13144. // non-indexed triangles
  13145. } else {
  13146. if ( updateBuffers ) {
  13147. for ( attributeName in programAttributes ) {
  13148. if ( attributeName === 'index') continue;
  13149. attributePointer = programAttributes[ attributeName ];
  13150. attributeItem = geometryAttributes[ attributeName ];
  13151. if ( attributePointer >= 0 ) {
  13152. if ( attributeItem ) {
  13153. attributeSize = attributeItem.itemSize;
  13154. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13155. enableAttribute( attributePointer );
  13156. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13157. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13158. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13159. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13160. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13161. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13162. }
  13163. }
  13164. }
  13165. }
  13166. }
  13167. var position = geometry.attributes[ "position" ];
  13168. // render non-indexed triangles
  13169. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13170. _this.info.render.calls ++;
  13171. _this.info.render.vertices += position.numItems / 3;
  13172. _this.info.render.faces += position.numItems / 3 / 3;
  13173. }
  13174. // render particles
  13175. } else if ( object instanceof THREE.ParticleSystem ) {
  13176. if ( updateBuffers ) {
  13177. for ( attributeName in programAttributes ) {
  13178. attributePointer = programAttributes[ attributeName ];
  13179. attributeItem = geometryAttributes[ attributeName ];
  13180. if ( attributePointer >= 0 ) {
  13181. if ( attributeItem ) {
  13182. attributeSize = attributeItem.itemSize;
  13183. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13184. enableAttribute( attributePointer );
  13185. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13186. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13187. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13188. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13189. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13190. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13191. }
  13192. }
  13193. }
  13194. }
  13195. var position = geometryAttributes[ "position" ];
  13196. // render particles
  13197. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13198. _this.info.render.calls ++;
  13199. _this.info.render.points += position.numItems / 3;
  13200. }
  13201. } else if ( object instanceof THREE.Line ) {
  13202. if ( updateBuffers ) {
  13203. for ( attributeName in programAttributes ) {
  13204. attributePointer = programAttributes[ attributeName ];
  13205. attributeItem = geometryAttributes[ attributeName ];
  13206. if ( attributePointer >= 0 ) {
  13207. if ( attributeItem ) {
  13208. attributeSize = attributeItem.itemSize;
  13209. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13210. enableAttribute( attributePointer );
  13211. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13212. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13213. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13214. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13215. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13216. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13217. }
  13218. }
  13219. }
  13220. }
  13221. // render lines
  13222. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13223. setLineWidth( material.linewidth );
  13224. var position = geometryAttributes[ "position" ];
  13225. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13226. _this.info.render.calls ++;
  13227. _this.info.render.points += position.numItems;
  13228. }
  13229. }
  13230. };
  13231. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13232. if ( material.visible === false ) return;
  13233. var linewidth, a, attribute, i, il;
  13234. var program = setProgram( camera, lights, fog, material, object );
  13235. var attributes = program.attributes;
  13236. var updateBuffers = false,
  13237. wireframeBit = material.wireframe ? 1 : 0,
  13238. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13239. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13240. _currentGeometryGroupHash = geometryGroupHash;
  13241. updateBuffers = true;
  13242. }
  13243. if ( updateBuffers ) {
  13244. disableAttributes();
  13245. }
  13246. // vertices
  13247. if ( !material.morphTargets && attributes.position >= 0 ) {
  13248. if ( updateBuffers ) {
  13249. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13250. enableAttribute( attributes.position );
  13251. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13252. }
  13253. } else {
  13254. if ( object.morphTargetBase ) {
  13255. setupMorphTargets( material, geometryGroup, object );
  13256. }
  13257. }
  13258. if ( updateBuffers ) {
  13259. // custom attributes
  13260. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13261. if ( geometryGroup.__webglCustomAttributesList ) {
  13262. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13263. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13264. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13265. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13266. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13267. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13268. }
  13269. }
  13270. }
  13271. // colors
  13272. if ( attributes.color >= 0 ) {
  13273. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13274. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13275. enableAttribute( attributes.color );
  13276. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13277. } else if ( material.defaultAttributeValues ) {
  13278. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13279. }
  13280. }
  13281. // normals
  13282. if ( attributes.normal >= 0 ) {
  13283. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13284. enableAttribute( attributes.normal );
  13285. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13286. }
  13287. // tangents
  13288. if ( attributes.tangent >= 0 ) {
  13289. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13290. enableAttribute( attributes.tangent );
  13291. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13292. }
  13293. // uvs
  13294. if ( attributes.uv >= 0 ) {
  13295. if ( object.geometry.faceVertexUvs[0] ) {
  13296. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13297. enableAttribute( attributes.uv );
  13298. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13299. } else if ( material.defaultAttributeValues ) {
  13300. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13301. }
  13302. }
  13303. if ( attributes.uv2 >= 0 ) {
  13304. if ( object.geometry.faceVertexUvs[1] ) {
  13305. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13306. enableAttribute( attributes.uv2 );
  13307. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13308. } else if ( material.defaultAttributeValues ) {
  13309. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13310. }
  13311. }
  13312. if ( material.skinning &&
  13313. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13314. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13315. enableAttribute( attributes.skinIndex );
  13316. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13317. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13318. enableAttribute( attributes.skinWeight );
  13319. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13320. }
  13321. // line distances
  13322. if ( attributes.lineDistance >= 0 ) {
  13323. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13324. enableAttribute( attributes.lineDistance );
  13325. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13326. }
  13327. }
  13328. // render mesh
  13329. if ( object instanceof THREE.Mesh ) {
  13330. // wireframe
  13331. if ( material.wireframe ) {
  13332. setLineWidth( material.wireframeLinewidth );
  13333. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13334. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13335. // triangles
  13336. } else {
  13337. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13338. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13339. }
  13340. _this.info.render.calls ++;
  13341. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13342. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13343. // render lines
  13344. } else if ( object instanceof THREE.Line ) {
  13345. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13346. setLineWidth( material.linewidth );
  13347. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13348. _this.info.render.calls ++;
  13349. // render particles
  13350. } else if ( object instanceof THREE.ParticleSystem ) {
  13351. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13352. _this.info.render.calls ++;
  13353. _this.info.render.points += geometryGroup.__webglParticleCount;
  13354. }
  13355. };
  13356. function enableAttribute( attribute ) {
  13357. if ( ! _enabledAttributes[ attribute ] ) {
  13358. _gl.enableVertexAttribArray( attribute );
  13359. _enabledAttributes[ attribute ] = true;
  13360. }
  13361. };
  13362. function disableAttributes() {
  13363. for ( var attribute in _enabledAttributes ) {
  13364. if ( _enabledAttributes[ attribute ] ) {
  13365. _gl.disableVertexAttribArray( attribute );
  13366. _enabledAttributes[ attribute ] = false;
  13367. }
  13368. }
  13369. };
  13370. function setupMorphTargets ( material, geometryGroup, object ) {
  13371. // set base
  13372. var attributes = material.program.attributes;
  13373. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13374. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13375. enableAttribute( attributes.position );
  13376. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13377. } else if ( attributes.position >= 0 ) {
  13378. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13379. enableAttribute( attributes.position );
  13380. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13381. }
  13382. if ( object.morphTargetForcedOrder.length ) {
  13383. // set forced order
  13384. var m = 0;
  13385. var order = object.morphTargetForcedOrder;
  13386. var influences = object.morphTargetInfluences;
  13387. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13388. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13389. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13390. enableAttribute( attributes[ "morphTarget" + m ] );
  13391. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13392. }
  13393. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13394. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13395. enableAttribute( attributes[ "morphNormal" + m ] );
  13396. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13397. }
  13398. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13399. m ++;
  13400. }
  13401. } else {
  13402. // find the most influencing
  13403. var influence, activeInfluenceIndices = [];
  13404. var influences = object.morphTargetInfluences;
  13405. var i, il = influences.length;
  13406. for ( i = 0; i < il; i ++ ) {
  13407. influence = influences[ i ];
  13408. if ( influence > 0 ) {
  13409. activeInfluenceIndices.push( [ influence, i ] );
  13410. }
  13411. }
  13412. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13413. activeInfluenceIndices.sort( numericalSort );
  13414. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13415. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13416. activeInfluenceIndices.sort( numericalSort );
  13417. } else if ( activeInfluenceIndices.length === 0 ) {
  13418. activeInfluenceIndices.push( [ 0, 0 ] );
  13419. };
  13420. var influenceIndex, m = 0;
  13421. while ( m < material.numSupportedMorphTargets ) {
  13422. if ( activeInfluenceIndices[ m ] ) {
  13423. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13424. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13425. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13426. enableAttribute( attributes[ "morphTarget" + m ] );
  13427. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13428. }
  13429. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13430. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13431. enableAttribute( attributes[ "morphNormal" + m ] );
  13432. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13433. }
  13434. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13435. } else {
  13436. /*
  13437. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13438. if ( material.morphNormals ) {
  13439. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13440. }
  13441. */
  13442. object.__webglMorphTargetInfluences[ m ] = 0;
  13443. }
  13444. m ++;
  13445. }
  13446. }
  13447. // load updated influences uniform
  13448. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13449. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13450. }
  13451. };
  13452. // Sorting
  13453. function painterSortStable ( a, b ) {
  13454. if ( a.z !== b.z ) {
  13455. return b.z - a.z;
  13456. } else {
  13457. return a.id - b.id;
  13458. }
  13459. };
  13460. function numericalSort ( a, b ) {
  13461. return b[ 0 ] - a[ 0 ];
  13462. };
  13463. // Rendering
  13464. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13465. if ( camera instanceof THREE.Camera === false ) {
  13466. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13467. return;
  13468. }
  13469. var i, il,
  13470. webglObject, object,
  13471. renderList,
  13472. lights = scene.__lights,
  13473. fog = scene.fog;
  13474. // reset caching for this frame
  13475. _currentMaterialId = -1;
  13476. _lightsNeedUpdate = true;
  13477. // update scene graph
  13478. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13479. // update camera matrices and frustum
  13480. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13481. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13482. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13483. _frustum.setFromMatrix( _projScreenMatrix );
  13484. // update WebGL objects
  13485. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13486. // custom render plugins (pre pass)
  13487. renderPlugins( this.renderPluginsPre, scene, camera );
  13488. //
  13489. _this.info.render.calls = 0;
  13490. _this.info.render.vertices = 0;
  13491. _this.info.render.faces = 0;
  13492. _this.info.render.points = 0;
  13493. this.setRenderTarget( renderTarget );
  13494. if ( this.autoClear || forceClear ) {
  13495. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13496. }
  13497. // set matrices for regular objects (frustum culled)
  13498. renderList = scene.__webglObjects;
  13499. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13500. webglObject = renderList[ i ];
  13501. object = webglObject.object;
  13502. webglObject.id = i;
  13503. webglObject.render = false;
  13504. if ( object.visible ) {
  13505. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13506. setupMatrices( object, camera );
  13507. unrollBufferMaterial( webglObject );
  13508. webglObject.render = true;
  13509. if ( this.sortObjects === true ) {
  13510. if ( object.renderDepth !== null ) {
  13511. webglObject.z = object.renderDepth;
  13512. } else {
  13513. _vector3.setFromMatrixPosition( object.matrixWorld );
  13514. _vector3.applyProjection( _projScreenMatrix );
  13515. webglObject.z = _vector3.z;
  13516. }
  13517. }
  13518. }
  13519. }
  13520. }
  13521. if ( this.sortObjects ) {
  13522. renderList.sort( painterSortStable );
  13523. }
  13524. // set matrices for immediate objects
  13525. renderList = scene.__webglObjectsImmediate;
  13526. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13527. webglObject = renderList[ i ];
  13528. object = webglObject.object;
  13529. if ( object.visible ) {
  13530. setupMatrices( object, camera );
  13531. unrollImmediateBufferMaterial( webglObject );
  13532. }
  13533. }
  13534. if ( scene.overrideMaterial ) {
  13535. var material = scene.overrideMaterial;
  13536. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13537. this.setDepthTest( material.depthTest );
  13538. this.setDepthWrite( material.depthWrite );
  13539. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13540. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13541. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13542. } else {
  13543. var material = null;
  13544. // opaque pass (front-to-back order)
  13545. this.setBlending( THREE.NoBlending );
  13546. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13547. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13548. // transparent pass (back-to-front order)
  13549. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13550. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13551. }
  13552. // custom render plugins (post pass)
  13553. renderPlugins( this.renderPluginsPost, scene, camera );
  13554. // Generate mipmap if we're using any kind of mipmap filtering
  13555. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13556. updateRenderTargetMipmap( renderTarget );
  13557. }
  13558. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13559. this.setDepthTest( true );
  13560. this.setDepthWrite( true );
  13561. // _gl.finish();
  13562. };
  13563. function renderPlugins( plugins, scene, camera ) {
  13564. if ( ! plugins.length ) return;
  13565. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13566. // reset state for plugin (to start from clean slate)
  13567. _currentProgram = null;
  13568. _currentCamera = null;
  13569. _oldBlending = -1;
  13570. _oldDepthTest = -1;
  13571. _oldDepthWrite = -1;
  13572. _oldDoubleSided = -1;
  13573. _oldFlipSided = -1;
  13574. _currentGeometryGroupHash = -1;
  13575. _currentMaterialId = -1;
  13576. _lightsNeedUpdate = true;
  13577. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13578. // reset state after plugin (anything could have changed)
  13579. _currentProgram = null;
  13580. _currentCamera = null;
  13581. _oldBlending = -1;
  13582. _oldDepthTest = -1;
  13583. _oldDepthWrite = -1;
  13584. _oldDoubleSided = -1;
  13585. _oldFlipSided = -1;
  13586. _currentGeometryGroupHash = -1;
  13587. _currentMaterialId = -1;
  13588. _lightsNeedUpdate = true;
  13589. }
  13590. };
  13591. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13592. var webglObject, object, buffer, material, start, end, delta;
  13593. if ( reverse ) {
  13594. start = renderList.length - 1;
  13595. end = -1;
  13596. delta = -1;
  13597. } else {
  13598. start = 0;
  13599. end = renderList.length;
  13600. delta = 1;
  13601. }
  13602. for ( var i = start; i !== end; i += delta ) {
  13603. webglObject = renderList[ i ];
  13604. if ( webglObject.render ) {
  13605. object = webglObject.object;
  13606. buffer = webglObject.buffer;
  13607. if ( overrideMaterial ) {
  13608. material = overrideMaterial;
  13609. } else {
  13610. material = webglObject[ materialType ];
  13611. if ( ! material ) continue;
  13612. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13613. _this.setDepthTest( material.depthTest );
  13614. _this.setDepthWrite( material.depthWrite );
  13615. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13616. }
  13617. _this.setMaterialFaces( material );
  13618. if ( buffer instanceof THREE.BufferGeometry ) {
  13619. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13620. } else {
  13621. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13622. }
  13623. }
  13624. }
  13625. };
  13626. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13627. var webglObject, object, material, program;
  13628. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13629. webglObject = renderList[ i ];
  13630. object = webglObject.object;
  13631. if ( object.visible ) {
  13632. if ( overrideMaterial ) {
  13633. material = overrideMaterial;
  13634. } else {
  13635. material = webglObject[ materialType ];
  13636. if ( ! material ) continue;
  13637. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13638. _this.setDepthTest( material.depthTest );
  13639. _this.setDepthWrite( material.depthWrite );
  13640. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13641. }
  13642. _this.renderImmediateObject( camera, lights, fog, material, object );
  13643. }
  13644. }
  13645. };
  13646. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13647. var program = setProgram( camera, lights, fog, material, object );
  13648. _currentGeometryGroupHash = -1;
  13649. _this.setMaterialFaces( material );
  13650. if ( object.immediateRenderCallback ) {
  13651. object.immediateRenderCallback( program, _gl, _frustum );
  13652. } else {
  13653. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13654. }
  13655. };
  13656. function unrollImmediateBufferMaterial ( globject ) {
  13657. var object = globject.object,
  13658. material = object.material;
  13659. if ( material.transparent ) {
  13660. globject.transparent = material;
  13661. globject.opaque = null;
  13662. } else {
  13663. globject.opaque = material;
  13664. globject.transparent = null;
  13665. }
  13666. };
  13667. function unrollBufferMaterial ( globject ) {
  13668. var object = globject.object,
  13669. buffer = globject.buffer,
  13670. material, materialIndex, meshMaterial;
  13671. meshMaterial = object.material;
  13672. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13673. materialIndex = buffer.materialIndex;
  13674. material = meshMaterial.materials[ materialIndex ];
  13675. if ( material.transparent ) {
  13676. globject.transparent = material;
  13677. globject.opaque = null;
  13678. } else {
  13679. globject.opaque = material;
  13680. globject.transparent = null;
  13681. }
  13682. } else {
  13683. material = meshMaterial;
  13684. if ( material ) {
  13685. if ( material.transparent ) {
  13686. globject.transparent = material;
  13687. globject.opaque = null;
  13688. } else {
  13689. globject.opaque = material;
  13690. globject.transparent = null;
  13691. }
  13692. }
  13693. }
  13694. };
  13695. // Geometry splitting
  13696. function sortFacesByMaterial ( geometry, material ) {
  13697. var f, fl, face, materialIndex, vertices,
  13698. groupHash, hash_map = {};
  13699. var numMorphTargets = geometry.morphTargets.length;
  13700. var numMorphNormals = geometry.morphNormals.length;
  13701. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13702. geometry.geometryGroups = {};
  13703. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13704. face = geometry.faces[ f ];
  13705. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13706. if ( hash_map[ materialIndex ] === undefined ) {
  13707. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13708. }
  13709. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13710. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13711. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13712. }
  13713. vertices = 3;
  13714. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13715. hash_map[ materialIndex ].counter += 1;
  13716. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13717. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13718. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13719. }
  13720. }
  13721. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13722. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13723. }
  13724. geometry.geometryGroupsList = [];
  13725. for ( var g in geometry.geometryGroups ) {
  13726. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13727. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13728. }
  13729. };
  13730. // Objects refresh
  13731. this.initWebGLObjects = function ( scene ) {
  13732. if ( !scene.__webglObjects ) {
  13733. scene.__webglObjects = [];
  13734. scene.__webglObjectsImmediate = [];
  13735. scene.__webglSprites = [];
  13736. scene.__webglFlares = [];
  13737. }
  13738. while ( scene.__objectsAdded.length ) {
  13739. addObject( scene.__objectsAdded[ 0 ], scene );
  13740. scene.__objectsAdded.splice( 0, 1 );
  13741. }
  13742. while ( scene.__objectsRemoved.length ) {
  13743. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13744. scene.__objectsRemoved.splice( 0, 1 );
  13745. }
  13746. // update must be called after objects adding / removal
  13747. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13748. var object = scene.__webglObjects[ o ].object;
  13749. // TODO: Remove this hack (WebGLRenderer refactoring)
  13750. if ( object.__webglInit === undefined ) {
  13751. if ( object.__webglActive !== undefined ) {
  13752. removeObject( object, scene );
  13753. }
  13754. addObject( object, scene );
  13755. }
  13756. updateObject( object );
  13757. }
  13758. };
  13759. // Objects adding
  13760. function addObject( object, scene ) {
  13761. var g, geometry, material, geometryGroup;
  13762. if ( object.__webglInit === undefined ) {
  13763. object.__webglInit = true;
  13764. object._modelViewMatrix = new THREE.Matrix4();
  13765. object._normalMatrix = new THREE.Matrix3();
  13766. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13767. object.geometry.__webglInit = true;
  13768. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13769. }
  13770. geometry = object.geometry;
  13771. if ( geometry === undefined ) {
  13772. // fail silently for now
  13773. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13774. initDirectBuffers( geometry );
  13775. } else if ( object instanceof THREE.Mesh ) {
  13776. material = object.material;
  13777. if ( geometry.geometryGroups === undefined ) {
  13778. sortFacesByMaterial( geometry, material );
  13779. }
  13780. // create separate VBOs per geometry chunk
  13781. for ( g in geometry.geometryGroups ) {
  13782. geometryGroup = geometry.geometryGroups[ g ];
  13783. // initialise VBO on the first access
  13784. if ( ! geometryGroup.__webglVertexBuffer ) {
  13785. createMeshBuffers( geometryGroup );
  13786. initMeshBuffers( geometryGroup, object );
  13787. geometry.verticesNeedUpdate = true;
  13788. geometry.morphTargetsNeedUpdate = true;
  13789. geometry.elementsNeedUpdate = true;
  13790. geometry.uvsNeedUpdate = true;
  13791. geometry.normalsNeedUpdate = true;
  13792. geometry.tangentsNeedUpdate = true;
  13793. geometry.colorsNeedUpdate = true;
  13794. }
  13795. }
  13796. } else if ( object instanceof THREE.Line ) {
  13797. if ( ! geometry.__webglVertexBuffer ) {
  13798. createLineBuffers( geometry );
  13799. initLineBuffers( geometry, object );
  13800. geometry.verticesNeedUpdate = true;
  13801. geometry.colorsNeedUpdate = true;
  13802. geometry.lineDistancesNeedUpdate = true;
  13803. }
  13804. } else if ( object instanceof THREE.ParticleSystem ) {
  13805. if ( ! geometry.__webglVertexBuffer ) {
  13806. createParticleBuffers( geometry );
  13807. initParticleBuffers( geometry, object );
  13808. geometry.verticesNeedUpdate = true;
  13809. geometry.colorsNeedUpdate = true;
  13810. }
  13811. }
  13812. }
  13813. if ( object.__webglActive === undefined ) {
  13814. if ( object instanceof THREE.Mesh ) {
  13815. geometry = object.geometry;
  13816. if ( geometry instanceof THREE.BufferGeometry ) {
  13817. addBuffer( scene.__webglObjects, geometry, object );
  13818. } else if ( geometry instanceof THREE.Geometry ) {
  13819. for ( g in geometry.geometryGroups ) {
  13820. geometryGroup = geometry.geometryGroups[ g ];
  13821. addBuffer( scene.__webglObjects, geometryGroup, object );
  13822. }
  13823. }
  13824. } else if ( object instanceof THREE.Line ||
  13825. object instanceof THREE.ParticleSystem ) {
  13826. geometry = object.geometry;
  13827. addBuffer( scene.__webglObjects, geometry, object );
  13828. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13829. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13830. } else if ( object instanceof THREE.Sprite ) {
  13831. scene.__webglSprites.push( object );
  13832. } else if ( object instanceof THREE.LensFlare ) {
  13833. scene.__webglFlares.push( object );
  13834. }
  13835. object.__webglActive = true;
  13836. }
  13837. };
  13838. function addBuffer( objlist, buffer, object ) {
  13839. objlist.push(
  13840. {
  13841. id: null,
  13842. buffer: buffer,
  13843. object: object,
  13844. opaque: null,
  13845. transparent: null,
  13846. z: 0
  13847. }
  13848. );
  13849. };
  13850. function addBufferImmediate( objlist, object ) {
  13851. objlist.push(
  13852. {
  13853. id: null,
  13854. object: object,
  13855. opaque: null,
  13856. transparent: null,
  13857. z: 0
  13858. }
  13859. );
  13860. };
  13861. // Objects updates
  13862. function updateObject( object ) {
  13863. var geometry = object.geometry,
  13864. geometryGroup, customAttributesDirty, material;
  13865. if ( geometry instanceof THREE.BufferGeometry ) {
  13866. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13867. } else if ( object instanceof THREE.Mesh ) {
  13868. // check all geometry groups
  13869. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13870. geometryGroup = geometry.geometryGroupsList[ i ];
  13871. material = getBufferMaterial( object, geometryGroup );
  13872. if ( geometry.buffersNeedUpdate ) {
  13873. initMeshBuffers( geometryGroup, object );
  13874. }
  13875. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13876. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13877. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13878. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13879. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13880. }
  13881. }
  13882. geometry.verticesNeedUpdate = false;
  13883. geometry.morphTargetsNeedUpdate = false;
  13884. geometry.elementsNeedUpdate = false;
  13885. geometry.uvsNeedUpdate = false;
  13886. geometry.normalsNeedUpdate = false;
  13887. geometry.colorsNeedUpdate = false;
  13888. geometry.tangentsNeedUpdate = false;
  13889. geometry.buffersNeedUpdate = false;
  13890. material.attributes && clearCustomAttributes( material );
  13891. } else if ( object instanceof THREE.Line ) {
  13892. material = getBufferMaterial( object, geometry );
  13893. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13894. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13895. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13896. }
  13897. geometry.verticesNeedUpdate = false;
  13898. geometry.colorsNeedUpdate = false;
  13899. geometry.lineDistancesNeedUpdate = false;
  13900. material.attributes && clearCustomAttributes( material );
  13901. } else if ( object instanceof THREE.ParticleSystem ) {
  13902. material = getBufferMaterial( object, geometry );
  13903. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13904. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13905. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13906. }
  13907. geometry.verticesNeedUpdate = false;
  13908. geometry.colorsNeedUpdate = false;
  13909. material.attributes && clearCustomAttributes( material );
  13910. }
  13911. };
  13912. // Objects updates - custom attributes check
  13913. function areCustomAttributesDirty( material ) {
  13914. for ( var a in material.attributes ) {
  13915. if ( material.attributes[ a ].needsUpdate ) return true;
  13916. }
  13917. return false;
  13918. };
  13919. function clearCustomAttributes( material ) {
  13920. for ( var a in material.attributes ) {
  13921. material.attributes[ a ].needsUpdate = false;
  13922. }
  13923. };
  13924. // Objects removal
  13925. function removeObject( object, scene ) {
  13926. if ( object instanceof THREE.Mesh ||
  13927. object instanceof THREE.ParticleSystem ||
  13928. object instanceof THREE.Line ) {
  13929. removeInstances( scene.__webglObjects, object );
  13930. } else if ( object instanceof THREE.Sprite ) {
  13931. removeInstancesDirect( scene.__webglSprites, object );
  13932. } else if ( object instanceof THREE.LensFlare ) {
  13933. removeInstancesDirect( scene.__webglFlares, object );
  13934. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13935. removeInstances( scene.__webglObjectsImmediate, object );
  13936. }
  13937. delete object.__webglActive;
  13938. };
  13939. function removeInstances( objlist, object ) {
  13940. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13941. if ( objlist[ o ].object === object ) {
  13942. objlist.splice( o, 1 );
  13943. }
  13944. }
  13945. };
  13946. function removeInstancesDirect( objlist, object ) {
  13947. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13948. if ( objlist[ o ] === object ) {
  13949. objlist.splice( o, 1 );
  13950. }
  13951. }
  13952. };
  13953. // Materials
  13954. this.initMaterial = function ( material, lights, fog, object ) {
  13955. material.addEventListener( 'dispose', onMaterialDispose );
  13956. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13957. if ( material instanceof THREE.MeshDepthMaterial ) {
  13958. shaderID = 'depth';
  13959. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13960. shaderID = 'normal';
  13961. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13962. shaderID = 'basic';
  13963. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13964. shaderID = 'lambert';
  13965. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13966. shaderID = 'phong';
  13967. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13968. shaderID = 'basic';
  13969. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13970. shaderID = 'dashed';
  13971. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  13972. shaderID = 'particle_basic';
  13973. }
  13974. if ( shaderID ) {
  13975. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13976. }
  13977. // heuristics to create shader parameters according to lights in the scene
  13978. // (not to blow over maxLights budget)
  13979. maxLightCount = allocateLights( lights );
  13980. maxShadows = allocateShadows( lights );
  13981. maxBones = allocateBones( object );
  13982. parameters = {
  13983. map: !!material.map,
  13984. envMap: !!material.envMap,
  13985. lightMap: !!material.lightMap,
  13986. bumpMap: !!material.bumpMap,
  13987. normalMap: !!material.normalMap,
  13988. specularMap: !!material.specularMap,
  13989. vertexColors: material.vertexColors,
  13990. fog: fog,
  13991. useFog: material.fog,
  13992. fogExp: fog instanceof THREE.FogExp2,
  13993. sizeAttenuation: material.sizeAttenuation,
  13994. skinning: material.skinning,
  13995. maxBones: maxBones,
  13996. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13997. morphTargets: material.morphTargets,
  13998. morphNormals: material.morphNormals,
  13999. maxMorphTargets: this.maxMorphTargets,
  14000. maxMorphNormals: this.maxMorphNormals,
  14001. maxDirLights: maxLightCount.directional,
  14002. maxPointLights: maxLightCount.point,
  14003. maxSpotLights: maxLightCount.spot,
  14004. maxHemiLights: maxLightCount.hemi,
  14005. maxShadows: maxShadows,
  14006. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  14007. shadowMapType: this.shadowMapType,
  14008. shadowMapDebug: this.shadowMapDebug,
  14009. shadowMapCascade: this.shadowMapCascade,
  14010. alphaTest: material.alphaTest,
  14011. metal: material.metal,
  14012. perPixel: material.perPixel,
  14013. wrapAround: material.wrapAround,
  14014. doubleSided: material.side === THREE.DoubleSide,
  14015. flipSided: material.side === THREE.BackSide
  14016. };
  14017. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  14018. var attributes = material.program.attributes;
  14019. if ( material.morphTargets ) {
  14020. material.numSupportedMorphTargets = 0;
  14021. var id, base = "morphTarget";
  14022. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14023. id = base + i;
  14024. if ( attributes[ id ] >= 0 ) {
  14025. material.numSupportedMorphTargets ++;
  14026. }
  14027. }
  14028. }
  14029. if ( material.morphNormals ) {
  14030. material.numSupportedMorphNormals = 0;
  14031. var id, base = "morphNormal";
  14032. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14033. id = base + i;
  14034. if ( attributes[ id ] >= 0 ) {
  14035. material.numSupportedMorphNormals ++;
  14036. }
  14037. }
  14038. }
  14039. material.uniformsList = [];
  14040. for ( u in material.uniforms ) {
  14041. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14042. }
  14043. };
  14044. function setMaterialShaders( material, shaders ) {
  14045. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14046. material.vertexShader = shaders.vertexShader;
  14047. material.fragmentShader = shaders.fragmentShader;
  14048. };
  14049. function setProgram( camera, lights, fog, material, object ) {
  14050. _usedTextureUnits = 0;
  14051. if ( material.needsUpdate ) {
  14052. if ( material.program ) deallocateMaterial( material );
  14053. _this.initMaterial( material, lights, fog, object );
  14054. material.needsUpdate = false;
  14055. }
  14056. if ( material.morphTargets ) {
  14057. if ( ! object.__webglMorphTargetInfluences ) {
  14058. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14059. }
  14060. }
  14061. var refreshMaterial = false;
  14062. var program = material.program,
  14063. p_uniforms = program.uniforms,
  14064. m_uniforms = material.uniforms;
  14065. if ( program !== _currentProgram ) {
  14066. _gl.useProgram( program );
  14067. _currentProgram = program;
  14068. refreshMaterial = true;
  14069. }
  14070. if ( material.id !== _currentMaterialId ) {
  14071. _currentMaterialId = material.id;
  14072. refreshMaterial = true;
  14073. }
  14074. if ( refreshMaterial || camera !== _currentCamera ) {
  14075. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14076. if ( camera !== _currentCamera ) _currentCamera = camera;
  14077. }
  14078. // skinning uniforms must be set even if material didn't change
  14079. // auto-setting of texture unit for bone texture must go before other textures
  14080. // not sure why, but otherwise weird things happen
  14081. if ( material.skinning ) {
  14082. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14083. if ( p_uniforms.boneTexture !== null ) {
  14084. var textureUnit = getTextureUnit();
  14085. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14086. _this.setTexture( object.boneTexture, textureUnit );
  14087. }
  14088. if ( p_uniforms.boneTextureWidth !== null ) {
  14089. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14090. }
  14091. if ( p_uniforms.boneTextureHeight !== null ) {
  14092. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14093. }
  14094. } else {
  14095. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14096. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14097. }
  14098. }
  14099. }
  14100. if ( refreshMaterial ) {
  14101. // refresh uniforms common to several materials
  14102. if ( fog && material.fog ) {
  14103. refreshUniformsFog( m_uniforms, fog );
  14104. }
  14105. if ( material instanceof THREE.MeshPhongMaterial ||
  14106. material instanceof THREE.MeshLambertMaterial ||
  14107. material.lights ) {
  14108. if ( _lightsNeedUpdate ) {
  14109. setupLights( program, lights );
  14110. _lightsNeedUpdate = false;
  14111. }
  14112. refreshUniformsLights( m_uniforms, _lights );
  14113. }
  14114. if ( material instanceof THREE.MeshBasicMaterial ||
  14115. material instanceof THREE.MeshLambertMaterial ||
  14116. material instanceof THREE.MeshPhongMaterial ) {
  14117. refreshUniformsCommon( m_uniforms, material );
  14118. }
  14119. // refresh single material specific uniforms
  14120. if ( material instanceof THREE.LineBasicMaterial ) {
  14121. refreshUniformsLine( m_uniforms, material );
  14122. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14123. refreshUniformsLine( m_uniforms, material );
  14124. refreshUniformsDash( m_uniforms, material );
  14125. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14126. refreshUniformsParticle( m_uniforms, material );
  14127. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14128. refreshUniformsPhong( m_uniforms, material );
  14129. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14130. refreshUniformsLambert( m_uniforms, material );
  14131. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14132. m_uniforms.mNear.value = camera.near;
  14133. m_uniforms.mFar.value = camera.far;
  14134. m_uniforms.opacity.value = material.opacity;
  14135. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14136. m_uniforms.opacity.value = material.opacity;
  14137. }
  14138. if ( object.receiveShadow && ! material._shadowPass ) {
  14139. refreshUniformsShadow( m_uniforms, lights );
  14140. }
  14141. // load common uniforms
  14142. loadUniformsGeneric( program, material.uniformsList );
  14143. // load material specific uniforms
  14144. // (shader material also gets them for the sake of genericity)
  14145. if ( material instanceof THREE.ShaderMaterial ||
  14146. material instanceof THREE.MeshPhongMaterial ||
  14147. material.envMap ) {
  14148. if ( p_uniforms.cameraPosition !== null ) {
  14149. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14150. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14151. }
  14152. }
  14153. if ( material instanceof THREE.MeshPhongMaterial ||
  14154. material instanceof THREE.MeshLambertMaterial ||
  14155. material instanceof THREE.ShaderMaterial ||
  14156. material.skinning ) {
  14157. if ( p_uniforms.viewMatrix !== null ) {
  14158. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14159. }
  14160. }
  14161. }
  14162. loadUniformsMatrices( p_uniforms, object );
  14163. if ( p_uniforms.modelMatrix !== null ) {
  14164. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14165. }
  14166. return program;
  14167. };
  14168. // Uniforms (refresh uniforms objects)
  14169. function refreshUniformsCommon ( uniforms, material ) {
  14170. uniforms.opacity.value = material.opacity;
  14171. if ( _this.gammaInput ) {
  14172. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14173. } else {
  14174. uniforms.diffuse.value = material.color;
  14175. }
  14176. uniforms.map.value = material.map;
  14177. uniforms.lightMap.value = material.lightMap;
  14178. uniforms.specularMap.value = material.specularMap;
  14179. if ( material.bumpMap ) {
  14180. uniforms.bumpMap.value = material.bumpMap;
  14181. uniforms.bumpScale.value = material.bumpScale;
  14182. }
  14183. if ( material.normalMap ) {
  14184. uniforms.normalMap.value = material.normalMap;
  14185. uniforms.normalScale.value.copy( material.normalScale );
  14186. }
  14187. // uv repeat and offset setting priorities
  14188. // 1. color map
  14189. // 2. specular map
  14190. // 3. normal map
  14191. // 4. bump map
  14192. var uvScaleMap;
  14193. if ( material.map ) {
  14194. uvScaleMap = material.map;
  14195. } else if ( material.specularMap ) {
  14196. uvScaleMap = material.specularMap;
  14197. } else if ( material.normalMap ) {
  14198. uvScaleMap = material.normalMap;
  14199. } else if ( material.bumpMap ) {
  14200. uvScaleMap = material.bumpMap;
  14201. }
  14202. if ( uvScaleMap !== undefined ) {
  14203. var offset = uvScaleMap.offset;
  14204. var repeat = uvScaleMap.repeat;
  14205. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14206. }
  14207. uniforms.envMap.value = material.envMap;
  14208. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14209. if ( _this.gammaInput ) {
  14210. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14211. uniforms.reflectivity.value = material.reflectivity;
  14212. } else {
  14213. uniforms.reflectivity.value = material.reflectivity;
  14214. }
  14215. uniforms.refractionRatio.value = material.refractionRatio;
  14216. uniforms.combine.value = material.combine;
  14217. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14218. };
  14219. function refreshUniformsLine ( uniforms, material ) {
  14220. uniforms.diffuse.value = material.color;
  14221. uniforms.opacity.value = material.opacity;
  14222. };
  14223. function refreshUniformsDash ( uniforms, material ) {
  14224. uniforms.dashSize.value = material.dashSize;
  14225. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14226. uniforms.scale.value = material.scale;
  14227. };
  14228. function refreshUniformsParticle ( uniforms, material ) {
  14229. uniforms.psColor.value = material.color;
  14230. uniforms.opacity.value = material.opacity;
  14231. uniforms.size.value = material.size;
  14232. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14233. uniforms.map.value = material.map;
  14234. };
  14235. function refreshUniformsFog ( uniforms, fog ) {
  14236. uniforms.fogColor.value = fog.color;
  14237. if ( fog instanceof THREE.Fog ) {
  14238. uniforms.fogNear.value = fog.near;
  14239. uniforms.fogFar.value = fog.far;
  14240. } else if ( fog instanceof THREE.FogExp2 ) {
  14241. uniforms.fogDensity.value = fog.density;
  14242. }
  14243. };
  14244. function refreshUniformsPhong ( uniforms, material ) {
  14245. uniforms.shininess.value = material.shininess;
  14246. if ( _this.gammaInput ) {
  14247. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14248. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14249. uniforms.specular.value.copyGammaToLinear( material.specular );
  14250. } else {
  14251. uniforms.ambient.value = material.ambient;
  14252. uniforms.emissive.value = material.emissive;
  14253. uniforms.specular.value = material.specular;
  14254. }
  14255. if ( material.wrapAround ) {
  14256. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14257. }
  14258. };
  14259. function refreshUniformsLambert ( uniforms, material ) {
  14260. if ( _this.gammaInput ) {
  14261. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14262. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14263. } else {
  14264. uniforms.ambient.value = material.ambient;
  14265. uniforms.emissive.value = material.emissive;
  14266. }
  14267. if ( material.wrapAround ) {
  14268. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14269. }
  14270. };
  14271. function refreshUniformsLights ( uniforms, lights ) {
  14272. uniforms.ambientLightColor.value = lights.ambient;
  14273. uniforms.directionalLightColor.value = lights.directional.colors;
  14274. uniforms.directionalLightDirection.value = lights.directional.positions;
  14275. uniforms.pointLightColor.value = lights.point.colors;
  14276. uniforms.pointLightPosition.value = lights.point.positions;
  14277. uniforms.pointLightDistance.value = lights.point.distances;
  14278. uniforms.spotLightColor.value = lights.spot.colors;
  14279. uniforms.spotLightPosition.value = lights.spot.positions;
  14280. uniforms.spotLightDistance.value = lights.spot.distances;
  14281. uniforms.spotLightDirection.value = lights.spot.directions;
  14282. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14283. uniforms.spotLightExponent.value = lights.spot.exponents;
  14284. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14285. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14286. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14287. };
  14288. function refreshUniformsShadow ( uniforms, lights ) {
  14289. if ( uniforms.shadowMatrix ) {
  14290. var j = 0;
  14291. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14292. var light = lights[ i ];
  14293. if ( ! light.castShadow ) continue;
  14294. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14295. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14296. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14297. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14298. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14299. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14300. j ++;
  14301. }
  14302. }
  14303. }
  14304. };
  14305. // Uniforms (load to GPU)
  14306. function loadUniformsMatrices ( uniforms, object ) {
  14307. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14308. if ( uniforms.normalMatrix ) {
  14309. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14310. }
  14311. };
  14312. function getTextureUnit() {
  14313. var textureUnit = _usedTextureUnits;
  14314. if ( textureUnit >= _maxTextures ) {
  14315. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14316. }
  14317. _usedTextureUnits += 1;
  14318. return textureUnit;
  14319. };
  14320. function loadUniformsGeneric ( program, uniforms ) {
  14321. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14322. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14323. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14324. if ( !location ) continue;
  14325. uniform = uniforms[ j ][ 0 ];
  14326. type = uniform.type;
  14327. value = uniform.value;
  14328. if ( type === "i" ) { // single integer
  14329. _gl.uniform1i( location, value );
  14330. } else if ( type === "f" ) { // single float
  14331. _gl.uniform1f( location, value );
  14332. } else if ( type === "v2" ) { // single THREE.Vector2
  14333. _gl.uniform2f( location, value.x, value.y );
  14334. } else if ( type === "v3" ) { // single THREE.Vector3
  14335. _gl.uniform3f( location, value.x, value.y, value.z );
  14336. } else if ( type === "v4" ) { // single THREE.Vector4
  14337. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14338. } else if ( type === "c" ) { // single THREE.Color
  14339. _gl.uniform3f( location, value.r, value.g, value.b );
  14340. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14341. _gl.uniform1iv( location, value );
  14342. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14343. _gl.uniform3iv( location, value );
  14344. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14345. _gl.uniform1fv( location, value );
  14346. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14347. _gl.uniform3fv( location, value );
  14348. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14349. if ( uniform._array === undefined ) {
  14350. uniform._array = new Float32Array( 2 * value.length );
  14351. }
  14352. for ( i = 0, il = value.length; i < il; i ++ ) {
  14353. offset = i * 2;
  14354. uniform._array[ offset ] = value[ i ].x;
  14355. uniform._array[ offset + 1 ] = value[ i ].y;
  14356. }
  14357. _gl.uniform2fv( location, uniform._array );
  14358. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14359. if ( uniform._array === undefined ) {
  14360. uniform._array = new Float32Array( 3 * value.length );
  14361. }
  14362. for ( i = 0, il = value.length; i < il; i ++ ) {
  14363. offset = i * 3;
  14364. uniform._array[ offset ] = value[ i ].x;
  14365. uniform._array[ offset + 1 ] = value[ i ].y;
  14366. uniform._array[ offset + 2 ] = value[ i ].z;
  14367. }
  14368. _gl.uniform3fv( location, uniform._array );
  14369. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14370. if ( uniform._array === undefined ) {
  14371. uniform._array = new Float32Array( 4 * value.length );
  14372. }
  14373. for ( i = 0, il = value.length; i < il; i ++ ) {
  14374. offset = i * 4;
  14375. uniform._array[ offset ] = value[ i ].x;
  14376. uniform._array[ offset + 1 ] = value[ i ].y;
  14377. uniform._array[ offset + 2 ] = value[ i ].z;
  14378. uniform._array[ offset + 3 ] = value[ i ].w;
  14379. }
  14380. _gl.uniform4fv( location, uniform._array );
  14381. } else if ( type === "m4") { // single THREE.Matrix4
  14382. if ( uniform._array === undefined ) {
  14383. uniform._array = new Float32Array( 16 );
  14384. }
  14385. value.flattenToArray( uniform._array );
  14386. _gl.uniformMatrix4fv( location, false, uniform._array );
  14387. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14388. if ( uniform._array === undefined ) {
  14389. uniform._array = new Float32Array( 16 * value.length );
  14390. }
  14391. for ( i = 0, il = value.length; i < il; i ++ ) {
  14392. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14393. }
  14394. _gl.uniformMatrix4fv( location, false, uniform._array );
  14395. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14396. texture = value;
  14397. textureUnit = getTextureUnit();
  14398. _gl.uniform1i( location, textureUnit );
  14399. if ( !texture ) continue;
  14400. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14401. setCubeTexture( texture, textureUnit );
  14402. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14403. setCubeTextureDynamic( texture, textureUnit );
  14404. } else {
  14405. _this.setTexture( texture, textureUnit );
  14406. }
  14407. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14408. if ( uniform._array === undefined ) {
  14409. uniform._array = [];
  14410. }
  14411. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14412. uniform._array[ i ] = getTextureUnit();
  14413. }
  14414. _gl.uniform1iv( location, uniform._array );
  14415. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14416. texture = uniform.value[ i ];
  14417. textureUnit = uniform._array[ i ];
  14418. if ( !texture ) continue;
  14419. _this.setTexture( texture, textureUnit );
  14420. }
  14421. } else {
  14422. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14423. }
  14424. }
  14425. };
  14426. function setupMatrices ( object, camera ) {
  14427. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14428. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14429. };
  14430. //
  14431. function setColorGamma( array, offset, color, intensitySq ) {
  14432. array[ offset ] = color.r * color.r * intensitySq;
  14433. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14434. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14435. };
  14436. function setColorLinear( array, offset, color, intensity ) {
  14437. array[ offset ] = color.r * intensity;
  14438. array[ offset + 1 ] = color.g * intensity;
  14439. array[ offset + 2 ] = color.b * intensity;
  14440. };
  14441. function setupLights ( program, lights ) {
  14442. var l, ll, light, n,
  14443. r = 0, g = 0, b = 0,
  14444. color, skyColor, groundColor,
  14445. intensity, intensitySq,
  14446. position,
  14447. distance,
  14448. zlights = _lights,
  14449. dirColors = zlights.directional.colors,
  14450. dirPositions = zlights.directional.positions,
  14451. pointColors = zlights.point.colors,
  14452. pointPositions = zlights.point.positions,
  14453. pointDistances = zlights.point.distances,
  14454. spotColors = zlights.spot.colors,
  14455. spotPositions = zlights.spot.positions,
  14456. spotDistances = zlights.spot.distances,
  14457. spotDirections = zlights.spot.directions,
  14458. spotAnglesCos = zlights.spot.anglesCos,
  14459. spotExponents = zlights.spot.exponents,
  14460. hemiSkyColors = zlights.hemi.skyColors,
  14461. hemiGroundColors = zlights.hemi.groundColors,
  14462. hemiPositions = zlights.hemi.positions,
  14463. dirLength = 0,
  14464. pointLength = 0,
  14465. spotLength = 0,
  14466. hemiLength = 0,
  14467. dirCount = 0,
  14468. pointCount = 0,
  14469. spotCount = 0,
  14470. hemiCount = 0,
  14471. dirOffset = 0,
  14472. pointOffset = 0,
  14473. spotOffset = 0,
  14474. hemiOffset = 0;
  14475. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14476. light = lights[ l ];
  14477. if ( light.onlyShadow ) continue;
  14478. color = light.color;
  14479. intensity = light.intensity;
  14480. distance = light.distance;
  14481. if ( light instanceof THREE.AmbientLight ) {
  14482. if ( ! light.visible ) continue;
  14483. if ( _this.gammaInput ) {
  14484. r += color.r * color.r;
  14485. g += color.g * color.g;
  14486. b += color.b * color.b;
  14487. } else {
  14488. r += color.r;
  14489. g += color.g;
  14490. b += color.b;
  14491. }
  14492. } else if ( light instanceof THREE.DirectionalLight ) {
  14493. dirCount += 1;
  14494. if ( ! light.visible ) continue;
  14495. _direction.setFromMatrixPosition( light.matrixWorld );
  14496. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14497. _direction.sub( _vector3 );
  14498. _direction.normalize();
  14499. // skip lights with undefined direction
  14500. // these create troubles in OpenGL (making pixel black)
  14501. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14502. dirOffset = dirLength * 3;
  14503. dirPositions[ dirOffset ] = _direction.x;
  14504. dirPositions[ dirOffset + 1 ] = _direction.y;
  14505. dirPositions[ dirOffset + 2 ] = _direction.z;
  14506. if ( _this.gammaInput ) {
  14507. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14508. } else {
  14509. setColorLinear( dirColors, dirOffset, color, intensity );
  14510. }
  14511. dirLength += 1;
  14512. } else if ( light instanceof THREE.PointLight ) {
  14513. pointCount += 1;
  14514. if ( ! light.visible ) continue;
  14515. pointOffset = pointLength * 3;
  14516. if ( _this.gammaInput ) {
  14517. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14518. } else {
  14519. setColorLinear( pointColors, pointOffset, color, intensity );
  14520. }
  14521. _vector3.setFromMatrixPosition( light.matrixWorld );
  14522. pointPositions[ pointOffset ] = _vector3.x;
  14523. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14524. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14525. pointDistances[ pointLength ] = distance;
  14526. pointLength += 1;
  14527. } else if ( light instanceof THREE.SpotLight ) {
  14528. spotCount += 1;
  14529. if ( ! light.visible ) continue;
  14530. spotOffset = spotLength * 3;
  14531. if ( _this.gammaInput ) {
  14532. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14533. } else {
  14534. setColorLinear( spotColors, spotOffset, color, intensity );
  14535. }
  14536. _vector3.setFromMatrixPosition( light.matrixWorld );
  14537. spotPositions[ spotOffset ] = _vector3.x;
  14538. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14539. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14540. spotDistances[ spotLength ] = distance;
  14541. _direction.copy( _vector3 );
  14542. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14543. _direction.sub( _vector3 );
  14544. _direction.normalize();
  14545. spotDirections[ spotOffset ] = _direction.x;
  14546. spotDirections[ spotOffset + 1 ] = _direction.y;
  14547. spotDirections[ spotOffset + 2 ] = _direction.z;
  14548. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14549. spotExponents[ spotLength ] = light.exponent;
  14550. spotLength += 1;
  14551. } else if ( light instanceof THREE.HemisphereLight ) {
  14552. hemiCount += 1;
  14553. if ( ! light.visible ) continue;
  14554. _direction.setFromMatrixPosition( light.matrixWorld );
  14555. _direction.normalize();
  14556. // skip lights with undefined direction
  14557. // these create troubles in OpenGL (making pixel black)
  14558. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14559. hemiOffset = hemiLength * 3;
  14560. hemiPositions[ hemiOffset ] = _direction.x;
  14561. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14562. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14563. skyColor = light.color;
  14564. groundColor = light.groundColor;
  14565. if ( _this.gammaInput ) {
  14566. intensitySq = intensity * intensity;
  14567. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14568. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14569. } else {
  14570. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14571. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14572. }
  14573. hemiLength += 1;
  14574. }
  14575. }
  14576. // null eventual remains from removed lights
  14577. // (this is to avoid if in shader)
  14578. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14579. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14580. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14581. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14582. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14583. zlights.directional.length = dirLength;
  14584. zlights.point.length = pointLength;
  14585. zlights.spot.length = spotLength;
  14586. zlights.hemi.length = hemiLength;
  14587. zlights.ambient[ 0 ] = r;
  14588. zlights.ambient[ 1 ] = g;
  14589. zlights.ambient[ 2 ] = b;
  14590. };
  14591. // GL state setting
  14592. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14593. if ( cullFace === THREE.CullFaceNone ) {
  14594. _gl.disable( _gl.CULL_FACE );
  14595. } else {
  14596. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14597. _gl.frontFace( _gl.CW );
  14598. } else {
  14599. _gl.frontFace( _gl.CCW );
  14600. }
  14601. if ( cullFace === THREE.CullFaceBack ) {
  14602. _gl.cullFace( _gl.BACK );
  14603. } else if ( cullFace === THREE.CullFaceFront ) {
  14604. _gl.cullFace( _gl.FRONT );
  14605. } else {
  14606. _gl.cullFace( _gl.FRONT_AND_BACK );
  14607. }
  14608. _gl.enable( _gl.CULL_FACE );
  14609. }
  14610. };
  14611. this.setMaterialFaces = function ( material ) {
  14612. var doubleSided = material.side === THREE.DoubleSide;
  14613. var flipSided = material.side === THREE.BackSide;
  14614. if ( _oldDoubleSided !== doubleSided ) {
  14615. if ( doubleSided ) {
  14616. _gl.disable( _gl.CULL_FACE );
  14617. } else {
  14618. _gl.enable( _gl.CULL_FACE );
  14619. }
  14620. _oldDoubleSided = doubleSided;
  14621. }
  14622. if ( _oldFlipSided !== flipSided ) {
  14623. if ( flipSided ) {
  14624. _gl.frontFace( _gl.CW );
  14625. } else {
  14626. _gl.frontFace( _gl.CCW );
  14627. }
  14628. _oldFlipSided = flipSided;
  14629. }
  14630. };
  14631. this.setDepthTest = function ( depthTest ) {
  14632. if ( _oldDepthTest !== depthTest ) {
  14633. if ( depthTest ) {
  14634. _gl.enable( _gl.DEPTH_TEST );
  14635. } else {
  14636. _gl.disable( _gl.DEPTH_TEST );
  14637. }
  14638. _oldDepthTest = depthTest;
  14639. }
  14640. };
  14641. this.setDepthWrite = function ( depthWrite ) {
  14642. if ( _oldDepthWrite !== depthWrite ) {
  14643. _gl.depthMask( depthWrite );
  14644. _oldDepthWrite = depthWrite;
  14645. }
  14646. };
  14647. function setLineWidth ( width ) {
  14648. if ( width !== _oldLineWidth ) {
  14649. _gl.lineWidth( width );
  14650. _oldLineWidth = width;
  14651. }
  14652. };
  14653. function setPolygonOffset ( polygonoffset, factor, units ) {
  14654. if ( _oldPolygonOffset !== polygonoffset ) {
  14655. if ( polygonoffset ) {
  14656. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14657. } else {
  14658. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14659. }
  14660. _oldPolygonOffset = polygonoffset;
  14661. }
  14662. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14663. _gl.polygonOffset( factor, units );
  14664. _oldPolygonOffsetFactor = factor;
  14665. _oldPolygonOffsetUnits = units;
  14666. }
  14667. };
  14668. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14669. if ( blending !== _oldBlending ) {
  14670. if ( blending === THREE.NoBlending ) {
  14671. _gl.disable( _gl.BLEND );
  14672. } else if ( blending === THREE.AdditiveBlending ) {
  14673. _gl.enable( _gl.BLEND );
  14674. _gl.blendEquation( _gl.FUNC_ADD );
  14675. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14676. } else if ( blending === THREE.SubtractiveBlending ) {
  14677. // TODO: Find blendFuncSeparate() combination
  14678. _gl.enable( _gl.BLEND );
  14679. _gl.blendEquation( _gl.FUNC_ADD );
  14680. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14681. } else if ( blending === THREE.MultiplyBlending ) {
  14682. // TODO: Find blendFuncSeparate() combination
  14683. _gl.enable( _gl.BLEND );
  14684. _gl.blendEquation( _gl.FUNC_ADD );
  14685. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14686. } else if ( blending === THREE.CustomBlending ) {
  14687. _gl.enable( _gl.BLEND );
  14688. } else {
  14689. _gl.enable( _gl.BLEND );
  14690. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14691. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14692. }
  14693. _oldBlending = blending;
  14694. }
  14695. if ( blending === THREE.CustomBlending ) {
  14696. if ( blendEquation !== _oldBlendEquation ) {
  14697. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14698. _oldBlendEquation = blendEquation;
  14699. }
  14700. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14701. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14702. _oldBlendSrc = blendSrc;
  14703. _oldBlendDst = blendDst;
  14704. }
  14705. } else {
  14706. _oldBlendEquation = null;
  14707. _oldBlendSrc = null;
  14708. _oldBlendDst = null;
  14709. }
  14710. };
  14711. // Defines
  14712. function generateDefines ( defines ) {
  14713. var value, chunk, chunks = [];
  14714. for ( var d in defines ) {
  14715. value = defines[ d ];
  14716. if ( value === false ) continue;
  14717. chunk = "#define " + d + " " + value;
  14718. chunks.push( chunk );
  14719. }
  14720. return chunks.join( "\n" );
  14721. };
  14722. // Shaders
  14723. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  14724. var p, pl, d, program, code;
  14725. var chunks = [];
  14726. // Generate code
  14727. if ( shaderID ) {
  14728. chunks.push( shaderID );
  14729. } else {
  14730. chunks.push( fragmentShader );
  14731. chunks.push( vertexShader );
  14732. }
  14733. for ( d in defines ) {
  14734. chunks.push( d );
  14735. chunks.push( defines[ d ] );
  14736. }
  14737. for ( p in parameters ) {
  14738. chunks.push( p );
  14739. chunks.push( parameters[ p ] );
  14740. }
  14741. code = chunks.join();
  14742. // Check if code has been already compiled
  14743. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14744. var programInfo = _programs[ p ];
  14745. if ( programInfo.code === code ) {
  14746. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14747. programInfo.usedTimes ++;
  14748. return programInfo.program;
  14749. }
  14750. }
  14751. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14752. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14753. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14754. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14755. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14756. }
  14757. // console.log( "building new program " );
  14758. //
  14759. var customDefines = generateDefines( defines );
  14760. //
  14761. program = _gl.createProgram();
  14762. var prefix_vertex = [
  14763. "precision " + _precision + " float;",
  14764. "precision " + _precision + " int;",
  14765. customDefines,
  14766. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14767. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14768. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14769. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14770. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14771. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14772. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14773. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14774. "#define MAX_SHADOWS " + parameters.maxShadows,
  14775. "#define MAX_BONES " + parameters.maxBones,
  14776. parameters.map ? "#define USE_MAP" : "",
  14777. parameters.envMap ? "#define USE_ENVMAP" : "",
  14778. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14779. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14780. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14781. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14782. parameters.vertexColors ? "#define USE_COLOR" : "",
  14783. parameters.skinning ? "#define USE_SKINNING" : "",
  14784. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14785. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14786. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14787. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14788. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14789. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14790. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14791. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14792. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14793. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14794. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14795. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14796. "uniform mat4 modelMatrix;",
  14797. "uniform mat4 modelViewMatrix;",
  14798. "uniform mat4 projectionMatrix;",
  14799. "uniform mat4 viewMatrix;",
  14800. "uniform mat3 normalMatrix;",
  14801. "uniform vec3 cameraPosition;",
  14802. "attribute vec3 position;",
  14803. "attribute vec3 normal;",
  14804. "attribute vec2 uv;",
  14805. "attribute vec2 uv2;",
  14806. "#ifdef USE_COLOR",
  14807. "attribute vec3 color;",
  14808. "#endif",
  14809. "#ifdef USE_MORPHTARGETS",
  14810. "attribute vec3 morphTarget0;",
  14811. "attribute vec3 morphTarget1;",
  14812. "attribute vec3 morphTarget2;",
  14813. "attribute vec3 morphTarget3;",
  14814. "#ifdef USE_MORPHNORMALS",
  14815. "attribute vec3 morphNormal0;",
  14816. "attribute vec3 morphNormal1;",
  14817. "attribute vec3 morphNormal2;",
  14818. "attribute vec3 morphNormal3;",
  14819. "#else",
  14820. "attribute vec3 morphTarget4;",
  14821. "attribute vec3 morphTarget5;",
  14822. "attribute vec3 morphTarget6;",
  14823. "attribute vec3 morphTarget7;",
  14824. "#endif",
  14825. "#endif",
  14826. "#ifdef USE_SKINNING",
  14827. "attribute vec4 skinIndex;",
  14828. "attribute vec4 skinWeight;",
  14829. "#endif",
  14830. ""
  14831. ].join("\n");
  14832. var prefix_fragment = [
  14833. "precision " + _precision + " float;",
  14834. "precision " + _precision + " int;",
  14835. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14836. customDefines,
  14837. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14838. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14839. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14840. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14841. "#define MAX_SHADOWS " + parameters.maxShadows,
  14842. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14843. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14844. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14845. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14846. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14847. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14848. parameters.map ? "#define USE_MAP" : "",
  14849. parameters.envMap ? "#define USE_ENVMAP" : "",
  14850. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14851. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14852. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14853. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14854. parameters.vertexColors ? "#define USE_COLOR" : "",
  14855. parameters.metal ? "#define METAL" : "",
  14856. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14857. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14858. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14859. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14860. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14861. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14862. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14863. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14864. "uniform mat4 viewMatrix;",
  14865. "uniform vec3 cameraPosition;",
  14866. ""
  14867. ].join("\n");
  14868. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14869. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14870. _gl.attachShader( program, glVertexShader );
  14871. _gl.attachShader( program, glFragmentShader );
  14872. //Force a particular attribute to index 0.
  14873. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  14874. //And, color, for example is often automatically bound to index 0 so disabling it
  14875. if ( index0AttributeName ) {
  14876. _gl.bindAttribLocation( program, 0, index0AttributeName );
  14877. }
  14878. _gl.linkProgram( program );
  14879. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14880. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14881. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  14882. }
  14883. // clean up
  14884. _gl.deleteShader( glFragmentShader );
  14885. _gl.deleteShader( glVertexShader );
  14886. // console.log( prefix_fragment + fragmentShader );
  14887. // console.log( prefix_vertex + vertexShader );
  14888. program.uniforms = {};
  14889. program.attributes = {};
  14890. var identifiers, u, a, i;
  14891. // cache uniform locations
  14892. identifiers = [
  14893. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14894. 'morphTargetInfluences'
  14895. ];
  14896. if ( parameters.useVertexTexture ) {
  14897. identifiers.push( 'boneTexture' );
  14898. identifiers.push( 'boneTextureWidth' );
  14899. identifiers.push( 'boneTextureHeight' );
  14900. } else {
  14901. identifiers.push( 'boneGlobalMatrices' );
  14902. }
  14903. for ( u in uniforms ) {
  14904. identifiers.push( u );
  14905. }
  14906. cacheUniformLocations( program, identifiers );
  14907. // cache attributes locations
  14908. identifiers = [
  14909. "position", "normal", "uv", "uv2", "tangent", "color",
  14910. "skinIndex", "skinWeight", "lineDistance"
  14911. ];
  14912. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14913. identifiers.push( "morphTarget" + i );
  14914. }
  14915. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14916. identifiers.push( "morphNormal" + i );
  14917. }
  14918. for ( a in attributes ) {
  14919. identifiers.push( a );
  14920. }
  14921. cacheAttributeLocations( program, identifiers );
  14922. program.id = _programs_counter ++;
  14923. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14924. _this.info.memory.programs = _programs.length;
  14925. return program;
  14926. };
  14927. // Shader parameters cache
  14928. function cacheUniformLocations ( program, identifiers ) {
  14929. var i, l, id;
  14930. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14931. id = identifiers[ i ];
  14932. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14933. }
  14934. };
  14935. function cacheAttributeLocations ( program, identifiers ) {
  14936. var i, l, id;
  14937. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14938. id = identifiers[ i ];
  14939. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14940. }
  14941. };
  14942. function addLineNumbers ( string ) {
  14943. var chunks = string.split( "\n" );
  14944. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14945. // Chrome reports shader errors on lines
  14946. // starting counting from 1
  14947. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14948. }
  14949. return chunks.join( "\n" );
  14950. };
  14951. function getShader ( type, string ) {
  14952. var shader;
  14953. if ( type === "fragment" ) {
  14954. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14955. } else if ( type === "vertex" ) {
  14956. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14957. }
  14958. _gl.shaderSource( shader, string );
  14959. _gl.compileShader( shader );
  14960. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14961. console.error( _gl.getShaderInfoLog( shader ) );
  14962. console.error( addLineNumbers( string ) );
  14963. return null;
  14964. }
  14965. return shader;
  14966. };
  14967. // Textures
  14968. function isPowerOfTwo ( value ) {
  14969. return ( value & ( value - 1 ) ) === 0;
  14970. };
  14971. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14972. if ( isImagePowerOfTwo ) {
  14973. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14974. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14975. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14976. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14977. } else {
  14978. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14979. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14980. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14981. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14982. }
  14983. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14984. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14985. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14986. texture.__oldAnisotropy = texture.anisotropy;
  14987. }
  14988. }
  14989. };
  14990. this.setTexture = function ( texture, slot ) {
  14991. if ( texture.needsUpdate ) {
  14992. if ( ! texture.__webglInit ) {
  14993. texture.__webglInit = true;
  14994. texture.addEventListener( 'dispose', onTextureDispose );
  14995. texture.__webglTexture = _gl.createTexture();
  14996. _this.info.memory.textures ++;
  14997. }
  14998. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14999. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15000. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15001. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15002. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15003. var image = texture.image,
  15004. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15005. glFormat = paramThreeToGL( texture.format ),
  15006. glType = paramThreeToGL( texture.type );
  15007. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15008. var mipmap, mipmaps = texture.mipmaps;
  15009. if ( texture instanceof THREE.DataTexture ) {
  15010. // use manually created mipmaps if available
  15011. // if there are no manual mipmaps
  15012. // set 0 level mipmap and then use GL to generate other mipmap levels
  15013. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15014. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15015. mipmap = mipmaps[ i ];
  15016. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15017. }
  15018. texture.generateMipmaps = false;
  15019. } else {
  15020. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15021. }
  15022. } else if ( texture instanceof THREE.CompressedTexture ) {
  15023. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15024. mipmap = mipmaps[ i ];
  15025. if ( texture.format!==THREE.RGBAFormat ) {
  15026. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15027. } else {
  15028. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15029. }
  15030. }
  15031. } else { // regular Texture (image, video, canvas)
  15032. // use manually created mipmaps if available
  15033. // if there are no manual mipmaps
  15034. // set 0 level mipmap and then use GL to generate other mipmap levels
  15035. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15036. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15037. mipmap = mipmaps[ i ];
  15038. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15039. }
  15040. texture.generateMipmaps = false;
  15041. } else {
  15042. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15043. }
  15044. }
  15045. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15046. texture.needsUpdate = false;
  15047. if ( texture.onUpdate ) texture.onUpdate();
  15048. } else {
  15049. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15050. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15051. }
  15052. };
  15053. function clampToMaxSize ( image, maxSize ) {
  15054. if ( image.width <= maxSize && image.height <= maxSize ) {
  15055. return image;
  15056. }
  15057. // Warning: Scaling through the canvas will only work with images that use
  15058. // premultiplied alpha.
  15059. var maxDimension = Math.max( image.width, image.height );
  15060. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15061. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15062. var canvas = document.createElement( 'canvas' );
  15063. canvas.width = newWidth;
  15064. canvas.height = newHeight;
  15065. var ctx = canvas.getContext( "2d" );
  15066. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15067. return canvas;
  15068. }
  15069. function setCubeTexture ( texture, slot ) {
  15070. if ( texture.image.length === 6 ) {
  15071. if ( texture.needsUpdate ) {
  15072. if ( ! texture.image.__webglTextureCube ) {
  15073. texture.addEventListener( 'dispose', onTextureDispose );
  15074. texture.image.__webglTextureCube = _gl.createTexture();
  15075. _this.info.memory.textures ++;
  15076. }
  15077. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15078. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15079. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15080. var isCompressed = texture instanceof THREE.CompressedTexture;
  15081. var cubeImage = [];
  15082. for ( var i = 0; i < 6; i ++ ) {
  15083. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15084. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15085. } else {
  15086. cubeImage[ i ] = texture.image[ i ];
  15087. }
  15088. }
  15089. var image = cubeImage[ 0 ],
  15090. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15091. glFormat = paramThreeToGL( texture.format ),
  15092. glType = paramThreeToGL( texture.type );
  15093. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15094. for ( var i = 0; i < 6; i ++ ) {
  15095. if( !isCompressed ) {
  15096. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15097. } else {
  15098. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15099. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15100. mipmap = mipmaps[ j ];
  15101. if ( texture.format!==THREE.RGBAFormat ) {
  15102. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15103. } else {
  15104. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15105. }
  15106. }
  15107. }
  15108. }
  15109. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15110. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15111. }
  15112. texture.needsUpdate = false;
  15113. if ( texture.onUpdate ) texture.onUpdate();
  15114. } else {
  15115. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15116. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15117. }
  15118. }
  15119. };
  15120. function setCubeTextureDynamic ( texture, slot ) {
  15121. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15122. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15123. };
  15124. // Render targets
  15125. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15126. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15127. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15128. };
  15129. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15130. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15131. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15132. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15133. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15134. /* For some reason this is not working. Defaulting to RGBA4.
  15135. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15136. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15137. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15138. */
  15139. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15140. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15141. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15142. } else {
  15143. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15144. }
  15145. };
  15146. this.setRenderTarget = function ( renderTarget ) {
  15147. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15148. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15149. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15150. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15151. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15152. renderTarget.__webglTexture = _gl.createTexture();
  15153. _this.info.memory.textures ++;
  15154. // Setup texture, create render and frame buffers
  15155. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15156. glFormat = paramThreeToGL( renderTarget.format ),
  15157. glType = paramThreeToGL( renderTarget.type );
  15158. if ( isCube ) {
  15159. renderTarget.__webglFramebuffer = [];
  15160. renderTarget.__webglRenderbuffer = [];
  15161. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15162. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15163. for ( var i = 0; i < 6; i ++ ) {
  15164. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15165. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15166. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15167. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15168. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15169. }
  15170. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15171. } else {
  15172. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15173. if ( renderTarget.shareDepthFrom ) {
  15174. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15175. } else {
  15176. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15177. }
  15178. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15179. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15180. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15181. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15182. if ( renderTarget.shareDepthFrom ) {
  15183. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15184. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15185. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15186. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15187. }
  15188. } else {
  15189. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15190. }
  15191. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15192. }
  15193. // Release everything
  15194. if ( isCube ) {
  15195. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15196. } else {
  15197. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15198. }
  15199. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15200. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15201. }
  15202. var framebuffer, width, height, vx, vy;
  15203. if ( renderTarget ) {
  15204. if ( isCube ) {
  15205. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15206. } else {
  15207. framebuffer = renderTarget.__webglFramebuffer;
  15208. }
  15209. width = renderTarget.width;
  15210. height = renderTarget.height;
  15211. vx = 0;
  15212. vy = 0;
  15213. } else {
  15214. framebuffer = null;
  15215. width = _viewportWidth;
  15216. height = _viewportHeight;
  15217. vx = _viewportX;
  15218. vy = _viewportY;
  15219. }
  15220. if ( framebuffer !== _currentFramebuffer ) {
  15221. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15222. _gl.viewport( vx, vy, width, height );
  15223. _currentFramebuffer = framebuffer;
  15224. }
  15225. _currentWidth = width;
  15226. _currentHeight = height;
  15227. };
  15228. function updateRenderTargetMipmap ( renderTarget ) {
  15229. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15230. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15231. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15232. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15233. } else {
  15234. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15235. _gl.generateMipmap( _gl.TEXTURE_2D );
  15236. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15237. }
  15238. };
  15239. // Fallback filters for non-power-of-2 textures
  15240. function filterFallback ( f ) {
  15241. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15242. return _gl.NEAREST;
  15243. }
  15244. return _gl.LINEAR;
  15245. };
  15246. // Map three.js constants to WebGL constants
  15247. function paramThreeToGL ( p ) {
  15248. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15249. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15250. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15251. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15252. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15253. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15254. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15255. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15256. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15257. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15258. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15259. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15260. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15261. if ( p === THREE.ByteType ) return _gl.BYTE;
  15262. if ( p === THREE.ShortType ) return _gl.SHORT;
  15263. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15264. if ( p === THREE.IntType ) return _gl.INT;
  15265. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15266. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15267. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15268. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15269. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15270. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15271. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15272. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15273. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15274. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15275. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15276. if ( p === THREE.OneFactor ) return _gl.ONE;
  15277. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15278. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15279. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15280. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15281. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15282. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15283. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15284. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15285. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15286. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15287. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15288. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15289. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15290. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15291. }
  15292. return 0;
  15293. };
  15294. // Allocations
  15295. function allocateBones ( object ) {
  15296. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15297. return 1024;
  15298. } else {
  15299. // default for when object is not specified
  15300. // ( for example when prebuilding shader
  15301. // to be used with multiple objects )
  15302. //
  15303. // - leave some extra space for other uniforms
  15304. // - limit here is ANGLE's 254 max uniform vectors
  15305. // (up to 54 should be safe)
  15306. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15307. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15308. var maxBones = nVertexMatrices;
  15309. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15310. maxBones = Math.min( object.bones.length, maxBones );
  15311. if ( maxBones < object.bones.length ) {
  15312. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15313. }
  15314. }
  15315. return maxBones;
  15316. }
  15317. };
  15318. function allocateLights( lights ) {
  15319. var dirLights = 0;
  15320. var pointLights = 0;
  15321. var spotLights = 0;
  15322. var hemiLights = 0;
  15323. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15324. var light = lights[ l ];
  15325. if ( light.onlyShadow ) continue;
  15326. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15327. if ( light instanceof THREE.PointLight ) pointLights ++;
  15328. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15329. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15330. }
  15331. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15332. };
  15333. function allocateShadows( lights ) {
  15334. var maxShadows = 0;
  15335. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15336. var light = lights[ l ];
  15337. if ( ! light.castShadow ) continue;
  15338. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15339. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15340. }
  15341. return maxShadows;
  15342. };
  15343. // Initialization
  15344. function initGL() {
  15345. try {
  15346. var attributes = {
  15347. alpha: _alpha,
  15348. premultipliedAlpha: _premultipliedAlpha,
  15349. antialias: _antialias,
  15350. stencil: _stencil,
  15351. preserveDrawingBuffer: _preserveDrawingBuffer
  15352. };
  15353. _gl = _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15354. if ( _gl === null ) {
  15355. throw 'Error creating WebGL context.';
  15356. }
  15357. } catch ( error ) {
  15358. console.error( error );
  15359. }
  15360. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15361. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15362. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15363. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15364. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15365. if ( ! _glExtensionTextureFloat ) {
  15366. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15367. }
  15368. if ( ! _glExtensionStandardDerivatives ) {
  15369. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15370. }
  15371. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15372. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15373. }
  15374. if ( ! _glExtensionCompressedTextureS3TC ) {
  15375. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15376. }
  15377. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15378. _gl.getShaderPrecisionFormat = function() {
  15379. return {
  15380. "rangeMin" : 1,
  15381. "rangeMax" : 1,
  15382. "precision" : 1
  15383. };
  15384. }
  15385. }
  15386. };
  15387. function setDefaultGLState () {
  15388. _gl.clearColor( 0, 0, 0, 1 );
  15389. _gl.clearDepth( 1 );
  15390. _gl.clearStencil( 0 );
  15391. _gl.enable( _gl.DEPTH_TEST );
  15392. _gl.depthFunc( _gl.LEQUAL );
  15393. _gl.frontFace( _gl.CCW );
  15394. _gl.cullFace( _gl.BACK );
  15395. _gl.enable( _gl.CULL_FACE );
  15396. _gl.enable( _gl.BLEND );
  15397. _gl.blendEquation( _gl.FUNC_ADD );
  15398. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15399. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15400. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15401. };
  15402. // default plugins (order is important)
  15403. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15404. this.addPrePlugin( this.shadowMapPlugin );
  15405. this.addPostPlugin( new THREE.SpritePlugin() );
  15406. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15407. };
  15408. /**
  15409. * @author szimek / https://github.com/szimek/
  15410. * @author alteredq / http://alteredqualia.com/
  15411. */
  15412. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15413. this.width = width;
  15414. this.height = height;
  15415. options = options || {};
  15416. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15417. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15418. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15419. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15420. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15421. this.offset = new THREE.Vector2( 0, 0 );
  15422. this.repeat = new THREE.Vector2( 1, 1 );
  15423. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15424. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15425. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15426. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15427. this.generateMipmaps = true;
  15428. this.shareDepthFrom = null;
  15429. };
  15430. THREE.WebGLRenderTarget.prototype = {
  15431. constructor: THREE.WebGLRenderTarget,
  15432. clone: function () {
  15433. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15434. tmp.wrapS = this.wrapS;
  15435. tmp.wrapT = this.wrapT;
  15436. tmp.magFilter = this.magFilter;
  15437. tmp.minFilter = this.minFilter;
  15438. tmp.anisotropy = this.anisotropy;
  15439. tmp.offset.copy( this.offset );
  15440. tmp.repeat.copy( this.repeat );
  15441. tmp.format = this.format;
  15442. tmp.type = this.type;
  15443. tmp.depthBuffer = this.depthBuffer;
  15444. tmp.stencilBuffer = this.stencilBuffer;
  15445. tmp.generateMipmaps = this.generateMipmaps;
  15446. tmp.shareDepthFrom = this.shareDepthFrom;
  15447. return tmp;
  15448. },
  15449. dispose: function () {
  15450. this.dispatchEvent( { type: 'dispose' } );
  15451. }
  15452. };
  15453. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15454. /**
  15455. * @author alteredq / http://alteredqualia.com
  15456. */
  15457. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15458. THREE.WebGLRenderTarget.call( this, width, height, options );
  15459. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15460. };
  15461. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15462. /**
  15463. * @author mrdoob / http://mrdoob.com/
  15464. */
  15465. THREE.RenderableVertex = function () {
  15466. this.positionWorld = new THREE.Vector3();
  15467. this.positionScreen = new THREE.Vector4();
  15468. this.visible = true;
  15469. };
  15470. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15471. this.positionWorld.copy( vertex.positionWorld );
  15472. this.positionScreen.copy( vertex.positionScreen );
  15473. };
  15474. /**
  15475. * @author mrdoob / http://mrdoob.com/
  15476. */
  15477. THREE.RenderableFace3 = function () {
  15478. this.id = 0;
  15479. this.v1 = new THREE.RenderableVertex();
  15480. this.v2 = new THREE.RenderableVertex();
  15481. this.v3 = new THREE.RenderableVertex();
  15482. this.centroidModel = new THREE.Vector3();
  15483. this.normalModel = new THREE.Vector3();
  15484. this.normalModelView = new THREE.Vector3();
  15485. this.vertexNormalsLength = 0;
  15486. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15487. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15488. this.color = null;
  15489. this.material = null;
  15490. this.uvs = [[]];
  15491. this.z = 0;
  15492. };
  15493. /**
  15494. * @author mrdoob / http://mrdoob.com/
  15495. */
  15496. THREE.RenderableObject = function () {
  15497. this.id = 0;
  15498. this.object = null;
  15499. this.z = 0;
  15500. };
  15501. /**
  15502. * @author mrdoob / http://mrdoob.com/
  15503. */
  15504. THREE.RenderableSprite = function () {
  15505. this.id = 0;
  15506. this.object = null;
  15507. this.x = 0;
  15508. this.y = 0;
  15509. this.z = 0;
  15510. this.rotation = 0;
  15511. this.scale = new THREE.Vector2();
  15512. this.material = null;
  15513. };
  15514. /**
  15515. * @author mrdoob / http://mrdoob.com/
  15516. */
  15517. THREE.RenderableLine = function () {
  15518. this.id = 0;
  15519. this.v1 = new THREE.RenderableVertex();
  15520. this.v2 = new THREE.RenderableVertex();
  15521. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15522. this.material = null;
  15523. this.z = 0;
  15524. };
  15525. /**
  15526. * @author mrdoob / http://mrdoob.com/
  15527. * @author alteredq / http://alteredqualia.com/
  15528. */
  15529. THREE.GeometryUtils = {
  15530. // Merge two geometries or geometry and geometry from object (using object's transform)
  15531. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15532. var matrix, normalMatrix,
  15533. vertexOffset = geometry1.vertices.length,
  15534. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15535. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15536. vertices1 = geometry1.vertices,
  15537. vertices2 = geometry2.vertices,
  15538. faces1 = geometry1.faces,
  15539. faces2 = geometry2.faces,
  15540. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15541. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15542. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15543. if ( object2 instanceof THREE.Mesh ) {
  15544. object2.matrixAutoUpdate && object2.updateMatrix();
  15545. matrix = object2.matrix;
  15546. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15547. }
  15548. // vertices
  15549. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15550. var vertex = vertices2[ i ];
  15551. var vertexCopy = vertex.clone();
  15552. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15553. vertices1.push( vertexCopy );
  15554. }
  15555. // faces
  15556. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15557. var face = faces2[ i ], faceCopy, normal, color,
  15558. faceVertexNormals = face.vertexNormals,
  15559. faceVertexColors = face.vertexColors;
  15560. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15561. faceCopy.normal.copy( face.normal );
  15562. if ( normalMatrix ) {
  15563. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15564. }
  15565. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15566. normal = faceVertexNormals[ j ].clone();
  15567. if ( normalMatrix ) {
  15568. normal.applyMatrix3( normalMatrix ).normalize();
  15569. }
  15570. faceCopy.vertexNormals.push( normal );
  15571. }
  15572. faceCopy.color.copy( face.color );
  15573. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15574. color = faceVertexColors[ j ];
  15575. faceCopy.vertexColors.push( color.clone() );
  15576. }
  15577. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15578. faceCopy.centroid.copy( face.centroid );
  15579. if ( matrix ) {
  15580. faceCopy.centroid.applyMatrix4( matrix );
  15581. }
  15582. faces1.push( faceCopy );
  15583. }
  15584. // uvs
  15585. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15586. var uv = uvs2[ i ], uvCopy = [];
  15587. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15588. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15589. }
  15590. uvs1.push( uvCopy );
  15591. }
  15592. },
  15593. // Get random point in triangle (via barycentric coordinates)
  15594. // (uniform distribution)
  15595. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15596. randomPointInTriangle: function () {
  15597. var vector = new THREE.Vector3();
  15598. return function ( vectorA, vectorB, vectorC ) {
  15599. var point = new THREE.Vector3();
  15600. var a = THREE.Math.random16();
  15601. var b = THREE.Math.random16();
  15602. if ( ( a + b ) > 1 ) {
  15603. a = 1 - a;
  15604. b = 1 - b;
  15605. }
  15606. var c = 1 - a - b;
  15607. point.copy( vectorA );
  15608. point.multiplyScalar( a );
  15609. vector.copy( vectorB );
  15610. vector.multiplyScalar( b );
  15611. point.add( vector );
  15612. vector.copy( vectorC );
  15613. vector.multiplyScalar( c );
  15614. point.add( vector );
  15615. return point;
  15616. };
  15617. }(),
  15618. // Get random point in face (triangle / quad)
  15619. // (uniform distribution)
  15620. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15621. var vA, vB, vC, vD;
  15622. vA = geometry.vertices[ face.a ];
  15623. vB = geometry.vertices[ face.b ];
  15624. vC = geometry.vertices[ face.c ];
  15625. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15626. },
  15627. // Get uniformly distributed random points in mesh
  15628. // - create array with cumulative sums of face areas
  15629. // - pick random number from 0 to total area
  15630. // - find corresponding place in area array by binary search
  15631. // - get random point in face
  15632. randomPointsInGeometry: function ( geometry, n ) {
  15633. var face, i,
  15634. faces = geometry.faces,
  15635. vertices = geometry.vertices,
  15636. il = faces.length,
  15637. totalArea = 0,
  15638. cumulativeAreas = [],
  15639. vA, vB, vC, vD;
  15640. // precompute face areas
  15641. for ( i = 0; i < il; i ++ ) {
  15642. face = faces[ i ];
  15643. vA = vertices[ face.a ];
  15644. vB = vertices[ face.b ];
  15645. vC = vertices[ face.c ];
  15646. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15647. totalArea += face._area;
  15648. cumulativeAreas[ i ] = totalArea;
  15649. }
  15650. // binary search cumulative areas array
  15651. function binarySearchIndices( value ) {
  15652. function binarySearch( start, end ) {
  15653. // return closest larger index
  15654. // if exact number is not found
  15655. if ( end < start )
  15656. return start;
  15657. var mid = start + Math.floor( ( end - start ) / 2 );
  15658. if ( cumulativeAreas[ mid ] > value ) {
  15659. return binarySearch( start, mid - 1 );
  15660. } else if ( cumulativeAreas[ mid ] < value ) {
  15661. return binarySearch( mid + 1, end );
  15662. } else {
  15663. return mid;
  15664. }
  15665. }
  15666. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15667. return result;
  15668. }
  15669. // pick random face weighted by face area
  15670. var r, index,
  15671. result = [];
  15672. var stats = {};
  15673. for ( i = 0; i < n; i ++ ) {
  15674. r = THREE.Math.random16() * totalArea;
  15675. index = binarySearchIndices( r );
  15676. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15677. if ( ! stats[ index ] ) {
  15678. stats[ index ] = 1;
  15679. } else {
  15680. stats[ index ] += 1;
  15681. }
  15682. }
  15683. return result;
  15684. },
  15685. // Get triangle area (half of parallelogram)
  15686. // http://mathworld.wolfram.com/TriangleArea.html
  15687. triangleArea: function () {
  15688. var vector1 = new THREE.Vector3();
  15689. var vector2 = new THREE.Vector3();
  15690. return function ( vectorA, vectorB, vectorC ) {
  15691. vector1.subVectors( vectorB, vectorA );
  15692. vector2.subVectors( vectorC, vectorA );
  15693. vector1.cross( vector2 );
  15694. return 0.5 * vector1.length();
  15695. };
  15696. }(),
  15697. // Center geometry so that 0,0,0 is in center of bounding box
  15698. center: function ( geometry ) {
  15699. geometry.computeBoundingBox();
  15700. var bb = geometry.boundingBox;
  15701. var offset = new THREE.Vector3();
  15702. offset.addVectors( bb.min, bb.max );
  15703. offset.multiplyScalar( -0.5 );
  15704. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15705. geometry.computeBoundingBox();
  15706. return offset;
  15707. },
  15708. triangulateQuads: function ( geometry ) {
  15709. var i, il, j, jl;
  15710. var faces = [];
  15711. var faceVertexUvs = [];
  15712. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15713. faceVertexUvs[ i ] = [];
  15714. }
  15715. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15716. var face = geometry.faces[ i ];
  15717. faces.push( face );
  15718. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15719. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15720. }
  15721. }
  15722. geometry.faces = faces;
  15723. geometry.faceVertexUvs = faceVertexUvs;
  15724. geometry.computeCentroids();
  15725. geometry.computeFaceNormals();
  15726. geometry.computeVertexNormals();
  15727. if ( geometry.hasTangents ) geometry.computeTangents();
  15728. }
  15729. };
  15730. /**
  15731. * @author alteredq / http://alteredqualia.com/
  15732. * @author mrdoob / http://mrdoob.com/
  15733. */
  15734. THREE.ImageUtils = {
  15735. crossOrigin: 'anonymous',
  15736. loadTexture: function ( url, mapping, onLoad, onError ) {
  15737. var loader = new THREE.ImageLoader();
  15738. loader.crossOrigin = this.crossOrigin;
  15739. var texture = new THREE.Texture( undefined, mapping );
  15740. var image = loader.load( url, function () {
  15741. texture.needsUpdate = true;
  15742. if ( onLoad ) onLoad( texture );
  15743. } );
  15744. texture.image = image;
  15745. texture.sourceFile = url;
  15746. return texture;
  15747. },
  15748. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15749. var texture = new THREE.CompressedTexture();
  15750. texture.mapping = mapping;
  15751. var request = new XMLHttpRequest();
  15752. request.onload = function () {
  15753. var buffer = request.response;
  15754. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15755. texture.format = dds.format;
  15756. texture.mipmaps = dds.mipmaps;
  15757. texture.image.width = dds.width;
  15758. texture.image.height = dds.height;
  15759. // gl.generateMipmap fails for compressed textures
  15760. // mipmaps must be embedded in the DDS file
  15761. // or texture filters must not use mipmapping
  15762. texture.generateMipmaps = false;
  15763. texture.needsUpdate = true;
  15764. if ( onLoad ) onLoad( texture );
  15765. }
  15766. request.onerror = onError;
  15767. request.open( 'GET', url, true );
  15768. request.responseType = "arraybuffer";
  15769. request.send( null );
  15770. return texture;
  15771. },
  15772. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15773. var images = [];
  15774. images.loadCount = 0;
  15775. var texture = new THREE.Texture();
  15776. texture.image = images;
  15777. if ( mapping !== undefined ) texture.mapping = mapping;
  15778. // no flipping needed for cube textures
  15779. texture.flipY = false;
  15780. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15781. var cubeImage = new Image();
  15782. images[ i ] = cubeImage;
  15783. cubeImage.onload = function () {
  15784. images.loadCount += 1;
  15785. if ( images.loadCount === 6 ) {
  15786. texture.needsUpdate = true;
  15787. if ( onLoad ) onLoad( texture );
  15788. }
  15789. };
  15790. cubeImage.onerror = onError;
  15791. cubeImage.crossOrigin = this.crossOrigin;
  15792. cubeImage.src = array[ i ];
  15793. }
  15794. return texture;
  15795. },
  15796. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15797. var images = [];
  15798. images.loadCount = 0;
  15799. var texture = new THREE.CompressedTexture();
  15800. texture.image = images;
  15801. if ( mapping !== undefined ) texture.mapping = mapping;
  15802. // no flipping for cube textures
  15803. // (also flipping doesn't work for compressed textures )
  15804. texture.flipY = false;
  15805. // can't generate mipmaps for compressed textures
  15806. // mips must be embedded in DDS files
  15807. texture.generateMipmaps = false;
  15808. var generateCubeFaceCallback = function ( rq, img ) {
  15809. return function () {
  15810. var buffer = rq.response;
  15811. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15812. img.format = dds.format;
  15813. img.mipmaps = dds.mipmaps;
  15814. img.width = dds.width;
  15815. img.height = dds.height;
  15816. images.loadCount += 1;
  15817. if ( images.loadCount === 6 ) {
  15818. texture.format = dds.format;
  15819. texture.needsUpdate = true;
  15820. if ( onLoad ) onLoad( texture );
  15821. }
  15822. }
  15823. }
  15824. // compressed cubemap textures as 6 separate DDS files
  15825. if ( array instanceof Array ) {
  15826. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15827. var cubeImage = {};
  15828. images[ i ] = cubeImage;
  15829. var request = new XMLHttpRequest();
  15830. request.onload = generateCubeFaceCallback( request, cubeImage );
  15831. request.onerror = onError;
  15832. var url = array[ i ];
  15833. request.open( 'GET', url, true );
  15834. request.responseType = "arraybuffer";
  15835. request.send( null );
  15836. }
  15837. // compressed cubemap texture stored in a single DDS file
  15838. } else {
  15839. var url = array;
  15840. var request = new XMLHttpRequest();
  15841. request.onload = function( ) {
  15842. var buffer = request.response;
  15843. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15844. if ( dds.isCubemap ) {
  15845. var faces = dds.mipmaps.length / dds.mipmapCount;
  15846. for ( var f = 0; f < faces; f ++ ) {
  15847. images[ f ] = { mipmaps : [] };
  15848. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15849. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15850. images[ f ].format = dds.format;
  15851. images[ f ].width = dds.width;
  15852. images[ f ].height = dds.height;
  15853. }
  15854. }
  15855. texture.format = dds.format;
  15856. texture.needsUpdate = true;
  15857. if ( onLoad ) onLoad( texture );
  15858. }
  15859. }
  15860. request.onerror = onError;
  15861. request.open( 'GET', url, true );
  15862. request.responseType = "arraybuffer";
  15863. request.send( null );
  15864. }
  15865. return texture;
  15866. },
  15867. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  15868. var images = [];
  15869. images.loadCount = 0;
  15870. var texture = new THREE.CompressedTexture();
  15871. texture.image = images;
  15872. if ( mapping !== undefined ) texture.mapping = mapping;
  15873. // no flipping for cube textures
  15874. // (also flipping doesn't work for compressed textures )
  15875. texture.flipY = false;
  15876. // can't generate mipmaps for compressed textures
  15877. // mips must be embedded in DDS files
  15878. texture.generateMipmaps = false;
  15879. {
  15880. var request = new XMLHttpRequest();
  15881. request.onload = function( ) {
  15882. var buffer = request.response;
  15883. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15884. if ( dds.isCubemap ) {
  15885. var faces = dds.mipmaps.length / dds.mipmapCount;
  15886. for ( var f = 0; f < faces; f ++ ) {
  15887. images[ f ] = { mipmaps : [] };
  15888. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15889. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15890. images[ f ].format = dds.format;
  15891. images[ f ].width = dds.width;
  15892. images[ f ].height = dds.height;
  15893. }
  15894. }
  15895. } else {
  15896. texture.image.width = dds.width;
  15897. texture.image.height = dds.height;
  15898. texture.mipmaps = dds.mipmaps;
  15899. }
  15900. texture.format = dds.format;
  15901. texture.needsUpdate = true;
  15902. if ( onLoad ) onLoad( texture );
  15903. }
  15904. request.onerror = onError;
  15905. request.open( 'GET', url, true );
  15906. request.responseType = "arraybuffer";
  15907. request.send( null );
  15908. }
  15909. return texture;
  15910. },
  15911. parseDDS: function ( buffer, loadMipmaps ) {
  15912. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15913. // Adapted from @toji's DDS utils
  15914. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15915. // All values and structures referenced from:
  15916. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15917. var DDS_MAGIC = 0x20534444;
  15918. var DDSD_CAPS = 0x1,
  15919. DDSD_HEIGHT = 0x2,
  15920. DDSD_WIDTH = 0x4,
  15921. DDSD_PITCH = 0x8,
  15922. DDSD_PIXELFORMAT = 0x1000,
  15923. DDSD_MIPMAPCOUNT = 0x20000,
  15924. DDSD_LINEARSIZE = 0x80000,
  15925. DDSD_DEPTH = 0x800000;
  15926. var DDSCAPS_COMPLEX = 0x8,
  15927. DDSCAPS_MIPMAP = 0x400000,
  15928. DDSCAPS_TEXTURE = 0x1000;
  15929. var DDSCAPS2_CUBEMAP = 0x200,
  15930. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15931. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15932. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15933. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15934. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15935. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15936. DDSCAPS2_VOLUME = 0x200000;
  15937. var DDPF_ALPHAPIXELS = 0x1,
  15938. DDPF_ALPHA = 0x2,
  15939. DDPF_FOURCC = 0x4,
  15940. DDPF_RGB = 0x40,
  15941. DDPF_YUV = 0x200,
  15942. DDPF_LUMINANCE = 0x20000;
  15943. function fourCCToInt32( value ) {
  15944. return value.charCodeAt(0) +
  15945. (value.charCodeAt(1) << 8) +
  15946. (value.charCodeAt(2) << 16) +
  15947. (value.charCodeAt(3) << 24);
  15948. }
  15949. function int32ToFourCC( value ) {
  15950. return String.fromCharCode(
  15951. value & 0xff,
  15952. (value >> 8) & 0xff,
  15953. (value >> 16) & 0xff,
  15954. (value >> 24) & 0xff
  15955. );
  15956. }
  15957. function loadARGBMip( buffer, dataOffset, width, height ) {
  15958. var dataLength = width*height*4;
  15959. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  15960. var byteArray = new Uint8Array( dataLength );
  15961. var dst = 0;
  15962. var src = 0;
  15963. for ( var y = 0; y < height; y++ ) {
  15964. for ( var x = 0; x < width; x++ ) {
  15965. var b = srcBuffer[src]; src++;
  15966. var g = srcBuffer[src]; src++;
  15967. var r = srcBuffer[src]; src++;
  15968. var a = srcBuffer[src]; src++;
  15969. byteArray[dst] = r; dst++; //r
  15970. byteArray[dst] = g; dst++; //g
  15971. byteArray[dst] = b; dst++; //b
  15972. byteArray[dst] = a; dst++; //a
  15973. }
  15974. }
  15975. return byteArray;
  15976. }
  15977. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15978. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15979. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15980. var headerLengthInt = 31; // The header length in 32 bit ints
  15981. // Offsets into the header array
  15982. var off_magic = 0;
  15983. var off_size = 1;
  15984. var off_flags = 2;
  15985. var off_height = 3;
  15986. var off_width = 4;
  15987. var off_mipmapCount = 7;
  15988. var off_pfFlags = 20;
  15989. var off_pfFourCC = 21;
  15990. var off_RGBBitCount = 22;
  15991. var off_RBitMask = 23;
  15992. var off_GBitMask = 24;
  15993. var off_BBitMask = 25;
  15994. var off_ABitMask = 26;
  15995. var off_caps = 27;
  15996. var off_caps2 = 28;
  15997. var off_caps3 = 29;
  15998. var off_caps4 = 30;
  15999. // Parse header
  16000. var header = new Int32Array( buffer, 0, headerLengthInt );
  16001. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16002. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16003. return dds;
  16004. }
  16005. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16006. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16007. return dds;
  16008. }
  16009. var blockBytes;
  16010. var fourCC = header[ off_pfFourCC ];
  16011. var isRGBAUncompressed = false;
  16012. switch ( fourCC ) {
  16013. case FOURCC_DXT1:
  16014. blockBytes = 8;
  16015. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16016. break;
  16017. case FOURCC_DXT3:
  16018. blockBytes = 16;
  16019. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16020. break;
  16021. case FOURCC_DXT5:
  16022. blockBytes = 16;
  16023. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16024. break;
  16025. default:
  16026. if( header[off_RGBBitCount] ==32
  16027. && header[off_RBitMask]&0xff0000
  16028. && header[off_GBitMask]&0xff00
  16029. && header[off_BBitMask]&0xff
  16030. && header[off_ABitMask]&0xff000000 ) {
  16031. isRGBAUncompressed = true;
  16032. blockBytes = 64;
  16033. dds.format = THREE.RGBAFormat;
  16034. } else {
  16035. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16036. return dds;
  16037. }
  16038. }
  16039. dds.mipmapCount = 1;
  16040. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16041. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16042. }
  16043. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16044. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16045. dds.width = header[ off_width ];
  16046. dds.height = header[ off_height ];
  16047. var dataOffset = header[ off_size ] + 4;
  16048. // Extract mipmaps buffers
  16049. var width = dds.width;
  16050. var height = dds.height;
  16051. var faces = dds.isCubemap ? 6 : 1;
  16052. for ( var face = 0; face < faces; face ++ ) {
  16053. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16054. if( isRGBAUncompressed ) {
  16055. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16056. var dataLength = byteArray.length;
  16057. } else {
  16058. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16059. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16060. }
  16061. var mipmap = { "data": byteArray, "width": width, "height": height };
  16062. dds.mipmaps.push( mipmap );
  16063. dataOffset += dataLength;
  16064. width = Math.max( width * 0.5, 1 );
  16065. height = Math.max( height * 0.5, 1 );
  16066. }
  16067. width = dds.width;
  16068. height = dds.height;
  16069. }
  16070. return dds;
  16071. },
  16072. getNormalMap: function ( image, depth ) {
  16073. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16074. var cross = function ( a, b ) {
  16075. 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 ] ];
  16076. }
  16077. var subtract = function ( a, b ) {
  16078. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16079. }
  16080. var normalize = function ( a ) {
  16081. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16082. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16083. }
  16084. depth = depth | 1;
  16085. var width = image.width;
  16086. var height = image.height;
  16087. var canvas = document.createElement( 'canvas' );
  16088. canvas.width = width;
  16089. canvas.height = height;
  16090. var context = canvas.getContext( '2d' );
  16091. context.drawImage( image, 0, 0 );
  16092. var data = context.getImageData( 0, 0, width, height ).data;
  16093. var imageData = context.createImageData( width, height );
  16094. var output = imageData.data;
  16095. for ( var x = 0; x < width; x ++ ) {
  16096. for ( var y = 0; y < height; y ++ ) {
  16097. var ly = y - 1 < 0 ? 0 : y - 1;
  16098. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16099. var lx = x - 1 < 0 ? 0 : x - 1;
  16100. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16101. var points = [];
  16102. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16103. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16104. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16105. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16106. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16107. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16108. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16109. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16110. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16111. var normals = [];
  16112. var num_points = points.length;
  16113. for ( var i = 0; i < num_points; i ++ ) {
  16114. var v1 = points[ i ];
  16115. var v2 = points[ ( i + 1 ) % num_points ];
  16116. v1 = subtract( v1, origin );
  16117. v2 = subtract( v2, origin );
  16118. normals.push( normalize( cross( v1, v2 ) ) );
  16119. }
  16120. var normal = [ 0, 0, 0 ];
  16121. for ( var i = 0; i < normals.length; i ++ ) {
  16122. normal[ 0 ] += normals[ i ][ 0 ];
  16123. normal[ 1 ] += normals[ i ][ 1 ];
  16124. normal[ 2 ] += normals[ i ][ 2 ];
  16125. }
  16126. normal[ 0 ] /= normals.length;
  16127. normal[ 1 ] /= normals.length;
  16128. normal[ 2 ] /= normals.length;
  16129. var idx = ( y * width + x ) * 4;
  16130. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16131. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16132. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16133. output[ idx + 3 ] = 255;
  16134. }
  16135. }
  16136. context.putImageData( imageData, 0, 0 );
  16137. return canvas;
  16138. },
  16139. generateDataTexture: function ( width, height, color ) {
  16140. var size = width * height;
  16141. var data = new Uint8Array( 3 * size );
  16142. var r = Math.floor( color.r * 255 );
  16143. var g = Math.floor( color.g * 255 );
  16144. var b = Math.floor( color.b * 255 );
  16145. for ( var i = 0; i < size; i ++ ) {
  16146. data[ i * 3 ] = r;
  16147. data[ i * 3 + 1 ] = g;
  16148. data[ i * 3 + 2 ] = b;
  16149. }
  16150. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16151. texture.needsUpdate = true;
  16152. return texture;
  16153. }
  16154. };
  16155. /**
  16156. * @author alteredq / http://alteredqualia.com/
  16157. */
  16158. THREE.SceneUtils = {
  16159. createMultiMaterialObject: function ( geometry, materials ) {
  16160. var group = new THREE.Object3D();
  16161. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16162. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16163. }
  16164. return group;
  16165. },
  16166. detach : function ( child, parent, scene ) {
  16167. child.applyMatrix( parent.matrixWorld );
  16168. parent.remove( child );
  16169. scene.add( child );
  16170. },
  16171. attach: function ( child, scene, parent ) {
  16172. var matrixWorldInverse = new THREE.Matrix4();
  16173. matrixWorldInverse.getInverse( parent.matrixWorld );
  16174. child.applyMatrix( matrixWorldInverse );
  16175. scene.remove( child );
  16176. parent.add( child );
  16177. }
  16178. };
  16179. /**
  16180. * @author zz85 / http://www.lab4games.net/zz85/blog
  16181. * @author alteredq / http://alteredqualia.com/
  16182. *
  16183. * For Text operations in three.js (See TextGeometry)
  16184. *
  16185. * It uses techniques used in:
  16186. *
  16187. * typeface.js and canvastext
  16188. * For converting fonts and rendering with javascript
  16189. * http://typeface.neocracy.org
  16190. *
  16191. * Triangulation ported from AS3
  16192. * Simple Polygon Triangulation
  16193. * http://actionsnippet.com/?p=1462
  16194. *
  16195. * A Method to triangulate shapes with holes
  16196. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16197. *
  16198. */
  16199. THREE.FontUtils = {
  16200. faces : {},
  16201. // Just for now. face[weight][style]
  16202. face : "helvetiker",
  16203. weight: "normal",
  16204. style : "normal",
  16205. size : 150,
  16206. divisions : 10,
  16207. getFace : function() {
  16208. return this.faces[ this.face ][ this.weight ][ this.style ];
  16209. },
  16210. loadFace : function( data ) {
  16211. var family = data.familyName.toLowerCase();
  16212. var ThreeFont = this;
  16213. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16214. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16215. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16216. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16217. return data;
  16218. },
  16219. drawText : function( text ) {
  16220. var characterPts = [], allPts = [];
  16221. // RenderText
  16222. var i, p,
  16223. face = this.getFace(),
  16224. scale = this.size / face.resolution,
  16225. offset = 0,
  16226. chars = String( text ).split( '' ),
  16227. length = chars.length;
  16228. var fontPaths = [];
  16229. for ( i = 0; i < length; i ++ ) {
  16230. var path = new THREE.Path();
  16231. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16232. offset += ret.offset;
  16233. fontPaths.push( ret.path );
  16234. }
  16235. // get the width
  16236. var width = offset / 2;
  16237. //
  16238. // for ( p = 0; p < allPts.length; p++ ) {
  16239. //
  16240. // allPts[ p ].x -= width;
  16241. //
  16242. // }
  16243. //var extract = this.extractPoints( allPts, characterPts );
  16244. //extract.contour = allPts;
  16245. //extract.paths = fontPaths;
  16246. //extract.offset = width;
  16247. return { paths : fontPaths, offset : width };
  16248. },
  16249. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16250. var pts = [];
  16251. var i, i2, divisions,
  16252. outline, action, length,
  16253. scaleX, scaleY,
  16254. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16255. laste,
  16256. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16257. if ( !glyph ) return;
  16258. if ( glyph.o ) {
  16259. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16260. length = outline.length;
  16261. scaleX = scale;
  16262. scaleY = scale;
  16263. for ( i = 0; i < length; ) {
  16264. action = outline[ i ++ ];
  16265. //console.log( action );
  16266. switch( action ) {
  16267. case 'm':
  16268. // Move To
  16269. x = outline[ i++ ] * scaleX + offset;
  16270. y = outline[ i++ ] * scaleY;
  16271. path.moveTo( x, y );
  16272. break;
  16273. case 'l':
  16274. // Line To
  16275. x = outline[ i++ ] * scaleX + offset;
  16276. y = outline[ i++ ] * scaleY;
  16277. path.lineTo(x,y);
  16278. break;
  16279. case 'q':
  16280. // QuadraticCurveTo
  16281. cpx = outline[ i++ ] * scaleX + offset;
  16282. cpy = outline[ i++ ] * scaleY;
  16283. cpx1 = outline[ i++ ] * scaleX + offset;
  16284. cpy1 = outline[ i++ ] * scaleY;
  16285. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16286. laste = pts[ pts.length - 1 ];
  16287. if ( laste ) {
  16288. cpx0 = laste.x;
  16289. cpy0 = laste.y;
  16290. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16291. var t = i2 / divisions;
  16292. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16293. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16294. }
  16295. }
  16296. break;
  16297. case 'b':
  16298. // Cubic Bezier Curve
  16299. cpx = outline[ i++ ] * scaleX + offset;
  16300. cpy = outline[ i++ ] * scaleY;
  16301. cpx1 = outline[ i++ ] * scaleX + offset;
  16302. cpy1 = outline[ i++ ] * -scaleY;
  16303. cpx2 = outline[ i++ ] * scaleX + offset;
  16304. cpy2 = outline[ i++ ] * -scaleY;
  16305. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16306. laste = pts[ pts.length - 1 ];
  16307. if ( laste ) {
  16308. cpx0 = laste.x;
  16309. cpy0 = laste.y;
  16310. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16311. var t = i2 / divisions;
  16312. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16313. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16314. }
  16315. }
  16316. break;
  16317. }
  16318. }
  16319. }
  16320. return { offset: glyph.ha*scale, path:path};
  16321. }
  16322. };
  16323. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16324. // Parameters
  16325. parameters = parameters || {};
  16326. var size = parameters.size !== undefined ? parameters.size : 100;
  16327. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16328. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16329. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16330. var style = parameters.style !== undefined ? parameters.style : "normal";
  16331. THREE.FontUtils.size = size;
  16332. THREE.FontUtils.divisions = curveSegments;
  16333. THREE.FontUtils.face = font;
  16334. THREE.FontUtils.weight = weight;
  16335. THREE.FontUtils.style = style;
  16336. // Get a Font data json object
  16337. var data = THREE.FontUtils.drawText( text );
  16338. var paths = data.paths;
  16339. var shapes = [];
  16340. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16341. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16342. }
  16343. return shapes;
  16344. };
  16345. /**
  16346. * This code is a quick port of code written in C++ which was submitted to
  16347. * flipcode.com by John W. Ratcliff // July 22, 2000
  16348. * See original code and more information here:
  16349. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16350. *
  16351. * ported to actionscript by Zevan Rosser
  16352. * www.actionsnippet.com
  16353. *
  16354. * ported to javascript by Joshua Koo
  16355. * http://www.lab4games.net/zz85/blog
  16356. *
  16357. */
  16358. ( function( namespace ) {
  16359. var EPSILON = 0.0000000001;
  16360. // takes in an contour array and returns
  16361. var process = function( contour, indices ) {
  16362. var n = contour.length;
  16363. if ( n < 3 ) return null;
  16364. var result = [],
  16365. verts = [],
  16366. vertIndices = [];
  16367. /* we want a counter-clockwise polygon in verts */
  16368. var u, v, w;
  16369. if ( area( contour ) > 0.0 ) {
  16370. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16371. } else {
  16372. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16373. }
  16374. var nv = n;
  16375. /* remove nv - 2 vertices, creating 1 triangle every time */
  16376. var count = 2 * nv; /* error detection */
  16377. for( v = nv - 1; nv > 2; ) {
  16378. /* if we loop, it is probably a non-simple polygon */
  16379. if ( ( count-- ) <= 0 ) {
  16380. //** Triangulate: ERROR - probable bad polygon!
  16381. //throw ( "Warning, unable to triangulate polygon!" );
  16382. //return null;
  16383. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16384. console.log( "Warning, unable to triangulate polygon!" );
  16385. if ( indices ) return vertIndices;
  16386. return result;
  16387. }
  16388. /* three consecutive vertices in current polygon, <u,v,w> */
  16389. u = v; if ( nv <= u ) u = 0; /* previous */
  16390. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16391. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16392. if ( snip( contour, u, v, w, nv, verts ) ) {
  16393. var a, b, c, s, t;
  16394. /* true names of the vertices */
  16395. a = verts[ u ];
  16396. b = verts[ v ];
  16397. c = verts[ w ];
  16398. /* output Triangle */
  16399. result.push( [ contour[ a ],
  16400. contour[ b ],
  16401. contour[ c ] ] );
  16402. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16403. /* remove v from the remaining polygon */
  16404. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16405. verts[ s ] = verts[ t ];
  16406. }
  16407. nv--;
  16408. /* reset error detection counter */
  16409. count = 2 * nv;
  16410. }
  16411. }
  16412. if ( indices ) return vertIndices;
  16413. return result;
  16414. };
  16415. // calculate area of the contour polygon
  16416. var area = function ( contour ) {
  16417. var n = contour.length;
  16418. var a = 0.0;
  16419. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16420. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16421. }
  16422. return a * 0.5;
  16423. };
  16424. var snip = function ( contour, u, v, w, n, verts ) {
  16425. var p;
  16426. var ax, ay, bx, by;
  16427. var cx, cy, px, py;
  16428. ax = contour[ verts[ u ] ].x;
  16429. ay = contour[ verts[ u ] ].y;
  16430. bx = contour[ verts[ v ] ].x;
  16431. by = contour[ verts[ v ] ].y;
  16432. cx = contour[ verts[ w ] ].x;
  16433. cy = contour[ verts[ w ] ].y;
  16434. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16435. var aX, aY, bX, bY, cX, cY;
  16436. var apx, apy, bpx, bpy, cpx, cpy;
  16437. var cCROSSap, bCROSScp, aCROSSbp;
  16438. aX = cx - bx; aY = cy - by;
  16439. bX = ax - cx; bY = ay - cy;
  16440. cX = bx - ax; cY = by - ay;
  16441. for ( p = 0; p < n; p++ ) {
  16442. if( (p === u) || (p === v) || (p === w) ) continue;
  16443. px = contour[ verts[ p ] ].x
  16444. py = contour[ verts[ p ] ].y
  16445. apx = px - ax; apy = py - ay;
  16446. bpx = px - bx; bpy = py - by;
  16447. cpx = px - cx; cpy = py - cy;
  16448. // see if p is inside triangle abc
  16449. aCROSSbp = aX*bpy - aY*bpx;
  16450. cCROSSap = cX*apy - cY*apx;
  16451. bCROSScp = bX*cpy - bY*cpx;
  16452. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16453. }
  16454. return true;
  16455. };
  16456. namespace.Triangulate = process;
  16457. namespace.Triangulate.area = area;
  16458. return namespace;
  16459. })(THREE.FontUtils);
  16460. // To use the typeface.js face files, hook up the API
  16461. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16462. THREE.typeface_js = self._typeface_js;
  16463. /**
  16464. * @author zz85 / http://www.lab4games.net/zz85/blog
  16465. * Extensible curve object
  16466. *
  16467. * Some common of Curve methods
  16468. * .getPoint(t), getTangent(t)
  16469. * .getPointAt(u), getTagentAt(u)
  16470. * .getPoints(), .getSpacedPoints()
  16471. * .getLength()
  16472. * .updateArcLengths()
  16473. *
  16474. * This following classes subclasses THREE.Curve:
  16475. *
  16476. * -- 2d classes --
  16477. * THREE.LineCurve
  16478. * THREE.QuadraticBezierCurve
  16479. * THREE.CubicBezierCurve
  16480. * THREE.SplineCurve
  16481. * THREE.ArcCurve
  16482. * THREE.EllipseCurve
  16483. *
  16484. * -- 3d classes --
  16485. * THREE.LineCurve3
  16486. * THREE.QuadraticBezierCurve3
  16487. * THREE.CubicBezierCurve3
  16488. * THREE.SplineCurve3
  16489. * THREE.ClosedSplineCurve3
  16490. *
  16491. * A series of curves can be represented as a THREE.CurvePath
  16492. *
  16493. **/
  16494. /**************************************************************
  16495. * Abstract Curve base class
  16496. **************************************************************/
  16497. THREE.Curve = function () {
  16498. };
  16499. // Virtual base class method to overwrite and implement in subclasses
  16500. // - t [0 .. 1]
  16501. THREE.Curve.prototype.getPoint = function ( t ) {
  16502. console.log( "Warning, getPoint() not implemented!" );
  16503. return null;
  16504. };
  16505. // Get point at relative position in curve according to arc length
  16506. // - u [0 .. 1]
  16507. THREE.Curve.prototype.getPointAt = function ( u ) {
  16508. var t = this.getUtoTmapping( u );
  16509. return this.getPoint( t );
  16510. };
  16511. // Get sequence of points using getPoint( t )
  16512. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16513. if ( !divisions ) divisions = 5;
  16514. var d, pts = [];
  16515. for ( d = 0; d <= divisions; d ++ ) {
  16516. pts.push( this.getPoint( d / divisions ) );
  16517. }
  16518. return pts;
  16519. };
  16520. // Get sequence of points using getPointAt( u )
  16521. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16522. if ( !divisions ) divisions = 5;
  16523. var d, pts = [];
  16524. for ( d = 0; d <= divisions; d ++ ) {
  16525. pts.push( this.getPointAt( d / divisions ) );
  16526. }
  16527. return pts;
  16528. };
  16529. // Get total curve arc length
  16530. THREE.Curve.prototype.getLength = function () {
  16531. var lengths = this.getLengths();
  16532. return lengths[ lengths.length - 1 ];
  16533. };
  16534. // Get list of cumulative segment lengths
  16535. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16536. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16537. if ( this.cacheArcLengths
  16538. && ( this.cacheArcLengths.length == divisions + 1 )
  16539. && !this.needsUpdate) {
  16540. //console.log( "cached", this.cacheArcLengths );
  16541. return this.cacheArcLengths;
  16542. }
  16543. this.needsUpdate = false;
  16544. var cache = [];
  16545. var current, last = this.getPoint( 0 );
  16546. var p, sum = 0;
  16547. cache.push( 0 );
  16548. for ( p = 1; p <= divisions; p ++ ) {
  16549. current = this.getPoint ( p / divisions );
  16550. sum += current.distanceTo( last );
  16551. cache.push( sum );
  16552. last = current;
  16553. }
  16554. this.cacheArcLengths = cache;
  16555. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16556. };
  16557. THREE.Curve.prototype.updateArcLengths = function() {
  16558. this.needsUpdate = true;
  16559. this.getLengths();
  16560. };
  16561. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16562. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16563. var arcLengths = this.getLengths();
  16564. var i = 0, il = arcLengths.length;
  16565. var targetArcLength; // The targeted u distance value to get
  16566. if ( distance ) {
  16567. targetArcLength = distance;
  16568. } else {
  16569. targetArcLength = u * arcLengths[ il - 1 ];
  16570. }
  16571. //var time = Date.now();
  16572. // binary search for the index with largest value smaller than target u distance
  16573. var low = 0, high = il - 1, comparison;
  16574. while ( low <= high ) {
  16575. 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
  16576. comparison = arcLengths[ i ] - targetArcLength;
  16577. if ( comparison < 0 ) {
  16578. low = i + 1;
  16579. continue;
  16580. } else if ( comparison > 0 ) {
  16581. high = i - 1;
  16582. continue;
  16583. } else {
  16584. high = i;
  16585. break;
  16586. // DONE
  16587. }
  16588. }
  16589. i = high;
  16590. //console.log('b' , i, low, high, Date.now()- time);
  16591. if ( arcLengths[ i ] == targetArcLength ) {
  16592. var t = i / ( il - 1 );
  16593. return t;
  16594. }
  16595. // we could get finer grain at lengths, or use simple interpolatation between two points
  16596. var lengthBefore = arcLengths[ i ];
  16597. var lengthAfter = arcLengths[ i + 1 ];
  16598. var segmentLength = lengthAfter - lengthBefore;
  16599. // determine where we are between the 'before' and 'after' points
  16600. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16601. // add that fractional amount to t
  16602. var t = ( i + segmentFraction ) / ( il -1 );
  16603. return t;
  16604. };
  16605. // Returns a unit vector tangent at t
  16606. // In case any sub curve does not implement its tangent derivation,
  16607. // 2 points a small delta apart will be used to find its gradient
  16608. // which seems to give a reasonable approximation
  16609. THREE.Curve.prototype.getTangent = function( t ) {
  16610. var delta = 0.0001;
  16611. var t1 = t - delta;
  16612. var t2 = t + delta;
  16613. // Capping in case of danger
  16614. if ( t1 < 0 ) t1 = 0;
  16615. if ( t2 > 1 ) t2 = 1;
  16616. var pt1 = this.getPoint( t1 );
  16617. var pt2 = this.getPoint( t2 );
  16618. var vec = pt2.clone().sub(pt1);
  16619. return vec.normalize();
  16620. };
  16621. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16622. var t = this.getUtoTmapping( u );
  16623. return this.getTangent( t );
  16624. };
  16625. /**************************************************************
  16626. * Utils
  16627. **************************************************************/
  16628. THREE.Curve.Utils = {
  16629. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16630. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16631. },
  16632. // Puay Bing, thanks for helping with this derivative!
  16633. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16634. return -3 * p0 * (1 - t) * (1 - t) +
  16635. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16636. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16637. 3 * t * t * p3;
  16638. },
  16639. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16640. // To check if my formulas are correct
  16641. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16642. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16643. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16644. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16645. return h00 + h10 + h01 + h11;
  16646. },
  16647. // Catmull-Rom
  16648. interpolate: function( p0, p1, p2, p3, t ) {
  16649. var v0 = ( p2 - p0 ) * 0.5;
  16650. var v1 = ( p3 - p1 ) * 0.5;
  16651. var t2 = t * t;
  16652. var t3 = t * t2;
  16653. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16654. }
  16655. };
  16656. // TODO: Transformation for Curves?
  16657. /**************************************************************
  16658. * 3D Curves
  16659. **************************************************************/
  16660. // A Factory method for creating new curve subclasses
  16661. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16662. constructor.prototype = Object.create( THREE.Curve.prototype );
  16663. constructor.prototype.getPoint = getPointFunc;
  16664. return constructor;
  16665. };
  16666. /**
  16667. * @author zz85 / http://www.lab4games.net/zz85/blog
  16668. *
  16669. **/
  16670. /**************************************************************
  16671. * Curved Path - a curve path is simply a array of connected
  16672. * curves, but retains the api of a curve
  16673. **************************************************************/
  16674. THREE.CurvePath = function () {
  16675. this.curves = [];
  16676. this.bends = [];
  16677. this.autoClose = false; // Automatically closes the path
  16678. };
  16679. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16680. THREE.CurvePath.prototype.add = function ( curve ) {
  16681. this.curves.push( curve );
  16682. };
  16683. THREE.CurvePath.prototype.checkConnection = function() {
  16684. // TODO
  16685. // If the ending of curve is not connected to the starting
  16686. // or the next curve, then, this is not a real path
  16687. };
  16688. THREE.CurvePath.prototype.closePath = function() {
  16689. // TODO Test
  16690. // and verify for vector3 (needs to implement equals)
  16691. // Add a line curve if start and end of lines are not connected
  16692. var startPoint = this.curves[0].getPoint(0);
  16693. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16694. if (!startPoint.equals(endPoint)) {
  16695. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16696. }
  16697. };
  16698. // To get accurate point with reference to
  16699. // entire path distance at time t,
  16700. // following has to be done:
  16701. // 1. Length of each sub path have to be known
  16702. // 2. Locate and identify type of curve
  16703. // 3. Get t for the curve
  16704. // 4. Return curve.getPointAt(t')
  16705. THREE.CurvePath.prototype.getPoint = function( t ) {
  16706. var d = t * this.getLength();
  16707. var curveLengths = this.getCurveLengths();
  16708. var i = 0, diff, curve;
  16709. // To think about boundaries points.
  16710. while ( i < curveLengths.length ) {
  16711. if ( curveLengths[ i ] >= d ) {
  16712. diff = curveLengths[ i ] - d;
  16713. curve = this.curves[ i ];
  16714. var u = 1 - diff / curve.getLength();
  16715. return curve.getPointAt( u );
  16716. break;
  16717. }
  16718. i ++;
  16719. }
  16720. return null;
  16721. // loop where sum != 0, sum > d , sum+1 <d
  16722. };
  16723. /*
  16724. THREE.CurvePath.prototype.getTangent = function( t ) {
  16725. };*/
  16726. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16727. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16728. // getPoint() depends on getLength
  16729. THREE.CurvePath.prototype.getLength = function() {
  16730. var lens = this.getCurveLengths();
  16731. return lens[ lens.length - 1 ];
  16732. };
  16733. // Compute lengths and cache them
  16734. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16735. THREE.CurvePath.prototype.getCurveLengths = function() {
  16736. // We use cache values if curves and cache array are same length
  16737. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16738. return this.cacheLengths;
  16739. };
  16740. // Get length of subsurve
  16741. // Push sums into cached array
  16742. var lengths = [], sums = 0;
  16743. var i, il = this.curves.length;
  16744. for ( i = 0; i < il; i ++ ) {
  16745. sums += this.curves[ i ].getLength();
  16746. lengths.push( sums );
  16747. }
  16748. this.cacheLengths = lengths;
  16749. return lengths;
  16750. };
  16751. // Returns min and max coordinates, as well as centroid
  16752. THREE.CurvePath.prototype.getBoundingBox = function () {
  16753. var points = this.getPoints();
  16754. var maxX, maxY, maxZ;
  16755. var minX, minY, minZ;
  16756. maxX = maxY = Number.NEGATIVE_INFINITY;
  16757. minX = minY = Number.POSITIVE_INFINITY;
  16758. var p, i, il, sum;
  16759. var v3 = points[0] instanceof THREE.Vector3;
  16760. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16761. for ( i = 0, il = points.length; i < il; i ++ ) {
  16762. p = points[ i ];
  16763. if ( p.x > maxX ) maxX = p.x;
  16764. else if ( p.x < minX ) minX = p.x;
  16765. if ( p.y > maxY ) maxY = p.y;
  16766. else if ( p.y < minY ) minY = p.y;
  16767. if ( v3 ) {
  16768. if ( p.z > maxZ ) maxZ = p.z;
  16769. else if ( p.z < minZ ) minZ = p.z;
  16770. }
  16771. sum.add( p );
  16772. }
  16773. var ret = {
  16774. minX: minX,
  16775. minY: minY,
  16776. maxX: maxX,
  16777. maxY: maxY,
  16778. centroid: sum.divideScalar( il )
  16779. };
  16780. if ( v3 ) {
  16781. ret.maxZ = maxZ;
  16782. ret.minZ = minZ;
  16783. }
  16784. return ret;
  16785. };
  16786. /**************************************************************
  16787. * Create Geometries Helpers
  16788. **************************************************************/
  16789. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16790. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16791. var pts = this.getPoints( divisions, true );
  16792. return this.createGeometry( pts );
  16793. };
  16794. // Generate geometry from equidistance sampling along the path
  16795. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16796. var pts = this.getSpacedPoints( divisions, true );
  16797. return this.createGeometry( pts );
  16798. };
  16799. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16800. var geometry = new THREE.Geometry();
  16801. for ( var i = 0; i < points.length; i ++ ) {
  16802. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16803. }
  16804. return geometry;
  16805. };
  16806. /**************************************************************
  16807. * Bend / Wrap Helper Methods
  16808. **************************************************************/
  16809. // Wrap path / Bend modifiers?
  16810. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16811. this.bends.push( bendpath );
  16812. };
  16813. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16814. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16815. var i, il;
  16816. if ( !bends ) {
  16817. bends = this.bends;
  16818. }
  16819. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16820. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16821. }
  16822. return oldPts;
  16823. };
  16824. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16825. var oldPts = this.getSpacedPoints( segments );
  16826. var i, il;
  16827. if ( !bends ) {
  16828. bends = this.bends;
  16829. }
  16830. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16831. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16832. }
  16833. return oldPts;
  16834. };
  16835. // This returns getPoints() bend/wrapped around the contour of a path.
  16836. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16837. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16838. var bounds = this.getBoundingBox();
  16839. var i, il, p, oldX, oldY, xNorm;
  16840. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16841. p = oldPts[ i ];
  16842. oldX = p.x;
  16843. oldY = p.y;
  16844. xNorm = oldX / bounds.maxX;
  16845. // If using actual distance, for length > path, requires line extrusions
  16846. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16847. xNorm = path.getUtoTmapping( xNorm, oldX );
  16848. // check for out of bounds?
  16849. var pathPt = path.getPoint( xNorm );
  16850. var normal = path.getTangent( xNorm );
  16851. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  16852. p.x = pathPt.x + normal.x;
  16853. p.y = pathPt.y + normal.y;
  16854. }
  16855. return oldPts;
  16856. };
  16857. /**
  16858. * @author alteredq / http://alteredqualia.com/
  16859. */
  16860. THREE.Gyroscope = function () {
  16861. THREE.Object3D.call( this );
  16862. };
  16863. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16864. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16865. this.matrixAutoUpdate && this.updateMatrix();
  16866. // update matrixWorld
  16867. if ( this.matrixWorldNeedsUpdate || force ) {
  16868. if ( this.parent ) {
  16869. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16870. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  16871. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  16872. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  16873. } else {
  16874. this.matrixWorld.copy( this.matrix );
  16875. }
  16876. this.matrixWorldNeedsUpdate = false;
  16877. force = true;
  16878. }
  16879. // update children
  16880. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16881. this.children[ i ].updateMatrixWorld( force );
  16882. }
  16883. };
  16884. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16885. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16886. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  16887. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  16888. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16889. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16890. /**
  16891. * @author zz85 / http://www.lab4games.net/zz85/blog
  16892. * Creates free form 2d path using series of points, lines or curves.
  16893. *
  16894. **/
  16895. THREE.Path = function ( points ) {
  16896. THREE.CurvePath.call(this);
  16897. this.actions = [];
  16898. if ( points ) {
  16899. this.fromPoints( points );
  16900. }
  16901. };
  16902. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16903. THREE.PathActions = {
  16904. MOVE_TO: 'moveTo',
  16905. LINE_TO: 'lineTo',
  16906. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16907. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16908. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16909. ARC: 'arc', // Circle
  16910. ELLIPSE: 'ellipse'
  16911. };
  16912. // TODO Clean up PATH API
  16913. // Create path using straight lines to connect all points
  16914. // - vectors: array of Vector2
  16915. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16916. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16917. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16918. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16919. };
  16920. };
  16921. // startPath() endPath()?
  16922. THREE.Path.prototype.moveTo = function ( x, y ) {
  16923. var args = Array.prototype.slice.call( arguments );
  16924. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16925. };
  16926. THREE.Path.prototype.lineTo = function ( x, y ) {
  16927. var args = Array.prototype.slice.call( arguments );
  16928. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16929. var x0 = lastargs[ lastargs.length - 2 ];
  16930. var y0 = lastargs[ lastargs.length - 1 ];
  16931. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16932. this.curves.push( curve );
  16933. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16934. };
  16935. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16936. var args = Array.prototype.slice.call( arguments );
  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. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16941. new THREE.Vector2( aCPx, aCPy ),
  16942. new THREE.Vector2( aX, aY ) );
  16943. this.curves.push( curve );
  16944. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16945. };
  16946. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16947. aCP2x, aCP2y,
  16948. aX, aY ) {
  16949. var args = Array.prototype.slice.call( arguments );
  16950. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16951. var x0 = lastargs[ lastargs.length - 2 ];
  16952. var y0 = lastargs[ lastargs.length - 1 ];
  16953. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16954. new THREE.Vector2( aCP1x, aCP1y ),
  16955. new THREE.Vector2( aCP2x, aCP2y ),
  16956. new THREE.Vector2( aX, aY ) );
  16957. this.curves.push( curve );
  16958. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16959. };
  16960. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16961. var args = Array.prototype.slice.call( arguments );
  16962. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16963. var x0 = lastargs[ lastargs.length - 2 ];
  16964. var y0 = lastargs[ lastargs.length - 1 ];
  16965. //---
  16966. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16967. Array.prototype.push.apply( npts, pts );
  16968. var curve = new THREE.SplineCurve( npts );
  16969. this.curves.push( curve );
  16970. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16971. };
  16972. // FUTURE: Change the API or follow canvas API?
  16973. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16974. aStartAngle, aEndAngle, aClockwise ) {
  16975. var lastargs = this.actions[ this.actions.length - 1].args;
  16976. var x0 = lastargs[ lastargs.length - 2 ];
  16977. var y0 = lastargs[ lastargs.length - 1 ];
  16978. this.absarc(aX + x0, aY + y0, aRadius,
  16979. aStartAngle, aEndAngle, aClockwise );
  16980. };
  16981. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16982. aStartAngle, aEndAngle, aClockwise ) {
  16983. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16984. };
  16985. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16986. aStartAngle, aEndAngle, aClockwise ) {
  16987. var lastargs = this.actions[ this.actions.length - 1].args;
  16988. var x0 = lastargs[ lastargs.length - 2 ];
  16989. var y0 = lastargs[ lastargs.length - 1 ];
  16990. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16991. aStartAngle, aEndAngle, aClockwise );
  16992. };
  16993. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16994. aStartAngle, aEndAngle, aClockwise ) {
  16995. var args = Array.prototype.slice.call( arguments );
  16996. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16997. aStartAngle, aEndAngle, aClockwise );
  16998. this.curves.push( curve );
  16999. var lastPoint = curve.getPoint(1);
  17000. args.push(lastPoint.x);
  17001. args.push(lastPoint.y);
  17002. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17003. };
  17004. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17005. if ( ! divisions ) divisions = 40;
  17006. var points = [];
  17007. for ( var i = 0; i < divisions; i ++ ) {
  17008. points.push( this.getPoint( i / divisions ) );
  17009. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17010. }
  17011. // if ( closedPath ) {
  17012. //
  17013. // points.push( points[ 0 ] );
  17014. //
  17015. // }
  17016. return points;
  17017. };
  17018. /* Return an array of vectors based on contour of the path */
  17019. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17020. if (this.useSpacedPoints) {
  17021. console.log('tata');
  17022. return this.getSpacedPoints( divisions, closedPath );
  17023. }
  17024. divisions = divisions || 12;
  17025. var points = [];
  17026. var i, il, item, action, args;
  17027. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17028. laste, j,
  17029. t, tx, ty;
  17030. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17031. item = this.actions[ i ];
  17032. action = item.action;
  17033. args = item.args;
  17034. switch( action ) {
  17035. case THREE.PathActions.MOVE_TO:
  17036. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17037. break;
  17038. case THREE.PathActions.LINE_TO:
  17039. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17040. break;
  17041. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17042. cpx = args[ 2 ];
  17043. cpy = args[ 3 ];
  17044. cpx1 = args[ 0 ];
  17045. cpy1 = args[ 1 ];
  17046. if ( points.length > 0 ) {
  17047. laste = points[ points.length - 1 ];
  17048. cpx0 = laste.x;
  17049. cpy0 = laste.y;
  17050. } else {
  17051. laste = this.actions[ i - 1 ].args;
  17052. cpx0 = laste[ laste.length - 2 ];
  17053. cpy0 = laste[ laste.length - 1 ];
  17054. }
  17055. for ( j = 1; j <= divisions; j ++ ) {
  17056. t = j / divisions;
  17057. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17058. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17059. points.push( new THREE.Vector2( tx, ty ) );
  17060. }
  17061. break;
  17062. case THREE.PathActions.BEZIER_CURVE_TO:
  17063. cpx = args[ 4 ];
  17064. cpy = args[ 5 ];
  17065. cpx1 = args[ 0 ];
  17066. cpy1 = args[ 1 ];
  17067. cpx2 = args[ 2 ];
  17068. cpy2 = args[ 3 ];
  17069. if ( points.length > 0 ) {
  17070. laste = points[ points.length - 1 ];
  17071. cpx0 = laste.x;
  17072. cpy0 = laste.y;
  17073. } else {
  17074. laste = this.actions[ i - 1 ].args;
  17075. cpx0 = laste[ laste.length - 2 ];
  17076. cpy0 = laste[ laste.length - 1 ];
  17077. }
  17078. for ( j = 1; j <= divisions; j ++ ) {
  17079. t = j / divisions;
  17080. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17081. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17082. points.push( new THREE.Vector2( tx, ty ) );
  17083. }
  17084. break;
  17085. case THREE.PathActions.CSPLINE_THRU:
  17086. laste = this.actions[ i - 1 ].args;
  17087. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17088. var spts = [ last ];
  17089. var n = divisions * args[ 0 ].length;
  17090. spts = spts.concat( args[ 0 ] );
  17091. var spline = new THREE.SplineCurve( spts );
  17092. for ( j = 1; j <= n; j ++ ) {
  17093. points.push( spline.getPointAt( j / n ) ) ;
  17094. }
  17095. break;
  17096. case THREE.PathActions.ARC:
  17097. var aX = args[ 0 ], aY = args[ 1 ],
  17098. aRadius = args[ 2 ],
  17099. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17100. aClockwise = !!args[ 5 ];
  17101. var deltaAngle = aEndAngle - aStartAngle;
  17102. var angle;
  17103. var tdivisions = divisions * 2;
  17104. for ( j = 1; j <= tdivisions; j ++ ) {
  17105. t = j / tdivisions;
  17106. if ( ! aClockwise ) {
  17107. t = 1 - t;
  17108. }
  17109. angle = aStartAngle + t * deltaAngle;
  17110. tx = aX + aRadius * Math.cos( angle );
  17111. ty = aY + aRadius * Math.sin( angle );
  17112. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17113. points.push( new THREE.Vector2( tx, ty ) );
  17114. }
  17115. //console.log(points);
  17116. break;
  17117. case THREE.PathActions.ELLIPSE:
  17118. var aX = args[ 0 ], aY = args[ 1 ],
  17119. xRadius = args[ 2 ],
  17120. yRadius = args[ 3 ],
  17121. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17122. aClockwise = !!args[ 6 ];
  17123. var deltaAngle = aEndAngle - aStartAngle;
  17124. var angle;
  17125. var tdivisions = divisions * 2;
  17126. for ( j = 1; j <= tdivisions; j ++ ) {
  17127. t = j / tdivisions;
  17128. if ( ! aClockwise ) {
  17129. t = 1 - t;
  17130. }
  17131. angle = aStartAngle + t * deltaAngle;
  17132. tx = aX + xRadius * Math.cos( angle );
  17133. ty = aY + yRadius * Math.sin( angle );
  17134. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17135. points.push( new THREE.Vector2( tx, ty ) );
  17136. }
  17137. //console.log(points);
  17138. break;
  17139. } // end switch
  17140. }
  17141. // Normalize to remove the closing point by default.
  17142. var lastPoint = points[ points.length - 1];
  17143. var EPSILON = 0.0000000001;
  17144. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17145. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17146. points.splice( points.length - 1, 1);
  17147. if ( closedPath ) {
  17148. points.push( points[ 0 ] );
  17149. }
  17150. return points;
  17151. };
  17152. // Breaks path into shapes
  17153. THREE.Path.prototype.toShapes = function( isCCW ) {
  17154. var i, il, item, action, args;
  17155. var subPaths = [], lastPath = new THREE.Path();
  17156. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17157. item = this.actions[ i ];
  17158. args = item.args;
  17159. action = item.action;
  17160. if ( action == THREE.PathActions.MOVE_TO ) {
  17161. if ( lastPath.actions.length != 0 ) {
  17162. subPaths.push( lastPath );
  17163. lastPath = new THREE.Path();
  17164. }
  17165. }
  17166. lastPath[ action ].apply( lastPath, args );
  17167. }
  17168. if ( lastPath.actions.length != 0 ) {
  17169. subPaths.push( lastPath );
  17170. }
  17171. // console.log(subPaths);
  17172. if ( subPaths.length == 0 ) return [];
  17173. var solid, tmpPath, tmpShape, shapes = [];
  17174. if ( subPaths.length == 1) {
  17175. tmpPath = subPaths[0];
  17176. tmpShape = new THREE.Shape();
  17177. tmpShape.actions = tmpPath.actions;
  17178. tmpShape.curves = tmpPath.curves;
  17179. shapes.push( tmpShape );
  17180. return shapes;
  17181. }
  17182. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17183. holesFirst = isCCW ? !holesFirst : holesFirst;
  17184. // console.log("Holes first", holesFirst);
  17185. if ( holesFirst ) {
  17186. tmpShape = new THREE.Shape();
  17187. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17188. tmpPath = subPaths[ i ];
  17189. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17190. solid = isCCW ? !solid : solid;
  17191. if ( solid ) {
  17192. tmpShape.actions = tmpPath.actions;
  17193. tmpShape.curves = tmpPath.curves;
  17194. shapes.push( tmpShape );
  17195. tmpShape = new THREE.Shape();
  17196. //console.log('cw', i);
  17197. } else {
  17198. tmpShape.holes.push( tmpPath );
  17199. //console.log('ccw', i);
  17200. }
  17201. }
  17202. } else {
  17203. // Shapes first
  17204. tmpShape = undefined;
  17205. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17206. tmpPath = subPaths[ i ];
  17207. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17208. solid = isCCW ? !solid : solid;
  17209. if ( solid ) {
  17210. if ( tmpShape ) shapes.push( tmpShape );
  17211. tmpShape = new THREE.Shape();
  17212. tmpShape.actions = tmpPath.actions;
  17213. tmpShape.curves = tmpPath.curves;
  17214. } else {
  17215. tmpShape.holes.push( tmpPath );
  17216. }
  17217. }
  17218. shapes.push( tmpShape );
  17219. }
  17220. //console.log("shape", shapes);
  17221. return shapes;
  17222. };
  17223. /**
  17224. * @author zz85 / http://www.lab4games.net/zz85/blog
  17225. * Defines a 2d shape plane using paths.
  17226. **/
  17227. // STEP 1 Create a path.
  17228. // STEP 2 Turn path into shape.
  17229. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17230. // STEP 3a - Extract points from each shape, turn to vertices
  17231. // STEP 3b - Triangulate each shape, add faces.
  17232. THREE.Shape = function () {
  17233. THREE.Path.apply( this, arguments );
  17234. this.holes = [];
  17235. };
  17236. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17237. // Convenience method to return ExtrudeGeometry
  17238. THREE.Shape.prototype.extrude = function ( options ) {
  17239. var extruded = new THREE.ExtrudeGeometry( this, options );
  17240. return extruded;
  17241. };
  17242. // Convenience method to return ShapeGeometry
  17243. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17244. var geometry = new THREE.ShapeGeometry( this, options );
  17245. return geometry;
  17246. };
  17247. // Get points of holes
  17248. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17249. var i, il = this.holes.length, holesPts = [];
  17250. for ( i = 0; i < il; i ++ ) {
  17251. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17252. }
  17253. return holesPts;
  17254. };
  17255. // Get points of holes (spaced by regular distance)
  17256. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17257. var i, il = this.holes.length, holesPts = [];
  17258. for ( i = 0; i < il; i ++ ) {
  17259. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17260. }
  17261. return holesPts;
  17262. };
  17263. // Get points of shape and holes (keypoints based on segments parameter)
  17264. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17265. return {
  17266. shape: this.getTransformedPoints( divisions ),
  17267. holes: this.getPointsHoles( divisions )
  17268. };
  17269. };
  17270. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17271. if (this.useSpacedPoints) {
  17272. return this.extractAllSpacedPoints(divisions);
  17273. }
  17274. return this.extractAllPoints(divisions);
  17275. };
  17276. //
  17277. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17278. //
  17279. // return {
  17280. //
  17281. // shape: this.transform( bend, divisions ),
  17282. // holes: this.getPointsHoles( divisions, bend )
  17283. //
  17284. // };
  17285. //
  17286. // };
  17287. // Get points of shape and holes (spaced by regular distance)
  17288. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17289. return {
  17290. shape: this.getTransformedSpacedPoints( divisions ),
  17291. holes: this.getSpacedPointsHoles( divisions )
  17292. };
  17293. };
  17294. /**************************************************************
  17295. * Utils
  17296. **************************************************************/
  17297. THREE.Shape.Utils = {
  17298. /*
  17299. contour - array of vector2 for contour
  17300. holes - array of array of vector2
  17301. */
  17302. removeHoles: function ( contour, holes ) {
  17303. var shape = contour.concat(); // work on this shape
  17304. var allpoints = shape.concat();
  17305. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17306. var prevShapeVert, nextShapeVert,
  17307. prevHoleVert, nextHoleVert,
  17308. holeIndex, shapeIndex,
  17309. shapeId, shapeGroup,
  17310. h, h2,
  17311. hole, shortest, d,
  17312. p, pts1, pts2,
  17313. tmpShape1, tmpShape2,
  17314. tmpHole1, tmpHole2,
  17315. verts = [];
  17316. for ( h = 0; h < holes.length; h ++ ) {
  17317. hole = holes[ h ];
  17318. /*
  17319. shapeholes[ h ].concat(); // preserves original
  17320. holes.push( hole );
  17321. */
  17322. Array.prototype.push.apply( allpoints, hole );
  17323. shortest = Number.POSITIVE_INFINITY;
  17324. // Find the shortest pair of pts between shape and hole
  17325. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17326. // Using distanceToSquared() intead of distanceTo() should speed a little
  17327. // since running square roots operations are reduced.
  17328. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17329. pts1 = hole[ h2 ];
  17330. var dist = [];
  17331. for ( p = 0; p < shape.length; p++ ) {
  17332. pts2 = shape[ p ];
  17333. d = pts1.distanceToSquared( pts2 );
  17334. dist.push( d );
  17335. if ( d < shortest ) {
  17336. shortest = d;
  17337. holeIndex = h2;
  17338. shapeIndex = p;
  17339. }
  17340. }
  17341. }
  17342. //console.log("shortest", shortest, dist);
  17343. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17344. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17345. var areaapts = [
  17346. hole[ holeIndex ],
  17347. shape[ shapeIndex ],
  17348. shape[ prevShapeVert ]
  17349. ];
  17350. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17351. var areabpts = [
  17352. hole[ holeIndex ],
  17353. hole[ prevHoleVert ],
  17354. shape[ shapeIndex ]
  17355. ];
  17356. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17357. var shapeOffset = 1;
  17358. var holeOffset = -1;
  17359. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17360. shapeIndex += shapeOffset;
  17361. holeIndex += holeOffset;
  17362. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17363. shapeIndex %= shape.length;
  17364. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17365. holeIndex %= hole.length;
  17366. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17367. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17368. areaapts = [
  17369. hole[ holeIndex ],
  17370. shape[ shapeIndex ],
  17371. shape[ prevShapeVert ]
  17372. ];
  17373. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17374. areabpts = [
  17375. hole[ holeIndex ],
  17376. hole[ prevHoleVert ],
  17377. shape[ shapeIndex ]
  17378. ];
  17379. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17380. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17381. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17382. // In case areas are not correct.
  17383. //console.log("USE THIS");
  17384. shapeIndex = oldShapeIndex;
  17385. holeIndex = oldHoleIndex ;
  17386. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17387. shapeIndex %= shape.length;
  17388. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17389. holeIndex %= hole.length;
  17390. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17391. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17392. } else {
  17393. //console.log("USE THAT ")
  17394. }
  17395. tmpShape1 = shape.slice( 0, shapeIndex );
  17396. tmpShape2 = shape.slice( shapeIndex );
  17397. tmpHole1 = hole.slice( holeIndex );
  17398. tmpHole2 = hole.slice( 0, holeIndex );
  17399. // Should check orders here again?
  17400. var trianglea = [
  17401. hole[ holeIndex ],
  17402. shape[ shapeIndex ],
  17403. shape[ prevShapeVert ]
  17404. ];
  17405. var triangleb = [
  17406. hole[ holeIndex ] ,
  17407. hole[ prevHoleVert ],
  17408. shape[ shapeIndex ]
  17409. ];
  17410. verts.push( trianglea );
  17411. verts.push( triangleb );
  17412. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17413. }
  17414. return {
  17415. shape:shape, /* shape with no holes */
  17416. isolatedPts: verts, /* isolated faces */
  17417. allpoints: allpoints
  17418. }
  17419. },
  17420. triangulateShape: function ( contour, holes ) {
  17421. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17422. var shape = shapeWithoutHoles.shape,
  17423. allpoints = shapeWithoutHoles.allpoints,
  17424. isolatedPts = shapeWithoutHoles.isolatedPts;
  17425. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17426. // 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.
  17427. //console.log( "triangles",triangles, triangles.length );
  17428. //console.log( "allpoints",allpoints, allpoints.length );
  17429. var i, il, f, face,
  17430. key, index,
  17431. allPointsMap = {},
  17432. isolatedPointsMap = {};
  17433. // prepare all points map
  17434. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17435. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17436. if ( allPointsMap[ key ] !== undefined ) {
  17437. console.log( "Duplicate point", key );
  17438. }
  17439. allPointsMap[ key ] = i;
  17440. }
  17441. // check all face vertices against all points map
  17442. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17443. face = triangles[ i ];
  17444. for ( f = 0; f < 3; f ++ ) {
  17445. key = face[ f ].x + ":" + face[ f ].y;
  17446. index = allPointsMap[ key ];
  17447. if ( index !== undefined ) {
  17448. face[ f ] = index;
  17449. }
  17450. }
  17451. }
  17452. // check isolated points vertices against all points map
  17453. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17454. face = isolatedPts[ i ];
  17455. for ( f = 0; f < 3; f ++ ) {
  17456. key = face[ f ].x + ":" + face[ f ].y;
  17457. index = allPointsMap[ key ];
  17458. if ( index !== undefined ) {
  17459. face[ f ] = index;
  17460. }
  17461. }
  17462. }
  17463. return triangles.concat( isolatedPts );
  17464. }, // end triangulate shapes
  17465. /*
  17466. triangulate2 : function( pts, holes ) {
  17467. // For use with Poly2Tri.js
  17468. var allpts = pts.concat();
  17469. var shape = [];
  17470. for (var p in pts) {
  17471. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17472. }
  17473. var swctx = new js.poly2tri.SweepContext(shape);
  17474. for (var h in holes) {
  17475. var aHole = holes[h];
  17476. var newHole = []
  17477. for (i in aHole) {
  17478. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17479. allpts.push(aHole[i]);
  17480. }
  17481. swctx.AddHole(newHole);
  17482. }
  17483. var find;
  17484. var findIndexForPt = function (pt) {
  17485. find = new THREE.Vector2(pt.x, pt.y);
  17486. var p;
  17487. for (p=0, pl = allpts.length; p<pl; p++) {
  17488. if (allpts[p].equals(find)) return p;
  17489. }
  17490. return -1;
  17491. };
  17492. // triangulate
  17493. js.poly2tri.sweep.Triangulate(swctx);
  17494. var triangles = swctx.GetTriangles();
  17495. var tr ;
  17496. var facesPts = [];
  17497. for (var t in triangles) {
  17498. tr = triangles[t];
  17499. facesPts.push([
  17500. findIndexForPt(tr.GetPoint(0)),
  17501. findIndexForPt(tr.GetPoint(1)),
  17502. findIndexForPt(tr.GetPoint(2))
  17503. ]);
  17504. }
  17505. // console.log(facesPts);
  17506. // console.log("triangles", triangles.length, triangles);
  17507. // Returns array of faces with 3 element each
  17508. return facesPts;
  17509. },
  17510. */
  17511. isClockWise: function ( pts ) {
  17512. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17513. },
  17514. // Bezier Curves formulas obtained from
  17515. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17516. // Quad Bezier Functions
  17517. b2p0: function ( t, p ) {
  17518. var k = 1 - t;
  17519. return k * k * p;
  17520. },
  17521. b2p1: function ( t, p ) {
  17522. return 2 * ( 1 - t ) * t * p;
  17523. },
  17524. b2p2: function ( t, p ) {
  17525. return t * t * p;
  17526. },
  17527. b2: function ( t, p0, p1, p2 ) {
  17528. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17529. },
  17530. // Cubic Bezier Functions
  17531. b3p0: function ( t, p ) {
  17532. var k = 1 - t;
  17533. return k * k * k * p;
  17534. },
  17535. b3p1: function ( t, p ) {
  17536. var k = 1 - t;
  17537. return 3 * k * k * t * p;
  17538. },
  17539. b3p2: function ( t, p ) {
  17540. var k = 1 - t;
  17541. return 3 * k * t * t * p;
  17542. },
  17543. b3p3: function ( t, p ) {
  17544. return t * t * t * p;
  17545. },
  17546. b3: function ( t, p0, p1, p2, p3 ) {
  17547. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17548. }
  17549. };
  17550. /**************************************************************
  17551. * Line
  17552. **************************************************************/
  17553. THREE.LineCurve = function ( v1, v2 ) {
  17554. this.v1 = v1;
  17555. this.v2 = v2;
  17556. };
  17557. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17558. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17559. var point = this.v2.clone().sub(this.v1);
  17560. point.multiplyScalar( t ).add( this.v1 );
  17561. return point;
  17562. };
  17563. // Line curve is linear, so we can overwrite default getPointAt
  17564. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17565. return this.getPoint( u );
  17566. };
  17567. THREE.LineCurve.prototype.getTangent = function( t ) {
  17568. var tangent = this.v2.clone().sub(this.v1);
  17569. return tangent.normalize();
  17570. };
  17571. /**************************************************************
  17572. * Quadratic Bezier curve
  17573. **************************************************************/
  17574. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17575. this.v0 = v0;
  17576. this.v1 = v1;
  17577. this.v2 = v2;
  17578. };
  17579. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17580. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17581. var tx, ty;
  17582. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17583. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17584. return new THREE.Vector2( tx, ty );
  17585. };
  17586. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17587. var tx, ty;
  17588. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17589. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17590. // returns unit vector
  17591. var tangent = new THREE.Vector2( tx, ty );
  17592. tangent.normalize();
  17593. return tangent;
  17594. };
  17595. /**************************************************************
  17596. * Cubic Bezier curve
  17597. **************************************************************/
  17598. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17599. this.v0 = v0;
  17600. this.v1 = v1;
  17601. this.v2 = v2;
  17602. this.v3 = v3;
  17603. };
  17604. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17605. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17606. var tx, ty;
  17607. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17608. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17609. return new THREE.Vector2( tx, ty );
  17610. };
  17611. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17612. var tx, ty;
  17613. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17614. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17615. var tangent = new THREE.Vector2( tx, ty );
  17616. tangent.normalize();
  17617. return tangent;
  17618. };
  17619. /**************************************************************
  17620. * Spline curve
  17621. **************************************************************/
  17622. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17623. this.points = (points == undefined) ? [] : points;
  17624. };
  17625. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17626. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17627. var v = new THREE.Vector2();
  17628. var c = [];
  17629. var points = this.points, point, intPoint, weight;
  17630. point = ( points.length - 1 ) * t;
  17631. intPoint = Math.floor( point );
  17632. weight = point - intPoint;
  17633. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17634. c[ 1 ] = intPoint;
  17635. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17636. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17637. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17638. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17639. return v;
  17640. };
  17641. /**************************************************************
  17642. * Ellipse curve
  17643. **************************************************************/
  17644. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17645. this.aX = aX;
  17646. this.aY = aY;
  17647. this.xRadius = xRadius;
  17648. this.yRadius = yRadius;
  17649. this.aStartAngle = aStartAngle;
  17650. this.aEndAngle = aEndAngle;
  17651. this.aClockwise = aClockwise;
  17652. };
  17653. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17654. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17655. var angle;
  17656. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17657. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17658. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17659. if ( this.aClockwise === true ) {
  17660. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17661. } else {
  17662. angle = this.aStartAngle + t * deltaAngle;
  17663. }
  17664. var tx = this.aX + this.xRadius * Math.cos( angle );
  17665. var ty = this.aY + this.yRadius * Math.sin( angle );
  17666. return new THREE.Vector2( tx, ty );
  17667. };
  17668. /**************************************************************
  17669. * Arc curve
  17670. **************************************************************/
  17671. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17672. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17673. };
  17674. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17675. /**************************************************************
  17676. * Line3D
  17677. **************************************************************/
  17678. THREE.LineCurve3 = THREE.Curve.create(
  17679. function ( v1, v2 ) {
  17680. this.v1 = v1;
  17681. this.v2 = v2;
  17682. },
  17683. function ( t ) {
  17684. var r = new THREE.Vector3();
  17685. r.subVectors( this.v2, this.v1 ); // diff
  17686. r.multiplyScalar( t );
  17687. r.add( this.v1 );
  17688. return r;
  17689. }
  17690. );
  17691. /**************************************************************
  17692. * Quadratic Bezier 3D curve
  17693. **************************************************************/
  17694. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17695. function ( v0, v1, v2 ) {
  17696. this.v0 = v0;
  17697. this.v1 = v1;
  17698. this.v2 = v2;
  17699. },
  17700. function ( t ) {
  17701. var tx, ty, tz;
  17702. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17703. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17704. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17705. return new THREE.Vector3( tx, ty, tz );
  17706. }
  17707. );
  17708. /**************************************************************
  17709. * Cubic Bezier 3D curve
  17710. **************************************************************/
  17711. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17712. function ( v0, v1, v2, v3 ) {
  17713. this.v0 = v0;
  17714. this.v1 = v1;
  17715. this.v2 = v2;
  17716. this.v3 = v3;
  17717. },
  17718. function ( t ) {
  17719. var tx, ty, tz;
  17720. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17721. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17722. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17723. return new THREE.Vector3( tx, ty, tz );
  17724. }
  17725. );
  17726. /**************************************************************
  17727. * Spline 3D curve
  17728. **************************************************************/
  17729. THREE.SplineCurve3 = THREE.Curve.create(
  17730. function ( points /* array of Vector3 */) {
  17731. this.points = (points == undefined) ? [] : points;
  17732. },
  17733. function ( t ) {
  17734. var v = new THREE.Vector3();
  17735. var c = [];
  17736. var points = this.points, point, intPoint, weight;
  17737. point = ( points.length - 1 ) * t;
  17738. intPoint = Math.floor( point );
  17739. weight = point - intPoint;
  17740. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17741. c[ 1 ] = intPoint;
  17742. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17743. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17744. var pt0 = points[ c[0] ],
  17745. pt1 = points[ c[1] ],
  17746. pt2 = points[ c[2] ],
  17747. pt3 = points[ c[3] ];
  17748. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17749. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17750. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17751. return v;
  17752. }
  17753. );
  17754. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  17755. // var v = new THREE.Vector3();
  17756. // var c = [];
  17757. // var points = this.points, point, intPoint, weight;
  17758. // point = ( points.length - 1 ) * t;
  17759. // intPoint = Math.floor( point );
  17760. // weight = point - intPoint;
  17761. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17762. // c[ 1 ] = intPoint;
  17763. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17764. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17765. // var pt0 = points[ c[0] ],
  17766. // pt1 = points[ c[1] ],
  17767. // pt2 = points[ c[2] ],
  17768. // pt3 = points[ c[3] ];
  17769. // // t = weight;
  17770. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  17771. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  17772. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  17773. // return v;
  17774. // }
  17775. /**************************************************************
  17776. * Closed Spline 3D curve
  17777. **************************************************************/
  17778. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  17779. function ( points /* array of Vector3 */) {
  17780. this.points = (points == undefined) ? [] : points;
  17781. },
  17782. function ( t ) {
  17783. var v = new THREE.Vector3();
  17784. var c = [];
  17785. var points = this.points, point, intPoint, weight;
  17786. point = ( points.length - 0 ) * t;
  17787. // This needs to be from 0-length +1
  17788. intPoint = Math.floor( point );
  17789. weight = point - intPoint;
  17790. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  17791. c[ 0 ] = ( intPoint - 1 ) % points.length;
  17792. c[ 1 ] = ( intPoint ) % points.length;
  17793. c[ 2 ] = ( intPoint + 1 ) % points.length;
  17794. c[ 3 ] = ( intPoint + 2 ) % points.length;
  17795. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17796. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17797. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  17798. return v;
  17799. }
  17800. );
  17801. /**
  17802. * @author mikael emtinger / http://gomo.se/
  17803. */
  17804. THREE.AnimationHandler = (function() {
  17805. var playing = [];
  17806. var library = {};
  17807. var that = {};
  17808. //--- update ---
  17809. that.update = function( deltaTimeMS ) {
  17810. for( var i = 0; i < playing.length; i ++ )
  17811. playing[ i ].update( deltaTimeMS );
  17812. };
  17813. //--- add ---
  17814. that.addToUpdate = function( animation ) {
  17815. if ( playing.indexOf( animation ) === -1 )
  17816. playing.push( animation );
  17817. };
  17818. //--- remove ---
  17819. that.removeFromUpdate = function( animation ) {
  17820. var index = playing.indexOf( animation );
  17821. if( index !== -1 )
  17822. playing.splice( index, 1 );
  17823. };
  17824. //--- add ---
  17825. that.add = function( data ) {
  17826. if ( library[ data.name ] !== undefined )
  17827. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17828. library[ data.name ] = data;
  17829. initData( data );
  17830. };
  17831. //--- get ---
  17832. that.get = function( name ) {
  17833. if ( typeof name === "string" ) {
  17834. if ( library[ name ] ) {
  17835. return library[ name ];
  17836. } else {
  17837. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17838. return null;
  17839. }
  17840. } else {
  17841. // todo: add simple tween library
  17842. }
  17843. };
  17844. //--- parse ---
  17845. that.parse = function( root ) {
  17846. // setup hierarchy
  17847. var hierarchy = [];
  17848. if ( root instanceof THREE.SkinnedMesh ) {
  17849. for( var b = 0; b < root.bones.length; b++ ) {
  17850. hierarchy.push( root.bones[ b ] );
  17851. }
  17852. } else {
  17853. parseRecurseHierarchy( root, hierarchy );
  17854. }
  17855. return hierarchy;
  17856. };
  17857. var parseRecurseHierarchy = function( root, hierarchy ) {
  17858. hierarchy.push( root );
  17859. for( var c = 0; c < root.children.length; c++ )
  17860. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17861. }
  17862. //--- init data ---
  17863. var initData = function( data ) {
  17864. if( data.initialized === true )
  17865. return;
  17866. // loop through all keys
  17867. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17868. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17869. // remove minus times
  17870. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17871. data.hierarchy[ h ].keys[ k ].time = 0;
  17872. // create quaternions
  17873. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17874. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17875. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17876. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17877. }
  17878. }
  17879. // prepare morph target keys
  17880. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17881. // get all used
  17882. var usedMorphTargets = {};
  17883. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17884. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17885. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17886. usedMorphTargets[ morphTargetName ] = -1;
  17887. }
  17888. }
  17889. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17890. // set all used on all frames
  17891. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17892. var influences = {};
  17893. for ( var morphTargetName in usedMorphTargets ) {
  17894. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17895. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17896. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17897. break;
  17898. }
  17899. }
  17900. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17901. influences[ morphTargetName ] = 0;
  17902. }
  17903. }
  17904. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17905. }
  17906. }
  17907. // remove all keys that are on the same time
  17908. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17909. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17910. data.hierarchy[ h ].keys.splice( k, 1 );
  17911. k --;
  17912. }
  17913. }
  17914. // set index
  17915. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17916. data.hierarchy[ h ].keys[ k ].index = k;
  17917. }
  17918. }
  17919. // JIT
  17920. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17921. data.JIT = {};
  17922. data.JIT.hierarchy = [];
  17923. for( var h = 0; h < data.hierarchy.length; h ++ )
  17924. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17925. // done
  17926. data.initialized = true;
  17927. };
  17928. // interpolation types
  17929. that.LINEAR = 0;
  17930. that.CATMULLROM = 1;
  17931. that.CATMULLROM_FORWARD = 2;
  17932. return that;
  17933. }());
  17934. /**
  17935. * @author mikael emtinger / http://gomo.se/
  17936. * @author mrdoob / http://mrdoob.com/
  17937. * @author alteredq / http://alteredqualia.com/
  17938. */
  17939. THREE.Animation = function ( root, name, interpolationType ) {
  17940. this.root = root;
  17941. this.data = THREE.AnimationHandler.get( name );
  17942. this.hierarchy = THREE.AnimationHandler.parse( root );
  17943. this.currentTime = 0;
  17944. this.timeScale = 1;
  17945. this.isPlaying = false;
  17946. this.isPaused = true;
  17947. this.loop = true;
  17948. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17949. this.points = [];
  17950. this.target = new THREE.Vector3();
  17951. };
  17952. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17953. if ( this.isPlaying === false ) {
  17954. this.isPlaying = true;
  17955. this.loop = loop !== undefined ? loop : true;
  17956. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17957. // reset key cache
  17958. var h, hl = this.hierarchy.length,
  17959. object;
  17960. for ( h = 0; h < hl; h ++ ) {
  17961. object = this.hierarchy[ h ];
  17962. object.matrixAutoUpdate = true;
  17963. if ( object.animationCache === undefined ) {
  17964. object.animationCache = {};
  17965. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17966. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17967. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17968. }
  17969. var prevKey = object.animationCache.prevKey;
  17970. var nextKey = object.animationCache.nextKey;
  17971. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17972. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17973. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17974. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17975. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17976. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17977. }
  17978. this.update( 0 );
  17979. }
  17980. this.isPaused = false;
  17981. THREE.AnimationHandler.addToUpdate( this );
  17982. };
  17983. THREE.Animation.prototype.pause = function() {
  17984. if ( this.isPaused === true ) {
  17985. THREE.AnimationHandler.addToUpdate( this );
  17986. } else {
  17987. THREE.AnimationHandler.removeFromUpdate( this );
  17988. }
  17989. this.isPaused = !this.isPaused;
  17990. };
  17991. THREE.Animation.prototype.stop = function() {
  17992. this.isPlaying = false;
  17993. this.isPaused = false;
  17994. THREE.AnimationHandler.removeFromUpdate( this );
  17995. };
  17996. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17997. // early out
  17998. if ( this.isPlaying === false ) return;
  17999. // vars
  18000. var types = [ "pos", "rot", "scl" ];
  18001. var type;
  18002. var scale;
  18003. var vector;
  18004. var prevXYZ, nextXYZ;
  18005. var prevKey, nextKey;
  18006. var object;
  18007. var animationCache;
  18008. var frame;
  18009. var JIThierarchy = this.data.JIT.hierarchy;
  18010. var currentTime, unloopedCurrentTime;
  18011. var currentPoint, forwardPoint, angle;
  18012. this.currentTime += deltaTimeMS * this.timeScale;
  18013. unloopedCurrentTime = this.currentTime;
  18014. // Mod operation fails on floats
  18015. // was this supposed to be in frames?
  18016. while ( this.currentTime > this.data.length ) {
  18017. this.currentTime -= this.data.length;
  18018. }
  18019. currentTime = this.currentTime = this.currentTime % this.data.length;
  18020. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18021. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18022. object = this.hierarchy[ h ];
  18023. animationCache = object.animationCache;
  18024. // loop through pos/rot/scl
  18025. for ( var t = 0; t < 3; t ++ ) {
  18026. // get keys
  18027. type = types[ t ];
  18028. prevKey = animationCache.prevKey[ type ];
  18029. nextKey = animationCache.nextKey[ type ];
  18030. // switch keys?
  18031. if ( nextKey.time <= unloopedCurrentTime ) {
  18032. // did we loop?
  18033. if ( currentTime <= unloopedCurrentTime ) {
  18034. if ( this.loop ) {
  18035. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18036. nextKey = this.getNextKeyWith( type, h, 1 );
  18037. // if ( nextKey.index < prevKey.index ) then we have wrapped over the end, and nextKey.time < currentTime will loop forever
  18038. while ( nextKey !== null && nextKey.time < currentTime && nextKey.index > prevKey.index) {
  18039. prevKey = nextKey;
  18040. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18041. }
  18042. } else {
  18043. this.stop();
  18044. return;
  18045. }
  18046. } else {
  18047. do {
  18048. prevKey = nextKey;
  18049. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18050. } while ( nextKey !== null && nextKey.time < currentTime && nextKey.index > prevKey.index )
  18051. // if ( nextKey.index < prevKey.index ) then we have wrapped over the end, and nextKey.time < currentTime will loop forever
  18052. }
  18053. animationCache.prevKey[ type ] = prevKey;
  18054. animationCache.nextKey[ type ] = nextKey;
  18055. }
  18056. object.matrixAutoUpdate = true;
  18057. object.matrixWorldNeedsUpdate = true;
  18058. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18059. prevXYZ = prevKey[ type ];
  18060. nextXYZ = nextKey[ type ];
  18061. // check scale error
  18062. if ( scale < 0 || scale > 1 ) {
  18063. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18064. scale = scale < 0 ? 0 : 1;
  18065. }
  18066. // interpolate
  18067. if ( type === "pos" ) {
  18068. vector = object.position;
  18069. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18070. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18071. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18072. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18073. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18074. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18075. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18076. this.points[ 1 ] = prevXYZ;
  18077. this.points[ 2 ] = nextXYZ;
  18078. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18079. scale = scale * 0.33 + 0.33;
  18080. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18081. vector.x = currentPoint[ 0 ];
  18082. vector.y = currentPoint[ 1 ];
  18083. vector.z = currentPoint[ 2 ];
  18084. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18085. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18086. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18087. this.target.sub( vector );
  18088. this.target.y = 0;
  18089. this.target.normalize();
  18090. angle = Math.atan2( this.target.x, this.target.z );
  18091. object.rotation.set( 0, angle, 0 );
  18092. }
  18093. }
  18094. } else if ( type === "rot" ) {
  18095. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18096. } else if ( type === "scl" ) {
  18097. vector = object.scale;
  18098. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18099. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18100. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18101. }
  18102. }
  18103. }
  18104. };
  18105. // Catmull-Rom spline
  18106. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18107. var c = [], v3 = [],
  18108. point, intPoint, weight, w2, w3,
  18109. pa, pb, pc, pd;
  18110. point = ( points.length - 1 ) * scale;
  18111. intPoint = Math.floor( point );
  18112. weight = point - intPoint;
  18113. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18114. c[ 1 ] = intPoint;
  18115. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18116. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18117. pa = points[ c[ 0 ] ];
  18118. pb = points[ c[ 1 ] ];
  18119. pc = points[ c[ 2 ] ];
  18120. pd = points[ c[ 3 ] ];
  18121. w2 = weight * weight;
  18122. w3 = weight * w2;
  18123. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18124. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18125. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18126. return v3;
  18127. };
  18128. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18129. var v0 = ( p2 - p0 ) * 0.5,
  18130. v1 = ( p3 - p1 ) * 0.5;
  18131. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18132. };
  18133. // Get next key with
  18134. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18135. var keys = this.data.hierarchy[ h ].keys;
  18136. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18137. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18138. key = key < keys.length - 1 ? key : keys.length - 1;
  18139. } else {
  18140. key = key % keys.length;
  18141. }
  18142. for ( ; key < keys.length; key++ ) {
  18143. if ( keys[ key ][ type ] !== undefined ) {
  18144. return keys[ key ];
  18145. }
  18146. }
  18147. return this.data.hierarchy[ h ].keys[ 0 ];
  18148. };
  18149. // Get previous key with
  18150. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18151. var keys = this.data.hierarchy[ h ].keys;
  18152. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18153. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18154. key = key > 0 ? key : 0;
  18155. } else {
  18156. key = key >= 0 ? key : key + keys.length;
  18157. }
  18158. for ( ; key >= 0; key -- ) {
  18159. if ( keys[ key ][ type ] !== undefined ) {
  18160. return keys[ key ];
  18161. }
  18162. }
  18163. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18164. };
  18165. /**
  18166. * @author mikael emtinger / http://gomo.se/
  18167. * @author mrdoob / http://mrdoob.com/
  18168. * @author alteredq / http://alteredqualia.com/
  18169. * @author khang duong
  18170. * @author erik kitson
  18171. */
  18172. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18173. this.root = root;
  18174. this.data = THREE.AnimationHandler.get( data );
  18175. this.hierarchy = THREE.AnimationHandler.parse( root );
  18176. this.currentTime = 0;
  18177. this.timeScale = 0.001;
  18178. this.isPlaying = false;
  18179. this.isPaused = true;
  18180. this.loop = true;
  18181. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18182. // initialize to first keyframes
  18183. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18184. var keys = this.data.hierarchy[h].keys,
  18185. sids = this.data.hierarchy[h].sids,
  18186. obj = this.hierarchy[h];
  18187. if ( keys.length && sids ) {
  18188. for ( var s = 0; s < sids.length; s++ ) {
  18189. var sid = sids[ s ],
  18190. next = this.getNextKeyWith( sid, h, 0 );
  18191. if ( next ) {
  18192. next.apply( sid );
  18193. }
  18194. }
  18195. obj.matrixAutoUpdate = false;
  18196. this.data.hierarchy[h].node.updateMatrix();
  18197. obj.matrixWorldNeedsUpdate = true;
  18198. }
  18199. }
  18200. };
  18201. // Play
  18202. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18203. if( !this.isPlaying ) {
  18204. this.isPlaying = true;
  18205. this.loop = loop !== undefined ? loop : true;
  18206. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18207. this.startTimeMs = startTimeMS;
  18208. this.startTime = 10000000;
  18209. this.endTime = -this.startTime;
  18210. // reset key cache
  18211. var h, hl = this.hierarchy.length,
  18212. object,
  18213. node;
  18214. for ( h = 0; h < hl; h++ ) {
  18215. object = this.hierarchy[ h ];
  18216. node = this.data.hierarchy[ h ];
  18217. if ( node.animationCache === undefined ) {
  18218. node.animationCache = {};
  18219. node.animationCache.prevKey = null;
  18220. node.animationCache.nextKey = null;
  18221. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18222. }
  18223. var keys = this.data.hierarchy[h].keys;
  18224. if (keys.length) {
  18225. node.animationCache.prevKey = keys[ 0 ];
  18226. node.animationCache.nextKey = keys[ 1 ];
  18227. this.startTime = Math.min( keys[0].time, this.startTime );
  18228. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18229. }
  18230. }
  18231. this.update( 0 );
  18232. }
  18233. this.isPaused = false;
  18234. THREE.AnimationHandler.addToUpdate( this );
  18235. };
  18236. // Pause
  18237. THREE.KeyFrameAnimation.prototype.pause = function() {
  18238. if( this.isPaused ) {
  18239. THREE.AnimationHandler.addToUpdate( this );
  18240. } else {
  18241. THREE.AnimationHandler.removeFromUpdate( this );
  18242. }
  18243. this.isPaused = !this.isPaused;
  18244. };
  18245. // Stop
  18246. THREE.KeyFrameAnimation.prototype.stop = function() {
  18247. this.isPlaying = false;
  18248. this.isPaused = false;
  18249. THREE.AnimationHandler.removeFromUpdate( this );
  18250. // reset JIT matrix and remove cache
  18251. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18252. var obj = this.hierarchy[ h ];
  18253. var node = this.data.hierarchy[ h ];
  18254. if ( node.animationCache !== undefined ) {
  18255. var original = node.animationCache.originalMatrix;
  18256. if( obj instanceof THREE.Bone ) {
  18257. original.copy( obj.skinMatrix );
  18258. obj.skinMatrix = original;
  18259. } else {
  18260. original.copy( obj.matrix );
  18261. obj.matrix = original;
  18262. }
  18263. delete node.animationCache;
  18264. }
  18265. }
  18266. };
  18267. // Update
  18268. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18269. // early out
  18270. if( !this.isPlaying ) return;
  18271. // vars
  18272. var prevKey, nextKey;
  18273. var object;
  18274. var node;
  18275. var frame;
  18276. var JIThierarchy = this.data.JIT.hierarchy;
  18277. var currentTime, unloopedCurrentTime;
  18278. var looped;
  18279. // update
  18280. this.currentTime += deltaTimeMS * this.timeScale;
  18281. unloopedCurrentTime = this.currentTime;
  18282. currentTime = this.currentTime = this.currentTime % this.data.length;
  18283. // if looped around, the current time should be based on the startTime
  18284. if ( currentTime < this.startTimeMs ) {
  18285. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18286. }
  18287. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18288. looped = currentTime < unloopedCurrentTime;
  18289. if ( looped && !this.loop ) {
  18290. // Set the animation to the last keyframes and stop
  18291. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18292. var keys = this.data.hierarchy[h].keys,
  18293. sids = this.data.hierarchy[h].sids,
  18294. end = keys.length-1,
  18295. obj = this.hierarchy[h];
  18296. if ( keys.length ) {
  18297. for ( var s = 0; s < sids.length; s++ ) {
  18298. var sid = sids[ s ],
  18299. prev = this.getPrevKeyWith( sid, h, end );
  18300. if ( prev ) {
  18301. prev.apply( sid );
  18302. }
  18303. }
  18304. this.data.hierarchy[h].node.updateMatrix();
  18305. obj.matrixWorldNeedsUpdate = true;
  18306. }
  18307. }
  18308. this.stop();
  18309. return;
  18310. }
  18311. // check pre-infinity
  18312. if ( currentTime < this.startTime ) {
  18313. return;
  18314. }
  18315. // update
  18316. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18317. object = this.hierarchy[ h ];
  18318. node = this.data.hierarchy[ h ];
  18319. var keys = node.keys,
  18320. animationCache = node.animationCache;
  18321. // use JIT?
  18322. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18323. if( object instanceof THREE.Bone ) {
  18324. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18325. object.matrixWorldNeedsUpdate = false;
  18326. } else {
  18327. object.matrix = JIThierarchy[ h ][ frame ];
  18328. object.matrixWorldNeedsUpdate = true;
  18329. }
  18330. // use interpolation
  18331. } else if ( keys.length ) {
  18332. // make sure so original matrix and not JIT matrix is set
  18333. if ( this.JITCompile && animationCache ) {
  18334. if( object instanceof THREE.Bone ) {
  18335. object.skinMatrix = animationCache.originalMatrix;
  18336. } else {
  18337. object.matrix = animationCache.originalMatrix;
  18338. }
  18339. }
  18340. prevKey = animationCache.prevKey;
  18341. nextKey = animationCache.nextKey;
  18342. if ( prevKey && nextKey ) {
  18343. // switch keys?
  18344. if ( nextKey.time <= unloopedCurrentTime ) {
  18345. // did we loop?
  18346. if ( looped && this.loop ) {
  18347. prevKey = keys[ 0 ];
  18348. nextKey = keys[ 1 ];
  18349. while ( nextKey.time < currentTime ) {
  18350. prevKey = nextKey;
  18351. nextKey = keys[ prevKey.index + 1 ];
  18352. }
  18353. } else if ( !looped ) {
  18354. var lastIndex = keys.length - 1;
  18355. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18356. prevKey = nextKey;
  18357. nextKey = keys[ prevKey.index + 1 ];
  18358. }
  18359. }
  18360. animationCache.prevKey = prevKey;
  18361. animationCache.nextKey = nextKey;
  18362. }
  18363. if(nextKey.time >= currentTime)
  18364. prevKey.interpolate( nextKey, currentTime );
  18365. else
  18366. prevKey.interpolate( nextKey, nextKey.time);
  18367. }
  18368. this.data.hierarchy[h].node.updateMatrix();
  18369. object.matrixWorldNeedsUpdate = true;
  18370. }
  18371. }
  18372. // update JIT?
  18373. if ( this.JITCompile ) {
  18374. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18375. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18376. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18377. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18378. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18379. } else {
  18380. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18381. }
  18382. }
  18383. }
  18384. }
  18385. };
  18386. // Get next key with
  18387. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18388. var keys = this.data.hierarchy[ h ].keys;
  18389. key = key % keys.length;
  18390. for ( ; key < keys.length; key++ ) {
  18391. if ( keys[ key ].hasTarget( sid ) ) {
  18392. return keys[ key ];
  18393. }
  18394. }
  18395. return keys[ 0 ];
  18396. };
  18397. // Get previous key with
  18398. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18399. var keys = this.data.hierarchy[ h ].keys;
  18400. key = key >= 0 ? key : key + keys.length;
  18401. for ( ; key >= 0; key-- ) {
  18402. if ( keys[ key ].hasTarget( sid ) ) {
  18403. return keys[ key ];
  18404. }
  18405. }
  18406. return keys[ keys.length - 1 ];
  18407. };
  18408. /**
  18409. * Camera for rendering cube maps
  18410. * - renders scene into axis-aligned cube
  18411. *
  18412. * @author alteredq / http://alteredqualia.com/
  18413. */
  18414. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18415. THREE.Object3D.call( this );
  18416. var fov = 90, aspect = 1;
  18417. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18418. cameraPX.up.set( 0, -1, 0 );
  18419. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18420. this.add( cameraPX );
  18421. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18422. cameraNX.up.set( 0, -1, 0 );
  18423. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18424. this.add( cameraNX );
  18425. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18426. cameraPY.up.set( 0, 0, 1 );
  18427. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18428. this.add( cameraPY );
  18429. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18430. cameraNY.up.set( 0, 0, -1 );
  18431. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18432. this.add( cameraNY );
  18433. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18434. cameraPZ.up.set( 0, -1, 0 );
  18435. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18436. this.add( cameraPZ );
  18437. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18438. cameraNZ.up.set( 0, -1, 0 );
  18439. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18440. this.add( cameraNZ );
  18441. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18442. this.updateCubeMap = function ( renderer, scene ) {
  18443. var renderTarget = this.renderTarget;
  18444. var generateMipmaps = renderTarget.generateMipmaps;
  18445. renderTarget.generateMipmaps = false;
  18446. renderTarget.activeCubeFace = 0;
  18447. renderer.render( scene, cameraPX, renderTarget );
  18448. renderTarget.activeCubeFace = 1;
  18449. renderer.render( scene, cameraNX, renderTarget );
  18450. renderTarget.activeCubeFace = 2;
  18451. renderer.render( scene, cameraPY, renderTarget );
  18452. renderTarget.activeCubeFace = 3;
  18453. renderer.render( scene, cameraNY, renderTarget );
  18454. renderTarget.activeCubeFace = 4;
  18455. renderer.render( scene, cameraPZ, renderTarget );
  18456. renderTarget.generateMipmaps = generateMipmaps;
  18457. renderTarget.activeCubeFace = 5;
  18458. renderer.render( scene, cameraNZ, renderTarget );
  18459. };
  18460. };
  18461. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18462. /*
  18463. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18464. *
  18465. * A general perpose camera, for setting FOV, Lens Focal Length,
  18466. * and switching between perspective and orthographic views easily.
  18467. * Use this only if you do not wish to manage
  18468. * both a Orthographic and Perspective Camera
  18469. *
  18470. */
  18471. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18472. THREE.Camera.call( this );
  18473. this.fov = fov;
  18474. this.left = -width / 2;
  18475. this.right = width / 2
  18476. this.top = height / 2;
  18477. this.bottom = -height / 2;
  18478. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18479. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18480. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18481. this.zoom = 1;
  18482. this.toPerspective();
  18483. var aspect = width/height;
  18484. };
  18485. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18486. THREE.CombinedCamera.prototype.toPerspective = function () {
  18487. // Switches to the Perspective Camera
  18488. this.near = this.cameraP.near;
  18489. this.far = this.cameraP.far;
  18490. this.cameraP.fov = this.fov / this.zoom ;
  18491. this.cameraP.updateProjectionMatrix();
  18492. this.projectionMatrix = this.cameraP.projectionMatrix;
  18493. this.inPerspectiveMode = true;
  18494. this.inOrthographicMode = false;
  18495. };
  18496. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18497. // Switches to the Orthographic camera estimating viewport from Perspective
  18498. var fov = this.fov;
  18499. var aspect = this.cameraP.aspect;
  18500. var near = this.cameraP.near;
  18501. var far = this.cameraP.far;
  18502. // The size that we set is the mid plane of the viewing frustum
  18503. var hyperfocus = ( near + far ) / 2;
  18504. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18505. var planeHeight = 2 * halfHeight;
  18506. var planeWidth = planeHeight * aspect;
  18507. var halfWidth = planeWidth / 2;
  18508. halfHeight /= this.zoom;
  18509. halfWidth /= this.zoom;
  18510. this.cameraO.left = -halfWidth;
  18511. this.cameraO.right = halfWidth;
  18512. this.cameraO.top = halfHeight;
  18513. this.cameraO.bottom = -halfHeight;
  18514. // this.cameraO.left = -farHalfWidth;
  18515. // this.cameraO.right = farHalfWidth;
  18516. // this.cameraO.top = farHalfHeight;
  18517. // this.cameraO.bottom = -farHalfHeight;
  18518. // this.cameraO.left = this.left / this.zoom;
  18519. // this.cameraO.right = this.right / this.zoom;
  18520. // this.cameraO.top = this.top / this.zoom;
  18521. // this.cameraO.bottom = this.bottom / this.zoom;
  18522. this.cameraO.updateProjectionMatrix();
  18523. this.near = this.cameraO.near;
  18524. this.far = this.cameraO.far;
  18525. this.projectionMatrix = this.cameraO.projectionMatrix;
  18526. this.inPerspectiveMode = false;
  18527. this.inOrthographicMode = true;
  18528. };
  18529. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18530. this.cameraP.aspect = width / height;
  18531. this.left = -width / 2;
  18532. this.right = width / 2
  18533. this.top = height / 2;
  18534. this.bottom = -height / 2;
  18535. };
  18536. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18537. this.fov = fov;
  18538. if ( this.inPerspectiveMode ) {
  18539. this.toPerspective();
  18540. } else {
  18541. this.toOrthographic();
  18542. }
  18543. };
  18544. // For mantaining similar API with PerspectiveCamera
  18545. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18546. if ( this.inPerspectiveMode ) {
  18547. this.toPerspective();
  18548. } else {
  18549. this.toPerspective();
  18550. this.toOrthographic();
  18551. }
  18552. };
  18553. /*
  18554. * Uses Focal Length (in mm) to estimate and set FOV
  18555. * 35mm (fullframe) camera is used if frame size is not specified;
  18556. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18557. */
  18558. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18559. if ( frameHeight === undefined ) frameHeight = 24;
  18560. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18561. this.setFov( fov );
  18562. return fov;
  18563. };
  18564. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18565. this.zoom = zoom;
  18566. if ( this.inPerspectiveMode ) {
  18567. this.toPerspective();
  18568. } else {
  18569. this.toOrthographic();
  18570. }
  18571. };
  18572. THREE.CombinedCamera.prototype.toFrontView = function() {
  18573. this.rotation.x = 0;
  18574. this.rotation.y = 0;
  18575. this.rotation.z = 0;
  18576. // should we be modifing the matrix instead?
  18577. this.rotationAutoUpdate = false;
  18578. };
  18579. THREE.CombinedCamera.prototype.toBackView = function() {
  18580. this.rotation.x = 0;
  18581. this.rotation.y = Math.PI;
  18582. this.rotation.z = 0;
  18583. this.rotationAutoUpdate = false;
  18584. };
  18585. THREE.CombinedCamera.prototype.toLeftView = function() {
  18586. this.rotation.x = 0;
  18587. this.rotation.y = - Math.PI / 2;
  18588. this.rotation.z = 0;
  18589. this.rotationAutoUpdate = false;
  18590. };
  18591. THREE.CombinedCamera.prototype.toRightView = function() {
  18592. this.rotation.x = 0;
  18593. this.rotation.y = Math.PI / 2;
  18594. this.rotation.z = 0;
  18595. this.rotationAutoUpdate = false;
  18596. };
  18597. THREE.CombinedCamera.prototype.toTopView = function() {
  18598. this.rotation.x = - Math.PI / 2;
  18599. this.rotation.y = 0;
  18600. this.rotation.z = 0;
  18601. this.rotationAutoUpdate = false;
  18602. };
  18603. THREE.CombinedCamera.prototype.toBottomView = function() {
  18604. this.rotation.x = Math.PI / 2;
  18605. this.rotation.y = 0;
  18606. this.rotation.z = 0;
  18607. this.rotationAutoUpdate = false;
  18608. };
  18609. /**
  18610. * @author hughes
  18611. */
  18612. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18613. THREE.Geometry.call( this );
  18614. this.radius = radius = radius || 50;
  18615. this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18616. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18617. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18618. var i, uvs = [],
  18619. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18620. this.vertices.push(center);
  18621. uvs.push( centerUV );
  18622. for ( i = 0; i <= segments; i ++ ) {
  18623. var vertex = new THREE.Vector3();
  18624. var segment = thetaStart + i / segments * thetaLength;
  18625. vertex.x = radius * Math.cos( segment );
  18626. vertex.y = radius * Math.sin( segment );
  18627. this.vertices.push( vertex );
  18628. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18629. }
  18630. var n = new THREE.Vector3( 0, 0, 1 );
  18631. for ( i = 1; i <= segments; i ++ ) {
  18632. var v1 = i;
  18633. var v2 = i + 1 ;
  18634. var v3 = 0;
  18635. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  18636. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18637. }
  18638. this.computeCentroids();
  18639. this.computeFaceNormals();
  18640. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18641. };
  18642. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18643. /**
  18644. * @author mrdoob / http://mrdoob.com/
  18645. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18646. */
  18647. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18648. THREE.Geometry.call( this );
  18649. var scope = this;
  18650. this.width = width;
  18651. this.height = height;
  18652. this.depth = depth;
  18653. this.widthSegments = widthSegments || 1;
  18654. this.heightSegments = heightSegments || 1;
  18655. this.depthSegments = depthSegments || 1;
  18656. var width_half = this.width / 2;
  18657. var height_half = this.height / 2;
  18658. var depth_half = this.depth / 2;
  18659. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18660. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18661. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18662. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18663. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18664. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18665. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18666. var w, ix, iy,
  18667. gridX = scope.widthSegments,
  18668. gridY = scope.heightSegments,
  18669. width_half = width / 2,
  18670. height_half = height / 2,
  18671. offset = scope.vertices.length;
  18672. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18673. w = 'z';
  18674. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18675. w = 'y';
  18676. gridY = scope.depthSegments;
  18677. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18678. w = 'x';
  18679. gridX = scope.depthSegments;
  18680. }
  18681. var gridX1 = gridX + 1,
  18682. gridY1 = gridY + 1,
  18683. segment_width = width / gridX,
  18684. segment_height = height / gridY,
  18685. normal = new THREE.Vector3();
  18686. normal[ w ] = depth > 0 ? 1 : - 1;
  18687. for ( iy = 0; iy < gridY1; iy ++ ) {
  18688. for ( ix = 0; ix < gridX1; ix ++ ) {
  18689. var vector = new THREE.Vector3();
  18690. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18691. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18692. vector[ w ] = depth;
  18693. scope.vertices.push( vector );
  18694. }
  18695. }
  18696. for ( iy = 0; iy < gridY; iy++ ) {
  18697. for ( ix = 0; ix < gridX; ix++ ) {
  18698. var a = ix + gridX1 * iy;
  18699. var b = ix + gridX1 * ( iy + 1 );
  18700. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18701. var d = ( ix + 1 ) + gridX1 * iy;
  18702. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18703. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18704. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18705. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18706. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18707. face.normal.copy( normal );
  18708. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18709. face.materialIndex = materialIndex;
  18710. scope.faces.push( face );
  18711. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18712. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18713. face.normal.copy( normal );
  18714. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18715. face.materialIndex = materialIndex;
  18716. scope.faces.push( face );
  18717. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18718. }
  18719. }
  18720. }
  18721. this.computeCentroids();
  18722. this.mergeVertices();
  18723. };
  18724. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18725. /**
  18726. * @author mrdoob / http://mrdoob.com/
  18727. */
  18728. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18729. THREE.Geometry.call( this );
  18730. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18731. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18732. this.height = height = height !== undefined ? height : 100;
  18733. this.radialSegments = radialSegments = radialSegments || 8;
  18734. this.heightSegments = heightSegments = heightSegments || 1;
  18735. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18736. var heightHalf = height / 2;
  18737. var x, y, vertices = [], uvs = [];
  18738. for ( y = 0; y <= heightSegments; y ++ ) {
  18739. var verticesRow = [];
  18740. var uvsRow = [];
  18741. var v = y / heightSegments;
  18742. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18743. for ( x = 0; x <= radialSegments; x ++ ) {
  18744. var u = x / radialSegments;
  18745. var vertex = new THREE.Vector3();
  18746. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18747. vertex.y = - v * height + heightHalf;
  18748. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18749. this.vertices.push( vertex );
  18750. verticesRow.push( this.vertices.length - 1 );
  18751. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18752. }
  18753. vertices.push( verticesRow );
  18754. uvs.push( uvsRow );
  18755. }
  18756. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18757. var na, nb;
  18758. for ( x = 0; x < radialSegments; x ++ ) {
  18759. if ( radiusTop !== 0 ) {
  18760. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18761. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18762. } else {
  18763. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18764. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18765. }
  18766. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18767. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18768. for ( y = 0; y < heightSegments; y ++ ) {
  18769. var v1 = vertices[ y ][ x ];
  18770. var v2 = vertices[ y + 1 ][ x ];
  18771. var v3 = vertices[ y + 1 ][ x + 1 ];
  18772. var v4 = vertices[ y ][ x + 1 ];
  18773. var n1 = na.clone();
  18774. var n2 = na.clone();
  18775. var n3 = nb.clone();
  18776. var n4 = nb.clone();
  18777. var uv1 = uvs[ y ][ x ].clone();
  18778. var uv2 = uvs[ y + 1 ][ x ].clone();
  18779. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18780. var uv4 = uvs[ y ][ x + 1 ].clone();
  18781. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  18782. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  18783. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  18784. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  18785. }
  18786. }
  18787. // top cap
  18788. if ( openEnded === false && radiusTop > 0 ) {
  18789. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18790. for ( x = 0; x < radialSegments; x ++ ) {
  18791. var v1 = vertices[ 0 ][ x ];
  18792. var v2 = vertices[ 0 ][ x + 1 ];
  18793. var v3 = this.vertices.length - 1;
  18794. var n1 = new THREE.Vector3( 0, 1, 0 );
  18795. var n2 = new THREE.Vector3( 0, 1, 0 );
  18796. var n3 = new THREE.Vector3( 0, 1, 0 );
  18797. var uv1 = uvs[ 0 ][ x ].clone();
  18798. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18799. var uv3 = new THREE.Vector2( uv2.x, 0 );
  18800. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18801. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18802. }
  18803. }
  18804. // bottom cap
  18805. if ( openEnded === false && radiusBottom > 0 ) {
  18806. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18807. for ( x = 0; x < radialSegments; x ++ ) {
  18808. var v1 = vertices[ y ][ x + 1 ];
  18809. var v2 = vertices[ y ][ x ];
  18810. var v3 = this.vertices.length - 1;
  18811. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18812. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18813. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18814. var uv1 = uvs[ y ][ x + 1 ].clone();
  18815. var uv2 = uvs[ y ][ x ].clone();
  18816. var uv3 = new THREE.Vector2( uv2.x, 1 );
  18817. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18818. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18819. }
  18820. }
  18821. this.computeCentroids();
  18822. this.computeFaceNormals();
  18823. }
  18824. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18825. /**
  18826. * @author zz85 / http://www.lab4games.net/zz85/blog
  18827. *
  18828. * Creates extruded geometry from a path shape.
  18829. *
  18830. * parameters = {
  18831. *
  18832. * curveSegments: <int>, // number of points on the curves
  18833. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18834. * amount: <int>, // Depth to extrude the shape
  18835. *
  18836. * bevelEnabled: <bool>, // turn on bevel
  18837. * bevelThickness: <float>, // how deep into the original shape bevel goes
  18838. * bevelSize: <float>, // how far from shape outline is bevel
  18839. * bevelSegments: <int>, // number of bevel layers
  18840. *
  18841. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18842. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18843. *
  18844. * material: <int> // material index for front and back faces
  18845. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18846. * uvGenerator: <Object> // object that provides UV generator functions
  18847. *
  18848. * }
  18849. **/
  18850. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18851. if ( typeof( shapes ) === "undefined" ) {
  18852. shapes = [];
  18853. return;
  18854. }
  18855. THREE.Geometry.call( this );
  18856. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18857. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18858. this.addShapeList( shapes, options );
  18859. this.computeCentroids();
  18860. this.computeFaceNormals();
  18861. // can't really use automatic vertex normals
  18862. // as then front and back sides get smoothed too
  18863. // should do separate smoothing just for sides
  18864. //this.computeVertexNormals();
  18865. //console.log( "took", ( Date.now() - startTime ) );
  18866. };
  18867. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18868. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18869. var sl = shapes.length;
  18870. for ( var s = 0; s < sl; s ++ ) {
  18871. var shape = shapes[ s ];
  18872. this.addShape( shape, options );
  18873. }
  18874. };
  18875. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18876. var amount = options.amount !== undefined ? options.amount : 100;
  18877. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18878. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18879. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18880. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18881. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18882. var steps = options.steps !== undefined ? options.steps : 1;
  18883. var extrudePath = options.extrudePath;
  18884. var extrudePts, extrudeByPath = false;
  18885. var material = options.material;
  18886. var extrudeMaterial = options.extrudeMaterial;
  18887. // Use default WorldUVGenerator if no UV generators are specified.
  18888. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18889. var shapebb = this.shapebb;
  18890. //shapebb = shape.getBoundingBox();
  18891. var splineTube, binormal, normal, position2;
  18892. if ( extrudePath ) {
  18893. extrudePts = extrudePath.getSpacedPoints( steps );
  18894. extrudeByPath = true;
  18895. bevelEnabled = false; // bevels not supported for path extrusion
  18896. // SETUP TNB variables
  18897. // Reuse TNB from TubeGeomtry for now.
  18898. // TODO1 - have a .isClosed in spline?
  18899. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18900. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18901. binormal = new THREE.Vector3();
  18902. normal = new THREE.Vector3();
  18903. position2 = new THREE.Vector3();
  18904. }
  18905. // Safeguards if bevels are not enabled
  18906. if ( ! bevelEnabled ) {
  18907. bevelSegments = 0;
  18908. bevelThickness = 0;
  18909. bevelSize = 0;
  18910. }
  18911. // Variables initalization
  18912. var ahole, h, hl; // looping of holes
  18913. var scope = this;
  18914. var bevelPoints = [];
  18915. var shapesOffset = this.vertices.length;
  18916. var shapePoints = shape.extractPoints( curveSegments );
  18917. var vertices = shapePoints.shape;
  18918. var holes = shapePoints.holes;
  18919. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18920. if ( reverse ) {
  18921. vertices = vertices.reverse();
  18922. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18923. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18924. ahole = holes[ h ];
  18925. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18926. holes[ h ] = ahole.reverse();
  18927. }
  18928. }
  18929. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18930. }
  18931. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18932. /* Vertices */
  18933. var contour = vertices; // vertices has all points but contour has only points of circumference
  18934. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18935. ahole = holes[ h ];
  18936. vertices = vertices.concat( ahole );
  18937. }
  18938. function scalePt2 ( pt, vec, size ) {
  18939. if ( !vec ) console.log( "die" );
  18940. return vec.clone().multiplyScalar( size ).add( pt );
  18941. }
  18942. var b, bs, t, z,
  18943. vert, vlen = vertices.length,
  18944. face, flen = faces.length,
  18945. cont, clen = contour.length;
  18946. // Find directions for point movement
  18947. var RAD_TO_DEGREES = 180 / Math.PI;
  18948. function getBevelVec( pt_i, pt_j, pt_k ) {
  18949. // Algorithm 2
  18950. return getBevelVec2( pt_i, pt_j, pt_k );
  18951. }
  18952. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18953. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18954. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18955. if ( anglea > angleb ) {
  18956. angleb += Math.PI * 2;
  18957. }
  18958. var anglec = ( anglea + angleb ) / 2;
  18959. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18960. var x = - Math.cos( anglec );
  18961. var y = - Math.sin( anglec );
  18962. var vec = new THREE.Vector2( x, y ); //.normalize();
  18963. return vec;
  18964. }
  18965. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18966. var a = THREE.ExtrudeGeometry.__v1,
  18967. b = THREE.ExtrudeGeometry.__v2,
  18968. v_hat = THREE.ExtrudeGeometry.__v3,
  18969. w_hat = THREE.ExtrudeGeometry.__v4,
  18970. p = THREE.ExtrudeGeometry.__v5,
  18971. q = THREE.ExtrudeGeometry.__v6,
  18972. v, w,
  18973. v_dot_w_hat, q_sub_p_dot_w_hat,
  18974. s, intersection;
  18975. // good reading for line-line intersection
  18976. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18977. // define a as vector j->i
  18978. // define b as vectot k->i
  18979. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18980. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18981. // get unit vectors
  18982. v = a.normalize();
  18983. w = b.normalize();
  18984. // normals from pt i
  18985. v_hat.set( -v.y, v.x );
  18986. w_hat.set( w.y, -w.x );
  18987. // pts from i
  18988. p.copy( pt_i ).add( v_hat );
  18989. q.copy( pt_i ).add( w_hat );
  18990. if ( p.equals( q ) ) {
  18991. //console.log("Warning: lines are straight");
  18992. return w_hat.clone();
  18993. }
  18994. // Points from j, k. helps prevents points cross overover most of the time
  18995. p.copy( pt_j ).add( v_hat );
  18996. q.copy( pt_k ).add( w_hat );
  18997. v_dot_w_hat = v.dot( w_hat );
  18998. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18999. // We should not reach these conditions
  19000. if ( v_dot_w_hat === 0 ) {
  19001. console.log( "Either infinite or no solutions!" );
  19002. if ( q_sub_p_dot_w_hat === 0 ) {
  19003. console.log( "Its finite solutions." );
  19004. } else {
  19005. console.log( "Too bad, no solutions." );
  19006. }
  19007. }
  19008. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19009. if ( s < 0 ) {
  19010. // in case of emergecy, revert to algorithm 1.
  19011. return getBevelVec1( pt_i, pt_j, pt_k );
  19012. }
  19013. intersection = v.multiplyScalar( s ).add( p );
  19014. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19015. }
  19016. var contourMovements = [];
  19017. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19018. if ( j === il ) j = 0;
  19019. if ( k === il ) k = 0;
  19020. // (j)---(i)---(k)
  19021. // console.log('i,j,k', i, j , k)
  19022. var pt_i = contour[ i ];
  19023. var pt_j = contour[ j ];
  19024. var pt_k = contour[ k ];
  19025. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19026. }
  19027. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19028. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19029. ahole = holes[ h ];
  19030. oneHoleMovements = [];
  19031. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19032. if ( j === il ) j = 0;
  19033. if ( k === il ) k = 0;
  19034. // (j)---(i)---(k)
  19035. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19036. }
  19037. holesMovements.push( oneHoleMovements );
  19038. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19039. }
  19040. // Loop bevelSegments, 1 for the front, 1 for the back
  19041. for ( b = 0; b < bevelSegments; b ++ ) {
  19042. //for ( b = bevelSegments; b > 0; b -- ) {
  19043. t = b / bevelSegments;
  19044. z = bevelThickness * ( 1 - t );
  19045. //z = bevelThickness * t;
  19046. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19047. //bs = bevelSize * t ; // linear
  19048. // contract shape
  19049. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19050. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19051. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19052. v( vert.x, vert.y, - z );
  19053. }
  19054. // expand holes
  19055. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19056. ahole = holes[ h ];
  19057. oneHoleMovements = holesMovements[ h ];
  19058. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19059. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19060. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19061. v( vert.x, vert.y, -z );
  19062. }
  19063. }
  19064. }
  19065. bs = bevelSize;
  19066. // Back facing vertices
  19067. for ( i = 0; i < vlen; i ++ ) {
  19068. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19069. if ( !extrudeByPath ) {
  19070. v( vert.x, vert.y, 0 );
  19071. } else {
  19072. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19073. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19074. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19075. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19076. v( position2.x, position2.y, position2.z );
  19077. }
  19078. }
  19079. // Add stepped vertices...
  19080. // Including front facing vertices
  19081. var s;
  19082. for ( s = 1; s <= steps; s ++ ) {
  19083. for ( i = 0; i < vlen; i ++ ) {
  19084. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19085. if ( !extrudeByPath ) {
  19086. v( vert.x, vert.y, amount / steps * s );
  19087. } else {
  19088. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19089. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19090. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19091. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19092. v( position2.x, position2.y, position2.z );
  19093. }
  19094. }
  19095. }
  19096. // Add bevel segments planes
  19097. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19098. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19099. t = b / bevelSegments;
  19100. z = bevelThickness * ( 1 - t );
  19101. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19102. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19103. // contract shape
  19104. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19105. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19106. v( vert.x, vert.y, amount + z );
  19107. }
  19108. // expand holes
  19109. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19110. ahole = holes[ h ];
  19111. oneHoleMovements = holesMovements[ h ];
  19112. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19113. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19114. if ( !extrudeByPath ) {
  19115. v( vert.x, vert.y, amount + z );
  19116. } else {
  19117. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19118. }
  19119. }
  19120. }
  19121. }
  19122. /* Faces */
  19123. // Top and bottom faces
  19124. buildLidFaces();
  19125. // Sides faces
  19126. buildSideFaces();
  19127. ///// Internal functions
  19128. function buildLidFaces() {
  19129. if ( bevelEnabled ) {
  19130. var layer = 0 ; // steps + 1
  19131. var offset = vlen * layer;
  19132. // Bottom faces
  19133. for ( i = 0; i < flen; i ++ ) {
  19134. face = faces[ i ];
  19135. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19136. }
  19137. layer = steps + bevelSegments * 2;
  19138. offset = vlen * layer;
  19139. // Top faces
  19140. for ( i = 0; i < flen; i ++ ) {
  19141. face = faces[ i ];
  19142. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19143. }
  19144. } else {
  19145. // Bottom faces
  19146. for ( i = 0; i < flen; i++ ) {
  19147. face = faces[ i ];
  19148. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19149. }
  19150. // Top faces
  19151. for ( i = 0; i < flen; i ++ ) {
  19152. face = faces[ i ];
  19153. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19154. }
  19155. }
  19156. }
  19157. // Create faces for the z-sides of the shape
  19158. function buildSideFaces() {
  19159. var layeroffset = 0;
  19160. sidewalls( contour, layeroffset );
  19161. layeroffset += contour.length;
  19162. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19163. ahole = holes[ h ];
  19164. sidewalls( ahole, layeroffset );
  19165. //, true
  19166. layeroffset += ahole.length;
  19167. }
  19168. }
  19169. function sidewalls( contour, layeroffset ) {
  19170. var j, k;
  19171. i = contour.length;
  19172. while ( --i >= 0 ) {
  19173. j = i;
  19174. k = i - 1;
  19175. if ( k < 0 ) k = contour.length - 1;
  19176. //console.log('b', i,j, i-1, k,vertices.length);
  19177. var s = 0, sl = steps + bevelSegments * 2;
  19178. for ( s = 0; s < sl; s ++ ) {
  19179. var slen1 = vlen * s;
  19180. var slen2 = vlen * ( s + 1 );
  19181. var a = layeroffset + j + slen1,
  19182. b = layeroffset + k + slen1,
  19183. c = layeroffset + k + slen2,
  19184. d = layeroffset + j + slen2;
  19185. f4( a, b, c, d, contour, s, sl, j, k );
  19186. }
  19187. }
  19188. }
  19189. function v( x, y, z ) {
  19190. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19191. }
  19192. function f3( a, b, c, isBottom ) {
  19193. a += shapesOffset;
  19194. b += shapesOffset;
  19195. c += shapesOffset;
  19196. // normal, color, material
  19197. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19198. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19199. scope.faceVertexUvs[ 0 ].push( uvs );
  19200. }
  19201. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19202. a += shapesOffset;
  19203. b += shapesOffset;
  19204. c += shapesOffset;
  19205. d += shapesOffset;
  19206. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19207. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19208. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19209. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19210. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19211. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19212. }
  19213. };
  19214. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19215. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19216. var ax = geometry.vertices[ indexA ].x,
  19217. ay = geometry.vertices[ indexA ].y,
  19218. bx = geometry.vertices[ indexB ].x,
  19219. by = geometry.vertices[ indexB ].y,
  19220. cx = geometry.vertices[ indexC ].x,
  19221. cy = geometry.vertices[ indexC ].y;
  19222. return [
  19223. new THREE.Vector2( ax, ay ),
  19224. new THREE.Vector2( bx, by ),
  19225. new THREE.Vector2( cx, cy )
  19226. ];
  19227. },
  19228. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19229. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19230. },
  19231. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19232. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19233. contourIndex1, contourIndex2 ) {
  19234. var ax = geometry.vertices[ indexA ].x,
  19235. ay = geometry.vertices[ indexA ].y,
  19236. az = geometry.vertices[ indexA ].z,
  19237. bx = geometry.vertices[ indexB ].x,
  19238. by = geometry.vertices[ indexB ].y,
  19239. bz = geometry.vertices[ indexB ].z,
  19240. cx = geometry.vertices[ indexC ].x,
  19241. cy = geometry.vertices[ indexC ].y,
  19242. cz = geometry.vertices[ indexC ].z,
  19243. dx = geometry.vertices[ indexD ].x,
  19244. dy = geometry.vertices[ indexD ].y,
  19245. dz = geometry.vertices[ indexD ].z;
  19246. if ( Math.abs( ay - by ) < 0.01 ) {
  19247. return [
  19248. new THREE.Vector2( ax, 1 - az ),
  19249. new THREE.Vector2( bx, 1 - bz ),
  19250. new THREE.Vector2( cx, 1 - cz ),
  19251. new THREE.Vector2( dx, 1 - dz )
  19252. ];
  19253. } else {
  19254. return [
  19255. new THREE.Vector2( ay, 1 - az ),
  19256. new THREE.Vector2( by, 1 - bz ),
  19257. new THREE.Vector2( cy, 1 - cz ),
  19258. new THREE.Vector2( dy, 1 - dz )
  19259. ];
  19260. }
  19261. }
  19262. };
  19263. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19264. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19265. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19266. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19267. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19268. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19269. /**
  19270. * @author jonobr1 / http://jonobr1.com
  19271. *
  19272. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19273. * ExtrudeGeometry.
  19274. *
  19275. * parameters = {
  19276. *
  19277. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19278. *
  19279. * material: <int> // material index for front and back faces
  19280. * uvGenerator: <Object> // object that provides UV generator functions
  19281. *
  19282. * }
  19283. **/
  19284. THREE.ShapeGeometry = function ( shapes, options ) {
  19285. THREE.Geometry.call( this );
  19286. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19287. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19288. this.addShapeList( shapes, options );
  19289. this.computeCentroids();
  19290. this.computeFaceNormals();
  19291. };
  19292. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19293. /**
  19294. * Add an array of shapes to THREE.ShapeGeometry.
  19295. */
  19296. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19297. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19298. this.addShape( shapes[ i ], options );
  19299. }
  19300. return this;
  19301. };
  19302. /**
  19303. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19304. */
  19305. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19306. if ( options === undefined ) options = {};
  19307. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19308. var material = options.material;
  19309. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19310. var shapebb = this.shapebb;
  19311. //
  19312. var i, l, hole, s;
  19313. var shapesOffset = this.vertices.length;
  19314. var shapePoints = shape.extractPoints( curveSegments );
  19315. var vertices = shapePoints.shape;
  19316. var holes = shapePoints.holes;
  19317. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19318. if ( reverse ) {
  19319. vertices = vertices.reverse();
  19320. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19321. for ( i = 0, l = holes.length; i < l; i++ ) {
  19322. hole = holes[ i ];
  19323. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19324. holes[ i ] = hole.reverse();
  19325. }
  19326. }
  19327. reverse = false;
  19328. }
  19329. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19330. // Vertices
  19331. var contour = vertices;
  19332. for ( i = 0, l = holes.length; i < l; i++ ) {
  19333. hole = holes[ i ];
  19334. vertices = vertices.concat( hole );
  19335. }
  19336. //
  19337. var vert, vlen = vertices.length;
  19338. var face, flen = faces.length;
  19339. var cont, clen = contour.length;
  19340. for ( i = 0; i < vlen; i++ ) {
  19341. vert = vertices[ i ];
  19342. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19343. }
  19344. for ( i = 0; i < flen; i++ ) {
  19345. face = faces[ i ];
  19346. var a = face[ 0 ] + shapesOffset;
  19347. var b = face[ 1 ] + shapesOffset;
  19348. var c = face[ 2 ] + shapesOffset;
  19349. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19350. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19351. }
  19352. };
  19353. /**
  19354. * @author astrodud / http://astrodud.isgreat.org/
  19355. * @author zz85 / https://github.com/zz85
  19356. * @author bhouston / http://exocortex.com
  19357. */
  19358. // points - to create a closed torus, one must use a set of points
  19359. // like so: [ a, b, c, d, a ], see first is the same as last.
  19360. // segments - the number of circumference segments to create
  19361. // phiStart - the starting radian
  19362. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19363. // 2*pi is a closed lathe, less than 2PI is a portion.
  19364. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19365. THREE.Geometry.call( this );
  19366. segments = segments || 12;
  19367. phiStart = phiStart || 0;
  19368. phiLength = phiLength || 2 * Math.PI;
  19369. var inversePointLength = 1.0 / ( points.length - 1 );
  19370. var inverseSegments = 1.0 / segments;
  19371. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19372. var phi = phiStart + i * inverseSegments * phiLength;
  19373. var c = Math.cos( phi ),
  19374. s = Math.sin( phi );
  19375. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19376. var pt = points[ j ];
  19377. var vertex = new THREE.Vector3();
  19378. vertex.x = c * pt.x - s * pt.y;
  19379. vertex.y = s * pt.x + c * pt.y;
  19380. vertex.z = pt.z;
  19381. this.vertices.push( vertex );
  19382. }
  19383. }
  19384. var np = points.length;
  19385. for ( var i = 0, il = segments; i < il; i ++ ) {
  19386. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19387. var base = j + np * i;
  19388. var a = base;
  19389. var b = base + np;
  19390. var c = base + 1 + np;
  19391. var d = base + 1;
  19392. var u0 = i * inverseSegments;
  19393. var v0 = j * inversePointLength;
  19394. var u1 = u0 + inverseSegments;
  19395. var v1 = v0 + inversePointLength;
  19396. this.faces.push( new THREE.Face3( a, b, d ) );
  19397. this.faceVertexUvs[ 0 ].push( [
  19398. new THREE.Vector2( u0, v0 ),
  19399. new THREE.Vector2( u1, v0 ),
  19400. new THREE.Vector2( u0, v1 )
  19401. ] );
  19402. this.faces.push( new THREE.Face3( b, c, d ) );
  19403. this.faceVertexUvs[ 0 ].push( [
  19404. new THREE.Vector2( u1, v0 ),
  19405. new THREE.Vector2( u1, v1 ),
  19406. new THREE.Vector2( u0, v1 )
  19407. ] );
  19408. }
  19409. }
  19410. this.mergeVertices();
  19411. this.computeCentroids();
  19412. this.computeFaceNormals();
  19413. this.computeVertexNormals();
  19414. };
  19415. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19416. /**
  19417. * @author mrdoob / http://mrdoob.com/
  19418. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19419. */
  19420. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19421. THREE.Geometry.call( this );
  19422. this.width = width;
  19423. this.height = height;
  19424. this.widthSegments = widthSegments || 1;
  19425. this.heightSegments = heightSegments || 1;
  19426. var ix, iz;
  19427. var width_half = width / 2;
  19428. var height_half = height / 2;
  19429. var gridX = this.widthSegments;
  19430. var gridZ = this.heightSegments;
  19431. var gridX1 = gridX + 1;
  19432. var gridZ1 = gridZ + 1;
  19433. var segment_width = this.width / gridX;
  19434. var segment_height = this.height / gridZ;
  19435. var normal = new THREE.Vector3( 0, 0, 1 );
  19436. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19437. for ( ix = 0; ix < gridX1; ix ++ ) {
  19438. var x = ix * segment_width - width_half;
  19439. var y = iz * segment_height - height_half;
  19440. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19441. }
  19442. }
  19443. for ( iz = 0; iz < gridZ; iz ++ ) {
  19444. for ( ix = 0; ix < gridX; ix ++ ) {
  19445. var a = ix + gridX1 * iz;
  19446. var b = ix + gridX1 * ( iz + 1 );
  19447. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19448. var d = ( ix + 1 ) + gridX1 * iz;
  19449. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19450. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19451. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19452. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19453. var face = new THREE.Face3( a, b, d );
  19454. face.normal.copy( normal );
  19455. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19456. this.faces.push( face );
  19457. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19458. face = new THREE.Face3( b, c, d );
  19459. face.normal.copy( normal );
  19460. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19461. this.faces.push( face );
  19462. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19463. }
  19464. }
  19465. this.computeCentroids();
  19466. };
  19467. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19468. /**
  19469. * @author Kaleb Murphy
  19470. */
  19471. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19472. THREE.Geometry.call( this );
  19473. innerRadius = innerRadius || 0;
  19474. outerRadius = outerRadius || 50;
  19475. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19476. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19477. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19478. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19479. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19480. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19481. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19482. var vertex = new THREE.Vector3();
  19483. var segment = thetaStart + o / thetaSegments * thetaLength;
  19484. vertex.x = radius * Math.cos( segment );
  19485. vertex.y = radius * Math.sin( segment );
  19486. this.vertices.push( vertex );
  19487. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19488. }
  19489. radius += radiusStep;
  19490. }
  19491. var n = new THREE.Vector3( 0, 0, 1 );
  19492. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19493. var thetaSegment = i * thetaSegments;
  19494. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19495. var segment = o + thetaSegment;
  19496. var v1 = segment + i;
  19497. var v2 = segment + thetaSegments + i;
  19498. var v3 = segment + thetaSegments + 1 + i;
  19499. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19500. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19501. v1 = segment + i;
  19502. v2 = segment + thetaSegments + 1 + i;
  19503. v3 = segment + 1 + i;
  19504. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19505. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19506. }
  19507. }
  19508. this.computeCentroids();
  19509. this.computeFaceNormals();
  19510. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19511. };
  19512. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19513. /**
  19514. * @author mrdoob / http://mrdoob.com/
  19515. */
  19516. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19517. THREE.Geometry.call( this );
  19518. this.radius = radius = radius || 50;
  19519. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19520. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19521. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19522. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19523. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19524. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19525. var x, y, vertices = [], uvs = [];
  19526. for ( y = 0; y <= heightSegments; y ++ ) {
  19527. var verticesRow = [];
  19528. var uvsRow = [];
  19529. for ( x = 0; x <= widthSegments; x ++ ) {
  19530. var u = x / widthSegments;
  19531. var v = y / heightSegments;
  19532. var vertex = new THREE.Vector3();
  19533. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19534. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19535. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19536. this.vertices.push( vertex );
  19537. verticesRow.push( this.vertices.length - 1 );
  19538. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19539. }
  19540. vertices.push( verticesRow );
  19541. uvs.push( uvsRow );
  19542. }
  19543. for ( y = 0; y < this.heightSegments; y ++ ) {
  19544. for ( x = 0; x < this.widthSegments; x ++ ) {
  19545. var v1 = vertices[ y ][ x + 1 ];
  19546. var v2 = vertices[ y ][ x ];
  19547. var v3 = vertices[ y + 1 ][ x ];
  19548. var v4 = vertices[ y + 1 ][ x + 1 ];
  19549. var n1 = this.vertices[ v1 ].clone().normalize();
  19550. var n2 = this.vertices[ v2 ].clone().normalize();
  19551. var n3 = this.vertices[ v3 ].clone().normalize();
  19552. var n4 = this.vertices[ v4 ].clone().normalize();
  19553. var uv1 = uvs[ y ][ x + 1 ].clone();
  19554. var uv2 = uvs[ y ][ x ].clone();
  19555. var uv3 = uvs[ y + 1 ][ x ].clone();
  19556. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19557. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19558. uv1.x = ( uv1.x + uv2.x ) / 2;
  19559. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19560. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19561. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19562. uv3.x = ( uv3.x + uv4.x ) / 2;
  19563. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19564. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19565. } else {
  19566. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19567. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19568. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19569. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19570. }
  19571. }
  19572. }
  19573. this.computeCentroids();
  19574. this.computeFaceNormals();
  19575. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19576. };
  19577. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19578. /**
  19579. * @author zz85 / http://www.lab4games.net/zz85/blog
  19580. * @author alteredq / http://alteredqualia.com/
  19581. *
  19582. * For creating 3D text geometry in three.js
  19583. *
  19584. * Text = 3D Text
  19585. *
  19586. * parameters = {
  19587. * size: <float>, // size of the text
  19588. * height: <float>, // thickness to extrude text
  19589. * curveSegments: <int>, // number of points on the curves
  19590. *
  19591. * font: <string>, // font name
  19592. * weight: <string>, // font weight (normal, bold)
  19593. * style: <string>, // font style (normal, italics)
  19594. *
  19595. * bevelEnabled: <bool>, // turn on bevel
  19596. * bevelThickness: <float>, // how deep into text bevel goes
  19597. * bevelSize: <float>, // how far from text outline is bevel
  19598. * }
  19599. *
  19600. */
  19601. /* Usage Examples
  19602. // TextGeometry wrapper
  19603. var text3d = new TextGeometry( text, options );
  19604. // Complete manner
  19605. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19606. var text3d = new ExtrudeGeometry( textShapes, options );
  19607. */
  19608. THREE.TextGeometry = function ( text, parameters ) {
  19609. parameters = parameters || {};
  19610. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19611. // translate parameters to ExtrudeGeometry API
  19612. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19613. // defaults
  19614. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19615. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19616. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19617. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19618. };
  19619. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19620. /**
  19621. * @author oosmoxiecode
  19622. * @author mrdoob / http://mrdoob.com/
  19623. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19624. */
  19625. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19626. THREE.Geometry.call( this );
  19627. var scope = this;
  19628. this.radius = radius || 100;
  19629. this.tube = tube || 40;
  19630. this.radialSegments = radialSegments || 8;
  19631. this.tubularSegments = tubularSegments || 6;
  19632. this.arc = arc || Math.PI * 2;
  19633. var center = new THREE.Vector3(), uvs = [], normals = [];
  19634. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19635. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19636. var u = i / this.tubularSegments * this.arc;
  19637. var v = j / this.radialSegments * Math.PI * 2;
  19638. center.x = this.radius * Math.cos( u );
  19639. center.y = this.radius * Math.sin( u );
  19640. var vertex = new THREE.Vector3();
  19641. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19642. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19643. vertex.z = this.tube * Math.sin( v );
  19644. this.vertices.push( vertex );
  19645. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19646. normals.push( vertex.clone().sub( center ).normalize() );
  19647. }
  19648. }
  19649. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19650. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19651. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19652. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19653. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19654. var d = ( this.tubularSegments + 1 ) * j + i;
  19655. var face = new THREE.Face3( a, b, d, [ normals[ a ], normals[ b ], normals[ d ] ] );
  19656. face.normal.add( normals[ a ] );
  19657. face.normal.add( normals[ b ] );
  19658. face.normal.add( normals[ d ] );
  19659. face.normal.normalize();
  19660. this.faces.push( face );
  19661. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19662. face = new THREE.Face3( b, c, d, [ normals[ b ], normals[ c ], normals[ d ] ] );
  19663. face.normal.add( normals[ b ] );
  19664. face.normal.add( normals[ c ] );
  19665. face.normal.add( normals[ d ] );
  19666. face.normal.normalize();
  19667. this.faces.push( face );
  19668. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19669. }
  19670. }
  19671. this.computeCentroids();
  19672. };
  19673. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19674. /**
  19675. * @author oosmoxiecode
  19676. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19677. */
  19678. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19679. THREE.Geometry.call( this );
  19680. var scope = this;
  19681. this.radius = radius || 100;
  19682. this.tube = tube || 40;
  19683. this.radialSegments = radialSegments || 64;
  19684. this.tubularSegments = tubularSegments || 8;
  19685. this.p = p || 2;
  19686. this.q = q || 3;
  19687. this.heightScale = heightScale || 1;
  19688. this.grid = new Array( this.radialSegments );
  19689. var tang = new THREE.Vector3();
  19690. var n = new THREE.Vector3();
  19691. var bitan = new THREE.Vector3();
  19692. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19693. this.grid[ i ] = new Array( this.tubularSegments );
  19694. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19695. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  19696. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  19697. tang.subVectors( p2, p1 );
  19698. n.addVectors( p2, p1 );
  19699. bitan.crossVectors( tang, n );
  19700. n.crossVectors( bitan, tang );
  19701. bitan.normalize();
  19702. n.normalize();
  19703. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19704. var v = j / this.tubularSegments * 2 * Math.PI;
  19705. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19706. var cy = this.tube * Math.sin( v );
  19707. var pos = new THREE.Vector3();
  19708. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19709. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19710. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19711. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  19712. }
  19713. }
  19714. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19715. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19716. var ip = ( i + 1 ) % this.radialSegments;
  19717. var jp = ( j + 1 ) % this.tubularSegments;
  19718. var a = this.grid[ i ][ j ];
  19719. var b = this.grid[ ip ][ j ];
  19720. var c = this.grid[ ip ][ jp ];
  19721. var d = this.grid[ i ][ jp ];
  19722. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19723. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19724. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19725. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19726. this.faces.push( new THREE.Face3( a, b, d ) );
  19727. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19728. this.faces.push( new THREE.Face3( b, c, d ) );
  19729. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19730. }
  19731. }
  19732. this.computeCentroids();
  19733. this.computeFaceNormals();
  19734. this.computeVertexNormals();
  19735. function getPos( u, in_q, in_p, radius, heightScale ) {
  19736. var cu = Math.cos( u );
  19737. var su = Math.sin( u );
  19738. var quOverP = in_q / in_p * u;
  19739. var cs = Math.cos( quOverP );
  19740. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19741. var ty = radius * ( 2 + cs ) * su * 0.5;
  19742. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19743. return new THREE.Vector3( tx, ty, tz );
  19744. }
  19745. };
  19746. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19747. /**
  19748. * @author WestLangley / https://github.com/WestLangley
  19749. * @author zz85 / https://github.com/zz85
  19750. * @author miningold / https://github.com/miningold
  19751. *
  19752. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19753. *
  19754. * Creates a tube which extrudes along a 3d spline
  19755. *
  19756. * Uses parallel transport frames as described in
  19757. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19758. */
  19759. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  19760. THREE.Geometry.call( this );
  19761. this.path = path;
  19762. this.segments = segments || 64;
  19763. this.radius = radius || 1;
  19764. this.radialSegments = radialSegments || 8;
  19765. this.closed = closed || false;
  19766. this.grid = [];
  19767. var scope = this,
  19768. tangent,
  19769. normal,
  19770. binormal,
  19771. numpoints = this.segments + 1,
  19772. x, y, z,
  19773. tx, ty, tz,
  19774. u, v,
  19775. cx, cy,
  19776. pos, pos2 = new THREE.Vector3(),
  19777. i, j,
  19778. ip, jp,
  19779. a, b, c, d,
  19780. uva, uvb, uvc, uvd;
  19781. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19782. tangents = frames.tangents,
  19783. normals = frames.normals,
  19784. binormals = frames.binormals;
  19785. // proxy internals
  19786. this.tangents = tangents;
  19787. this.normals = normals;
  19788. this.binormals = binormals;
  19789. function vert( x, y, z ) {
  19790. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19791. }
  19792. // consruct the grid
  19793. for ( i = 0; i < numpoints; i++ ) {
  19794. this.grid[ i ] = [];
  19795. u = i / ( numpoints - 1 );
  19796. pos = path.getPointAt( u );
  19797. tangent = tangents[ i ];
  19798. normal = normals[ i ];
  19799. binormal = binormals[ i ];
  19800. for ( j = 0; j < this.radialSegments; j++ ) {
  19801. v = j / this.radialSegments * 2 * Math.PI;
  19802. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19803. cy = this.radius * Math.sin( v );
  19804. pos2.copy( pos );
  19805. pos2.x += cx * normal.x + cy * binormal.x;
  19806. pos2.y += cx * normal.y + cy * binormal.y;
  19807. pos2.z += cx * normal.z + cy * binormal.z;
  19808. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19809. }
  19810. }
  19811. // construct the mesh
  19812. for ( i = 0; i < this.segments; i++ ) {
  19813. for ( j = 0; j < this.radialSegments; j++ ) {
  19814. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19815. jp = (j + 1) % this.radialSegments;
  19816. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19817. b = this.grid[ ip ][ j ];
  19818. c = this.grid[ ip ][ jp ];
  19819. d = this.grid[ i ][ jp ];
  19820. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  19821. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  19822. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  19823. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  19824. this.faces.push( new THREE.Face3( a, b, d ) );
  19825. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19826. this.faces.push( new THREE.Face3( b, c, d ) );
  19827. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19828. }
  19829. }
  19830. this.computeCentroids();
  19831. this.computeFaceNormals();
  19832. this.computeVertexNormals();
  19833. };
  19834. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19835. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19836. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19837. var tangent = new THREE.Vector3(),
  19838. normal = new THREE.Vector3(),
  19839. binormal = new THREE.Vector3(),
  19840. tangents = [],
  19841. normals = [],
  19842. binormals = [],
  19843. vec = new THREE.Vector3(),
  19844. mat = new THREE.Matrix4(),
  19845. numpoints = segments + 1,
  19846. theta,
  19847. epsilon = 0.0001,
  19848. smallest,
  19849. tx, ty, tz,
  19850. i, u, v;
  19851. // expose internals
  19852. this.tangents = tangents;
  19853. this.normals = normals;
  19854. this.binormals = binormals;
  19855. // compute the tangent vectors for each segment on the path
  19856. for ( i = 0; i < numpoints; i++ ) {
  19857. u = i / ( numpoints - 1 );
  19858. tangents[ i ] = path.getTangentAt( u );
  19859. tangents[ i ].normalize();
  19860. }
  19861. initialNormal3();
  19862. function initialNormal1(lastBinormal) {
  19863. // fixed start binormal. Has dangers of 0 vectors
  19864. normals[ 0 ] = new THREE.Vector3();
  19865. binormals[ 0 ] = new THREE.Vector3();
  19866. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19867. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19868. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19869. }
  19870. function initialNormal2() {
  19871. // This uses the Frenet-Serret formula for deriving binormal
  19872. var t2 = path.getTangentAt( epsilon );
  19873. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19874. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19875. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19876. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19877. }
  19878. function initialNormal3() {
  19879. // select an initial normal vector perpenicular to the first tangent vector,
  19880. // and in the direction of the smallest tangent xyz component
  19881. normals[ 0 ] = new THREE.Vector3();
  19882. binormals[ 0 ] = new THREE.Vector3();
  19883. smallest = Number.MAX_VALUE;
  19884. tx = Math.abs( tangents[ 0 ].x );
  19885. ty = Math.abs( tangents[ 0 ].y );
  19886. tz = Math.abs( tangents[ 0 ].z );
  19887. if ( tx <= smallest ) {
  19888. smallest = tx;
  19889. normal.set( 1, 0, 0 );
  19890. }
  19891. if ( ty <= smallest ) {
  19892. smallest = ty;
  19893. normal.set( 0, 1, 0 );
  19894. }
  19895. if ( tz <= smallest ) {
  19896. normal.set( 0, 0, 1 );
  19897. }
  19898. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19899. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19900. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19901. }
  19902. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19903. for ( i = 1; i < numpoints; i++ ) {
  19904. normals[ i ] = normals[ i-1 ].clone();
  19905. binormals[ i ] = binormals[ i-1 ].clone();
  19906. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19907. if ( vec.length() > epsilon ) {
  19908. vec.normalize();
  19909. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  19910. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19911. }
  19912. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19913. }
  19914. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19915. if ( closed ) {
  19916. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  19917. theta /= ( numpoints - 1 );
  19918. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19919. theta = -theta;
  19920. }
  19921. for ( i = 1; i < numpoints; i++ ) {
  19922. // twist a little...
  19923. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19924. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19925. }
  19926. }
  19927. };
  19928. /**
  19929. * @author clockworkgeek / https://github.com/clockworkgeek
  19930. * @author timothypratley / https://github.com/timothypratley
  19931. * @author WestLangley / http://github.com/WestLangley
  19932. */
  19933. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19934. THREE.Geometry.call( this );
  19935. radius = radius || 1;
  19936. detail = detail || 0;
  19937. var that = this;
  19938. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19939. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19940. }
  19941. var midpoints = [], p = this.vertices;
  19942. var f = [];
  19943. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19944. var v1 = p[ faces[ i ][ 0 ] ];
  19945. var v2 = p[ faces[ i ][ 1 ] ];
  19946. var v3 = p[ faces[ i ][ 2 ] ];
  19947. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19948. }
  19949. for ( var i = 0, l = f.length; i < l; i ++ ) {
  19950. subdivide(f[ i ], detail);
  19951. }
  19952. // Handle case when face straddles the seam
  19953. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19954. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19955. var x0 = uvs[ 0 ].x;
  19956. var x1 = uvs[ 1 ].x;
  19957. var x2 = uvs[ 2 ].x;
  19958. var max = Math.max( x0, Math.max( x1, x2 ) );
  19959. var min = Math.min( x0, Math.min( x1, x2 ) );
  19960. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19961. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19962. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19963. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19964. }
  19965. }
  19966. // Apply radius
  19967. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19968. this.vertices[ i ].multiplyScalar( radius );
  19969. }
  19970. // Merge vertices
  19971. this.mergeVertices();
  19972. this.computeCentroids();
  19973. this.computeFaceNormals();
  19974. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19975. // Project vector onto sphere's surface
  19976. function prepare( vector ) {
  19977. var vertex = vector.normalize().clone();
  19978. vertex.index = that.vertices.push( vertex ) - 1;
  19979. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19980. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19981. var v = inclination( vector ) / Math.PI + 0.5;
  19982. vertex.uv = new THREE.Vector2( u, 1 - v );
  19983. return vertex;
  19984. }
  19985. // Approximate a curved face with recursively sub-divided triangles.
  19986. function make( v1, v2, v3 ) {
  19987. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19988. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19989. that.faces.push( face );
  19990. var azi = azimuth( face.centroid );
  19991. that.faceVertexUvs[ 0 ].push( [
  19992. correctUV( v1.uv, v1, azi ),
  19993. correctUV( v2.uv, v2, azi ),
  19994. correctUV( v3.uv, v3, azi )
  19995. ] );
  19996. }
  19997. // Analytically subdivide a face to the required detail level.
  19998. function subdivide(face, detail ) {
  19999. var cols = Math.pow(2, detail);
  20000. var cells = Math.pow(4, detail);
  20001. var a = prepare( that.vertices[ face.a ] );
  20002. var b = prepare( that.vertices[ face.b ] );
  20003. var c = prepare( that.vertices[ face.c ] );
  20004. var v = [];
  20005. // Construct all of the vertices for this subdivision.
  20006. for ( var i = 0 ; i <= cols; i ++ ) {
  20007. v[ i ] = [];
  20008. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20009. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20010. var rows = cols - i;
  20011. for ( var j = 0; j <= rows; j ++) {
  20012. if ( j == 0 && i == cols ) {
  20013. v[ i ][ j ] = aj;
  20014. } else {
  20015. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20016. }
  20017. }
  20018. }
  20019. // Construct all of the faces.
  20020. for ( var i = 0; i < cols ; i ++ ) {
  20021. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20022. var k = Math.floor( j / 2 );
  20023. if ( j % 2 == 0 ) {
  20024. make(
  20025. v[ i ][ k + 1],
  20026. v[ i + 1 ][ k ],
  20027. v[ i ][ k ]
  20028. );
  20029. } else {
  20030. make(
  20031. v[ i ][ k + 1 ],
  20032. v[ i + 1][ k + 1],
  20033. v[ i + 1 ][ k ]
  20034. );
  20035. }
  20036. }
  20037. }
  20038. }
  20039. // Angle around the Y axis, counter-clockwise when looking from above.
  20040. function azimuth( vector ) {
  20041. return Math.atan2( vector.z, -vector.x );
  20042. }
  20043. // Angle above the XZ plane.
  20044. function inclination( vector ) {
  20045. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20046. }
  20047. // Texture fixing helper. Spheres have some odd behaviours.
  20048. function correctUV( uv, vector, azimuth ) {
  20049. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20050. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20051. return uv.clone();
  20052. }
  20053. };
  20054. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20055. /**
  20056. * @author timothypratley / https://github.com/timothypratley
  20057. */
  20058. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20059. this.radius = radius;
  20060. this.detail = detail;
  20061. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20062. var vertices = [
  20063. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20064. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20065. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20066. ];
  20067. var faces = [
  20068. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20069. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20070. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20071. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20072. ];
  20073. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20074. };
  20075. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20076. /**
  20077. * @author timothypratley / https://github.com/timothypratley
  20078. */
  20079. THREE.OctahedronGeometry = function ( radius, detail ) {
  20080. var vertices = [
  20081. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20082. ];
  20083. var faces = [
  20084. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20085. ];
  20086. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20087. };
  20088. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20089. /**
  20090. * @author timothypratley / https://github.com/timothypratley
  20091. */
  20092. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20093. var vertices = [
  20094. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20095. ];
  20096. var faces = [
  20097. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20098. ];
  20099. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20100. };
  20101. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20102. /**
  20103. * @author zz85 / https://github.com/zz85
  20104. * Parametric Surfaces Geometry
  20105. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20106. *
  20107. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20108. *
  20109. */
  20110. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20111. THREE.Geometry.call( this );
  20112. var verts = this.vertices;
  20113. var faces = this.faces;
  20114. var uvs = this.faceVertexUvs[ 0 ];
  20115. var i, il, j, p;
  20116. var u, v;
  20117. var stackCount = stacks + 1;
  20118. var sliceCount = slices + 1;
  20119. for ( i = 0; i <= stacks; i ++ ) {
  20120. v = i / stacks;
  20121. for ( j = 0; j <= slices; j ++ ) {
  20122. u = j / slices;
  20123. p = func( u, v );
  20124. verts.push( p );
  20125. }
  20126. }
  20127. var a, b, c, d;
  20128. var uva, uvb, uvc, uvd;
  20129. for ( i = 0; i < stacks; i ++ ) {
  20130. for ( j = 0; j < slices; j ++ ) {
  20131. a = i * sliceCount + j;
  20132. b = i * sliceCount + j + 1;
  20133. c = (i + 1) * sliceCount + j + 1;
  20134. d = (i + 1) * sliceCount + j;
  20135. uva = new THREE.Vector2( j / slices, i / stacks );
  20136. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20137. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20138. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20139. faces.push( new THREE.Face3( a, b, d ) );
  20140. uvs.push( [ uva, uvb, uvd ] );
  20141. faces.push( new THREE.Face3( b, c, d ) );
  20142. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20143. }
  20144. }
  20145. // console.log(this);
  20146. // magic bullet
  20147. // var diff = this.mergeVertices();
  20148. // console.log('removed ', diff, ' vertices by merging');
  20149. this.computeCentroids();
  20150. this.computeFaceNormals();
  20151. this.computeVertexNormals();
  20152. };
  20153. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20154. /**
  20155. * @author sroucheray / http://sroucheray.org/
  20156. * @author mrdoob / http://mrdoob.com/
  20157. */
  20158. THREE.AxisHelper = function ( size ) {
  20159. size = size || 1;
  20160. var geometry = new THREE.Geometry();
  20161. geometry.vertices.push(
  20162. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20163. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20164. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20165. );
  20166. geometry.colors.push(
  20167. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20168. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20169. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20170. );
  20171. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20172. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20173. };
  20174. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20175. /**
  20176. * @author WestLangley / http://github.com/WestLangley
  20177. * @author zz85 / http://github.com/zz85
  20178. * @author bhouston / http://exocortex.com
  20179. *
  20180. * Creates an arrow for visualizing directions
  20181. *
  20182. * Parameters:
  20183. * dir - Vector3
  20184. * origin - Vector3
  20185. * length - Number
  20186. * hex - color in hex value
  20187. * headLength - Number
  20188. * headWidth - Number
  20189. */
  20190. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  20191. // dir is assumed to be normalized
  20192. THREE.Object3D.call( this );
  20193. if ( hex === undefined ) hex = 0xffff00;
  20194. if ( length === undefined ) length = 1;
  20195. if ( headLength === undefined ) headLength = 0.2 * length;
  20196. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20197. this.position = origin;
  20198. var lineGeometry = new THREE.Geometry();
  20199. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20200. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20201. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20202. this.line.matrixAutoUpdate = false;
  20203. this.add( this.line );
  20204. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20205. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20206. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20207. this.cone.matrixAutoUpdate = false;
  20208. this.add( this.cone );
  20209. this.setDirection( dir );
  20210. this.setLength( length, headLength, headWidth );
  20211. };
  20212. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20213. THREE.ArrowHelper.prototype.setDirection = function () {
  20214. var axis = new THREE.Vector3();
  20215. var radians;
  20216. return function ( dir ) {
  20217. // dir is assumed to be normalized
  20218. if ( dir.y > 0.99999 ) {
  20219. this.quaternion.set( 0, 0, 0, 1 );
  20220. } else if ( dir.y < - 0.99999 ) {
  20221. this.quaternion.set( 1, 0, 0, 0 );
  20222. } else {
  20223. axis.set( dir.z, 0, - dir.x ).normalize();
  20224. radians = Math.acos( dir.y );
  20225. this.quaternion.setFromAxisAngle( axis, radians );
  20226. }
  20227. };
  20228. }();
  20229. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20230. if ( headLength === undefined ) headLength = 0.2 * length;
  20231. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20232. this.line.scale.set( 1, length, 1 );
  20233. this.line.updateMatrix();
  20234. this.cone.scale.set( headWidth, headLength, headWidth );
  20235. this.cone.position.y = length;
  20236. this.cone.updateMatrix();
  20237. };
  20238. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20239. this.line.material.color.setHex( hex );
  20240. this.cone.material.color.setHex( hex );
  20241. };
  20242. /**
  20243. * @author mrdoob / http://mrdoob.com/
  20244. */
  20245. THREE.BoxHelper = function ( object ) {
  20246. // 5____4
  20247. // 1/___0/|
  20248. // | 6__|_7
  20249. // 2/___3/
  20250. var vertices = [
  20251. new THREE.Vector3( 1, 1, 1 ),
  20252. new THREE.Vector3( - 1, 1, 1 ),
  20253. new THREE.Vector3( - 1, - 1, 1 ),
  20254. new THREE.Vector3( 1, - 1, 1 ),
  20255. new THREE.Vector3( 1, 1, - 1 ),
  20256. new THREE.Vector3( - 1, 1, - 1 ),
  20257. new THREE.Vector3( - 1, - 1, - 1 ),
  20258. new THREE.Vector3( 1, - 1, - 1 )
  20259. ];
  20260. this.vertices = vertices;
  20261. // TODO: Wouldn't be nice if Line had .segments?
  20262. var geometry = new THREE.Geometry();
  20263. geometry.vertices.push(
  20264. vertices[ 0 ], vertices[ 1 ],
  20265. vertices[ 1 ], vertices[ 2 ],
  20266. vertices[ 2 ], vertices[ 3 ],
  20267. vertices[ 3 ], vertices[ 0 ],
  20268. vertices[ 4 ], vertices[ 5 ],
  20269. vertices[ 5 ], vertices[ 6 ],
  20270. vertices[ 6 ], vertices[ 7 ],
  20271. vertices[ 7 ], vertices[ 4 ],
  20272. vertices[ 0 ], vertices[ 4 ],
  20273. vertices[ 1 ], vertices[ 5 ],
  20274. vertices[ 2 ], vertices[ 6 ],
  20275. vertices[ 3 ], vertices[ 7 ]
  20276. );
  20277. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20278. if ( object !== undefined ) {
  20279. this.update( object );
  20280. }
  20281. };
  20282. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20283. THREE.BoxHelper.prototype.update = function ( object ) {
  20284. var geometry = object.geometry;
  20285. if ( geometry.boundingBox === null ) {
  20286. geometry.computeBoundingBox();
  20287. }
  20288. var min = geometry.boundingBox.min;
  20289. var max = geometry.boundingBox.max;
  20290. var vertices = this.vertices;
  20291. vertices[ 0 ].set( max.x, max.y, max.z );
  20292. vertices[ 1 ].set( min.x, max.y, max.z );
  20293. vertices[ 2 ].set( min.x, min.y, max.z );
  20294. vertices[ 3 ].set( max.x, min.y, max.z );
  20295. vertices[ 4 ].set( max.x, max.y, min.z );
  20296. vertices[ 5 ].set( min.x, max.y, min.z );
  20297. vertices[ 6 ].set( min.x, min.y, min.z );
  20298. vertices[ 7 ].set( max.x, min.y, min.z );
  20299. this.geometry.computeBoundingSphere();
  20300. this.geometry.verticesNeedUpdate = true;
  20301. this.matrixAutoUpdate = false;
  20302. this.matrixWorld = object.matrixWorld;
  20303. };
  20304. /**
  20305. * @author WestLangley / http://github.com/WestLangley
  20306. */
  20307. // a helper to show the world-axis-aligned bounding box for an object
  20308. THREE.BoundingBoxHelper = function ( object, hex ) {
  20309. var color = hex || 0x888888;
  20310. this.object = object;
  20311. this.box = new THREE.Box3();
  20312. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20313. };
  20314. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20315. THREE.BoundingBoxHelper.prototype.update = function () {
  20316. this.box.setFromObject( this.object );
  20317. this.box.size( this.scale );
  20318. this.box.center( this.position );
  20319. };
  20320. /**
  20321. * @author alteredq / http://alteredqualia.com/
  20322. *
  20323. * - shows frustum, line of sight and up of the camera
  20324. * - suitable for fast updates
  20325. * - based on frustum visualization in lightgl.js shadowmap example
  20326. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20327. */
  20328. THREE.CameraHelper = function ( camera ) {
  20329. var geometry = new THREE.Geometry();
  20330. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20331. var pointMap = {};
  20332. // colors
  20333. var hexFrustum = 0xffaa00;
  20334. var hexCone = 0xff0000;
  20335. var hexUp = 0x00aaff;
  20336. var hexTarget = 0xffffff;
  20337. var hexCross = 0x333333;
  20338. // near
  20339. addLine( "n1", "n2", hexFrustum );
  20340. addLine( "n2", "n4", hexFrustum );
  20341. addLine( "n4", "n3", hexFrustum );
  20342. addLine( "n3", "n1", hexFrustum );
  20343. // far
  20344. addLine( "f1", "f2", hexFrustum );
  20345. addLine( "f2", "f4", hexFrustum );
  20346. addLine( "f4", "f3", hexFrustum );
  20347. addLine( "f3", "f1", hexFrustum );
  20348. // sides
  20349. addLine( "n1", "f1", hexFrustum );
  20350. addLine( "n2", "f2", hexFrustum );
  20351. addLine( "n3", "f3", hexFrustum );
  20352. addLine( "n4", "f4", hexFrustum );
  20353. // cone
  20354. addLine( "p", "n1", hexCone );
  20355. addLine( "p", "n2", hexCone );
  20356. addLine( "p", "n3", hexCone );
  20357. addLine( "p", "n4", hexCone );
  20358. // up
  20359. addLine( "u1", "u2", hexUp );
  20360. addLine( "u2", "u3", hexUp );
  20361. addLine( "u3", "u1", hexUp );
  20362. // target
  20363. addLine( "c", "t", hexTarget );
  20364. addLine( "p", "c", hexCross );
  20365. // cross
  20366. addLine( "cn1", "cn2", hexCross );
  20367. addLine( "cn3", "cn4", hexCross );
  20368. addLine( "cf1", "cf2", hexCross );
  20369. addLine( "cf3", "cf4", hexCross );
  20370. function addLine( a, b, hex ) {
  20371. addPoint( a, hex );
  20372. addPoint( b, hex );
  20373. }
  20374. function addPoint( id, hex ) {
  20375. geometry.vertices.push( new THREE.Vector3() );
  20376. geometry.colors.push( new THREE.Color( hex ) );
  20377. if ( pointMap[ id ] === undefined ) {
  20378. pointMap[ id ] = [];
  20379. }
  20380. pointMap[ id ].push( geometry.vertices.length - 1 );
  20381. }
  20382. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20383. this.camera = camera;
  20384. this.matrixWorld = camera.matrixWorld;
  20385. this.matrixAutoUpdate = false;
  20386. this.pointMap = pointMap;
  20387. this.update();
  20388. };
  20389. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20390. THREE.CameraHelper.prototype.update = function () {
  20391. var vector = new THREE.Vector3();
  20392. var camera = new THREE.Camera();
  20393. var projector = new THREE.Projector();
  20394. return function () {
  20395. var scope = this;
  20396. var w = 1, h = 1;
  20397. // we need just camera projection matrix
  20398. // world matrix must be identity
  20399. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20400. // center / target
  20401. setPoint( "c", 0, 0, -1 );
  20402. setPoint( "t", 0, 0, 1 );
  20403. // near
  20404. setPoint( "n1", -w, -h, -1 );
  20405. setPoint( "n2", w, -h, -1 );
  20406. setPoint( "n3", -w, h, -1 );
  20407. setPoint( "n4", w, h, -1 );
  20408. // far
  20409. setPoint( "f1", -w, -h, 1 );
  20410. setPoint( "f2", w, -h, 1 );
  20411. setPoint( "f3", -w, h, 1 );
  20412. setPoint( "f4", w, h, 1 );
  20413. // up
  20414. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20415. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20416. setPoint( "u3", 0, h * 2, -1 );
  20417. // cross
  20418. setPoint( "cf1", -w, 0, 1 );
  20419. setPoint( "cf2", w, 0, 1 );
  20420. setPoint( "cf3", 0, -h, 1 );
  20421. setPoint( "cf4", 0, h, 1 );
  20422. setPoint( "cn1", -w, 0, -1 );
  20423. setPoint( "cn2", w, 0, -1 );
  20424. setPoint( "cn3", 0, -h, -1 );
  20425. setPoint( "cn4", 0, h, -1 );
  20426. function setPoint( point, x, y, z ) {
  20427. vector.set( x, y, z );
  20428. projector.unprojectVector( vector, camera );
  20429. var points = scope.pointMap[ point ];
  20430. if ( points !== undefined ) {
  20431. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20432. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20433. }
  20434. }
  20435. }
  20436. this.geometry.verticesNeedUpdate = true;
  20437. };
  20438. }();
  20439. /**
  20440. * @author alteredq / http://alteredqualia.com/
  20441. * @author mrdoob / http://mrdoob.com/
  20442. * @author WestLangley / http://github.com/WestLangley
  20443. */
  20444. THREE.DirectionalLightHelper = function ( light, size ) {
  20445. THREE.Object3D.call( this );
  20446. this.light = light;
  20447. this.light.updateMatrixWorld();
  20448. this.matrixWorld = light.matrixWorld;
  20449. this.matrixAutoUpdate = false;
  20450. size = size || 1;
  20451. var geometry = new THREE.PlaneGeometry( size, size );
  20452. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20453. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20454. this.lightPlane = new THREE.Mesh( geometry, material );
  20455. this.add( this.lightPlane );
  20456. geometry = new THREE.Geometry();
  20457. geometry.vertices.push( new THREE.Vector3() );
  20458. geometry.vertices.push( new THREE.Vector3() );
  20459. material = new THREE.LineBasicMaterial( { fog: false } );
  20460. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20461. this.targetLine = new THREE.Line( geometry, material );
  20462. this.add( this.targetLine );
  20463. this.update();
  20464. };
  20465. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20466. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20467. this.lightPlane.geometry.dispose();
  20468. this.lightPlane.material.dispose();
  20469. this.targetLine.geometry.dispose();
  20470. this.targetLine.material.dispose();
  20471. };
  20472. THREE.DirectionalLightHelper.prototype.update = function () {
  20473. var v1 = new THREE.Vector3();
  20474. var v2 = new THREE.Vector3();
  20475. var v3 = new THREE.Vector3();
  20476. return function () {
  20477. v1.setFromMatrixPosition( this.light.matrixWorld );
  20478. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20479. v3.subVectors( v2, v1 );
  20480. this.lightPlane.lookAt( v3 );
  20481. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20482. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20483. this.targetLine.geometry.verticesNeedUpdate = true;
  20484. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20485. }
  20486. }();
  20487. /**
  20488. * @author mrdoob / http://mrdoob.com/
  20489. * @author WestLangley / http://github.com/WestLangley
  20490. */
  20491. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20492. this.object = object;
  20493. this.size = size || 1;
  20494. var color = hex || 0xffff00;
  20495. var width = linewidth || 1;
  20496. var geometry = new THREE.Geometry();
  20497. var faces = this.object.geometry.faces;
  20498. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20499. geometry.vertices.push( new THREE.Vector3() );
  20500. geometry.vertices.push( new THREE.Vector3() );
  20501. }
  20502. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20503. this.matrixAutoUpdate = false;
  20504. this.normalMatrix = new THREE.Matrix3();
  20505. this.update();
  20506. };
  20507. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20508. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20509. var v1 = new THREE.Vector3();
  20510. return function ( object ) {
  20511. this.object.updateMatrixWorld( true );
  20512. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20513. var vertices = this.geometry.vertices;
  20514. var faces = this.object.geometry.faces;
  20515. var worldMatrix = this.object.matrixWorld;
  20516. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20517. var face = faces[ i ];
  20518. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20519. var idx = 2 * i;
  20520. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  20521. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20522. }
  20523. this.geometry.verticesNeedUpdate = true;
  20524. return this;
  20525. }
  20526. }());
  20527. /**
  20528. * @author mrdoob / http://mrdoob.com/
  20529. */
  20530. THREE.GridHelper = function ( size, step ) {
  20531. var geometry = new THREE.Geometry();
  20532. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20533. this.color1 = new THREE.Color( 0x444444 );
  20534. this.color2 = new THREE.Color( 0x888888 );
  20535. for ( var i = - size; i <= size; i += step ) {
  20536. geometry.vertices.push(
  20537. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20538. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20539. );
  20540. var color = i === 0 ? this.color1 : this.color2;
  20541. geometry.colors.push( color, color, color, color );
  20542. }
  20543. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20544. };
  20545. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20546. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20547. this.color1.set( colorCenterLine );
  20548. this.color2.set( colorGrid );
  20549. this.geometry.colorsNeedUpdate = true;
  20550. }
  20551. /**
  20552. * @author alteredq / http://alteredqualia.com/
  20553. * @author mrdoob / http://mrdoob.com/
  20554. */
  20555. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20556. THREE.Object3D.call( this );
  20557. this.light = light;
  20558. this.light.updateMatrixWorld();
  20559. this.matrixWorld = light.matrixWorld;
  20560. this.matrixAutoUpdate = false;
  20561. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20562. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20563. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20564. for ( var i = 0, il = 8; i < il; i ++ ) {
  20565. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20566. }
  20567. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20568. this.lightSphere = new THREE.Mesh( geometry, material );
  20569. this.add( this.lightSphere );
  20570. this.update();
  20571. };
  20572. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20573. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20574. this.lightSphere.geometry.dispose();
  20575. this.lightSphere.material.dispose();
  20576. };
  20577. THREE.HemisphereLightHelper.prototype.update = function () {
  20578. var vector = new THREE.Vector3();
  20579. return function () {
  20580. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20581. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20582. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20583. this.lightSphere.geometry.colorsNeedUpdate = true;
  20584. }
  20585. }();
  20586. /**
  20587. * @author alteredq / http://alteredqualia.com/
  20588. * @author mrdoob / http://mrdoob.com/
  20589. */
  20590. THREE.PointLightHelper = function ( light, sphereSize ) {
  20591. this.light = light;
  20592. this.light.updateMatrixWorld();
  20593. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20594. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20595. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20596. THREE.Mesh.call( this, geometry, material );
  20597. this.matrixWorld = this.light.matrixWorld;
  20598. this.matrixAutoUpdate = false;
  20599. /*
  20600. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20601. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20602. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20603. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20604. var d = light.distance;
  20605. if ( d === 0.0 ) {
  20606. this.lightDistance.visible = false;
  20607. } else {
  20608. this.lightDistance.scale.set( d, d, d );
  20609. }
  20610. this.add( this.lightDistance );
  20611. */
  20612. };
  20613. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20614. THREE.PointLightHelper.prototype.dispose = function () {
  20615. this.geometry.dispose();
  20616. this.material.dispose();
  20617. };
  20618. THREE.PointLightHelper.prototype.update = function () {
  20619. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20620. /*
  20621. var d = this.light.distance;
  20622. if ( d === 0.0 ) {
  20623. this.lightDistance.visible = false;
  20624. } else {
  20625. this.lightDistance.visible = true;
  20626. this.lightDistance.scale.set( d, d, d );
  20627. }
  20628. */
  20629. };
  20630. /**
  20631. * @author alteredq / http://alteredqualia.com/
  20632. * @author mrdoob / http://mrdoob.com/
  20633. * @author WestLangley / http://github.com/WestLangley
  20634. */
  20635. THREE.SpotLightHelper = function ( light ) {
  20636. THREE.Object3D.call( this );
  20637. this.light = light;
  20638. this.light.updateMatrixWorld();
  20639. this.matrixWorld = light.matrixWorld;
  20640. this.matrixAutoUpdate = false;
  20641. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20642. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20643. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20644. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20645. this.cone = new THREE.Mesh( geometry, material );
  20646. this.add( this.cone );
  20647. this.update();
  20648. };
  20649. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20650. THREE.SpotLightHelper.prototype.dispose = function () {
  20651. this.cone.geometry.dispose();
  20652. this.cone.material.dispose();
  20653. };
  20654. THREE.SpotLightHelper.prototype.update = function () {
  20655. var vector = new THREE.Vector3();
  20656. var vector2 = new THREE.Vector3();
  20657. return function () {
  20658. var coneLength = this.light.distance ? this.light.distance : 10000;
  20659. var coneWidth = coneLength * Math.tan( this.light.angle );
  20660. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20661. vector.setFromMatrixPosition( this.light.matrixWorld );
  20662. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20663. this.cone.lookAt( vector2.sub( vector ) );
  20664. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20665. };
  20666. }();
  20667. /**
  20668. * @author mrdoob / http://mrdoob.com/
  20669. * @author WestLangley / http://github.com/WestLangley
  20670. */
  20671. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20672. this.object = object;
  20673. this.size = size || 1;
  20674. var color = hex || 0xff0000;
  20675. var width = linewidth || 1;
  20676. var geometry = new THREE.Geometry();
  20677. var vertices = object.geometry.vertices;
  20678. var faces = object.geometry.faces;
  20679. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20680. var face = faces[ i ];
  20681. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20682. geometry.vertices.push( new THREE.Vector3() );
  20683. geometry.vertices.push( new THREE.Vector3() );
  20684. }
  20685. }
  20686. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20687. this.matrixAutoUpdate = false;
  20688. this.normalMatrix = new THREE.Matrix3();
  20689. this.update();
  20690. };
  20691. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20692. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20693. var v1 = new THREE.Vector3();
  20694. return function( object ) {
  20695. var keys = [ 'a', 'b', 'c', 'd' ];
  20696. this.object.updateMatrixWorld( true );
  20697. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20698. var vertices = this.geometry.vertices;
  20699. var verts = this.object.geometry.vertices;
  20700. var faces = this.object.geometry.faces;
  20701. var worldMatrix = this.object.matrixWorld;
  20702. var idx = 0;
  20703. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20704. var face = faces[ i ];
  20705. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20706. var vertexId = face[ keys[ j ] ];
  20707. var vertex = verts[ vertexId ];
  20708. var normal = face.vertexNormals[ j ];
  20709. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20710. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20711. v1.add( vertices[ idx ] );
  20712. idx = idx + 1;
  20713. vertices[ idx ].copy( v1 );
  20714. idx = idx + 1;
  20715. }
  20716. }
  20717. this.geometry.verticesNeedUpdate = true;
  20718. return this;
  20719. }
  20720. }());
  20721. /**
  20722. * @author mrdoob / http://mrdoob.com/
  20723. * @author WestLangley / http://github.com/WestLangley
  20724. */
  20725. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  20726. this.object = object;
  20727. this.size = size || 1;
  20728. var color = hex || 0x0000ff;
  20729. var width = linewidth || 1;
  20730. var geometry = new THREE.Geometry();
  20731. var vertices = object.geometry.vertices;
  20732. var faces = object.geometry.faces;
  20733. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20734. var face = faces[ i ];
  20735. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20736. geometry.vertices.push( new THREE.Vector3() );
  20737. geometry.vertices.push( new THREE.Vector3() );
  20738. }
  20739. }
  20740. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20741. this.matrixAutoUpdate = false;
  20742. this.update();
  20743. };
  20744. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  20745. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  20746. var v1 = new THREE.Vector3();
  20747. return function( object ) {
  20748. var keys = [ 'a', 'b', 'c', 'd' ];
  20749. this.object.updateMatrixWorld( true );
  20750. var vertices = this.geometry.vertices;
  20751. var verts = this.object.geometry.vertices;
  20752. var faces = this.object.geometry.faces;
  20753. var worldMatrix = this.object.matrixWorld;
  20754. var idx = 0;
  20755. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20756. var face = faces[ i ];
  20757. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  20758. var vertexId = face[ keys[ j ] ];
  20759. var vertex = verts[ vertexId ];
  20760. var tangent = face.vertexTangents[ j ];
  20761. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  20762. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  20763. v1.add( vertices[ idx ] );
  20764. idx = idx + 1;
  20765. vertices[ idx ].copy( v1 );
  20766. idx = idx + 1;
  20767. }
  20768. }
  20769. this.geometry.verticesNeedUpdate = true;
  20770. return this;
  20771. }
  20772. }());
  20773. /**
  20774. * @author mrdoob / http://mrdoob.com/
  20775. */
  20776. THREE.WireframeHelper = function ( object ) {
  20777. var edge = [ 0, 0 ], hash = {};
  20778. var sortFunction = function ( a, b ) { return a - b };
  20779. var keys = [ 'a', 'b', 'c', 'd' ];
  20780. var geometry = new THREE.BufferGeometry();
  20781. var numEdges = 0;
  20782. if ( object.geometry instanceof THREE.Geometry ) {
  20783. var vertices = object.geometry.vertices;
  20784. var faces = object.geometry.faces;
  20785. // allocate maximal size
  20786. var edges = new Uint32Array(6 * faces.length);
  20787. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20788. var face = faces[ i ];
  20789. for ( var j = 0; j < 3; j ++ ) {
  20790. edge[ 0 ] = face[ keys[ j ] ];
  20791. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20792. edge.sort( sortFunction );
  20793. var key = edge.toString();
  20794. if ( hash[ key ] === undefined ) {
  20795. edges[ 2 * numEdges ] = edge[ 0 ];
  20796. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20797. hash[ key ] = true;
  20798. numEdges ++;
  20799. }
  20800. }
  20801. }
  20802. geometry.addAttribute( 'position', Float32Array, 2 * numEdges , 3 );
  20803. var coords = geometry.attributes.position.array;
  20804. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20805. for ( var j = 0; j < 2; j ++ ) {
  20806. var vertex = vertices[ edges [ 2 * i + j] ];
  20807. var index = 6 * i + 3 * j;
  20808. coords[ index + 0 ] = vertex.x;
  20809. coords[ index + 1 ] = vertex.y;
  20810. coords[ index + 2 ] = vertex.z;
  20811. }
  20812. }
  20813. } else {
  20814. var vertices = object.geometry.attributes.position.array;
  20815. var faces = object.geometry.attributes.index.array;
  20816. // allocate maximal size
  20817. var edges = new Uint32Array(2 * faces.length);
  20818. for ( var i = 0, l = faces.length / 3; i < l; i ++ ) {
  20819. for ( var j = 0; j < 3; j ++ ) {
  20820. var index = i * 3;
  20821. edge[ 0 ] = faces[ index + j ];
  20822. edge[ 1 ] = faces[ index + ( j + 1 ) % 3 ];
  20823. edge.sort( sortFunction );
  20824. var key = edge.toString();
  20825. if ( hash[ key ] === undefined ) {
  20826. edges[ 2 * numEdges ] = edge[ 0 ];
  20827. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  20828. hash[ key ] = true;
  20829. numEdges ++;
  20830. }
  20831. }
  20832. }
  20833. geometry.addAttribute( 'position', Float32Array, 2 * numEdges , 3 );
  20834. var coords = geometry.attributes.position.array;
  20835. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  20836. for ( var j = 0; j < 2; j ++ ) {
  20837. var index = 6 * i + 3 * j;
  20838. var index2 = 3 * edges[ 2 * i + j];
  20839. coords[ index + 0 ] = vertices[ index2 ];
  20840. coords[ index + 1 ] = vertices[ index2 + 1 ];
  20841. coords[ index + 2 ] = vertices[ index2 + 2 ];
  20842. }
  20843. }
  20844. }
  20845. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  20846. this.matrixAutoUpdate = false;
  20847. this.matrixWorld = object.matrixWorld;
  20848. };
  20849. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  20850. /**
  20851. * @author alteredq / http://alteredqualia.com/
  20852. */
  20853. THREE.ImmediateRenderObject = function () {
  20854. THREE.Object3D.call( this );
  20855. this.render = function ( renderCallback ) { };
  20856. };
  20857. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20858. /**
  20859. * @author mikael emtinger / http://gomo.se/
  20860. * @author alteredq / http://alteredqualia.com/
  20861. */
  20862. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20863. THREE.Object3D.call( this );
  20864. this.lensFlares = [];
  20865. this.positionScreen = new THREE.Vector3();
  20866. this.customUpdateCallback = undefined;
  20867. if( texture !== undefined ) {
  20868. this.add( texture, size, distance, blending, color );
  20869. }
  20870. };
  20871. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20872. /*
  20873. * Add: adds another flare
  20874. */
  20875. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20876. if( size === undefined ) size = -1;
  20877. if( distance === undefined ) distance = 0;
  20878. if( opacity === undefined ) opacity = 1;
  20879. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20880. if( blending === undefined ) blending = THREE.NormalBlending;
  20881. distance = Math.min( distance, Math.max( 0, distance ) );
  20882. this.lensFlares.push( { texture: texture, // THREE.Texture
  20883. size: size, // size in pixels (-1 = use texture.width)
  20884. distance: distance, // distance (0-1) from light source (0=at light source)
  20885. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20886. scale: 1, // scale
  20887. rotation: 1, // rotation
  20888. opacity: opacity, // opacity
  20889. color: color, // color
  20890. blending: blending } ); // blending
  20891. };
  20892. /*
  20893. * Update lens flares update positions on all flares based on the screen position
  20894. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20895. */
  20896. THREE.LensFlare.prototype.updateLensFlares = function () {
  20897. var f, fl = this.lensFlares.length;
  20898. var flare;
  20899. var vecX = -this.positionScreen.x * 2;
  20900. var vecY = -this.positionScreen.y * 2;
  20901. for( f = 0; f < fl; f ++ ) {
  20902. flare = this.lensFlares[ f ];
  20903. flare.x = this.positionScreen.x + vecX * flare.distance;
  20904. flare.y = this.positionScreen.y + vecY * flare.distance;
  20905. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20906. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20907. }
  20908. };
  20909. /**
  20910. * @author alteredq / http://alteredqualia.com/
  20911. */
  20912. THREE.MorphBlendMesh = function( geometry, material ) {
  20913. THREE.Mesh.call( this, geometry, material );
  20914. this.animationsMap = {};
  20915. this.animationsList = [];
  20916. // prepare default animation
  20917. // (all frames played together in 1 second)
  20918. var numFrames = this.geometry.morphTargets.length;
  20919. var name = "__default";
  20920. var startFrame = 0;
  20921. var endFrame = numFrames - 1;
  20922. var fps = numFrames / 1;
  20923. this.createAnimation( name, startFrame, endFrame, fps );
  20924. this.setAnimationWeight( name, 1 );
  20925. };
  20926. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20927. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20928. var animation = {
  20929. startFrame: start,
  20930. endFrame: end,
  20931. length: end - start + 1,
  20932. fps: fps,
  20933. duration: ( end - start ) / fps,
  20934. lastFrame: 0,
  20935. currentFrame: 0,
  20936. active: false,
  20937. time: 0,
  20938. direction: 1,
  20939. weight: 1,
  20940. directionBackwards: false,
  20941. mirroredLoop: false
  20942. };
  20943. this.animationsMap[ name ] = animation;
  20944. this.animationsList.push( animation );
  20945. };
  20946. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20947. var pattern = /([a-z]+)(\d+)/;
  20948. var firstAnimation, frameRanges = {};
  20949. var geometry = this.geometry;
  20950. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20951. var morph = geometry.morphTargets[ i ];
  20952. var chunks = morph.name.match( pattern );
  20953. if ( chunks && chunks.length > 1 ) {
  20954. var name = chunks[ 1 ];
  20955. var num = chunks[ 2 ];
  20956. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20957. var range = frameRanges[ name ];
  20958. if ( i < range.start ) range.start = i;
  20959. if ( i > range.end ) range.end = i;
  20960. if ( ! firstAnimation ) firstAnimation = name;
  20961. }
  20962. }
  20963. for ( var name in frameRanges ) {
  20964. var range = frameRanges[ name ];
  20965. this.createAnimation( name, range.start, range.end, fps );
  20966. }
  20967. this.firstAnimation = firstAnimation;
  20968. };
  20969. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20970. var animation = this.animationsMap[ name ];
  20971. if ( animation ) {
  20972. animation.direction = 1;
  20973. animation.directionBackwards = false;
  20974. }
  20975. };
  20976. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20977. var animation = this.animationsMap[ name ];
  20978. if ( animation ) {
  20979. animation.direction = -1;
  20980. animation.directionBackwards = true;
  20981. }
  20982. };
  20983. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20984. var animation = this.animationsMap[ name ];
  20985. if ( animation ) {
  20986. animation.fps = fps;
  20987. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20988. }
  20989. };
  20990. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20991. var animation = this.animationsMap[ name ];
  20992. if ( animation ) {
  20993. animation.duration = duration;
  20994. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20995. }
  20996. };
  20997. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20998. var animation = this.animationsMap[ name ];
  20999. if ( animation ) {
  21000. animation.weight = weight;
  21001. }
  21002. };
  21003. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21004. var animation = this.animationsMap[ name ];
  21005. if ( animation ) {
  21006. animation.time = time;
  21007. }
  21008. };
  21009. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21010. var time = 0;
  21011. var animation = this.animationsMap[ name ];
  21012. if ( animation ) {
  21013. time = animation.time;
  21014. }
  21015. return time;
  21016. };
  21017. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21018. var duration = -1;
  21019. var animation = this.animationsMap[ name ];
  21020. if ( animation ) {
  21021. duration = animation.duration;
  21022. }
  21023. return duration;
  21024. };
  21025. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21026. var animation = this.animationsMap[ name ];
  21027. if ( animation ) {
  21028. animation.time = 0;
  21029. animation.active = true;
  21030. } else {
  21031. console.warn( "animation[" + name + "] undefined" );
  21032. }
  21033. };
  21034. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21035. var animation = this.animationsMap[ name ];
  21036. if ( animation ) {
  21037. animation.active = false;
  21038. }
  21039. };
  21040. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21041. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21042. var animation = this.animationsList[ i ];
  21043. if ( ! animation.active ) continue;
  21044. var frameTime = animation.duration / animation.length;
  21045. animation.time += animation.direction * delta;
  21046. if ( animation.mirroredLoop ) {
  21047. if ( animation.time > animation.duration || animation.time < 0 ) {
  21048. animation.direction *= -1;
  21049. if ( animation.time > animation.duration ) {
  21050. animation.time = animation.duration;
  21051. animation.directionBackwards = true;
  21052. }
  21053. if ( animation.time < 0 ) {
  21054. animation.time = 0;
  21055. animation.directionBackwards = false;
  21056. }
  21057. }
  21058. } else {
  21059. animation.time = animation.time % animation.duration;
  21060. if ( animation.time < 0 ) animation.time += animation.duration;
  21061. }
  21062. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21063. var weight = animation.weight;
  21064. if ( keyframe !== animation.currentFrame ) {
  21065. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21066. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21067. this.morphTargetInfluences[ keyframe ] = 0;
  21068. animation.lastFrame = animation.currentFrame;
  21069. animation.currentFrame = keyframe;
  21070. }
  21071. var mix = ( animation.time % frameTime ) / frameTime;
  21072. if ( animation.directionBackwards ) mix = 1 - mix;
  21073. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21074. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21075. }
  21076. };
  21077. /**
  21078. * @author mikael emtinger / http://gomo.se/
  21079. * @author alteredq / http://alteredqualia.com/
  21080. */
  21081. THREE.LensFlarePlugin = function () {
  21082. var _gl, _renderer, _precision, _lensFlare = {};
  21083. this.init = function ( renderer ) {
  21084. _gl = renderer.context;
  21085. _renderer = renderer;
  21086. _precision = renderer.getPrecision();
  21087. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21088. _lensFlare.faces = new Uint16Array( 6 );
  21089. var i = 0;
  21090. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21091. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21092. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21093. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21094. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21095. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21096. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21097. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21098. i = 0;
  21099. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21100. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21101. // buffers
  21102. _lensFlare.vertexBuffer = _gl.createBuffer();
  21103. _lensFlare.elementBuffer = _gl.createBuffer();
  21104. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21105. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21106. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21107. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21108. // textures
  21109. _lensFlare.tempTexture = _gl.createTexture();
  21110. _lensFlare.occlusionTexture = _gl.createTexture();
  21111. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21112. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21113. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21114. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21115. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21116. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21117. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21118. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21119. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21120. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21121. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21122. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21123. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21124. _lensFlare.hasVertexTexture = false;
  21125. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21126. } else {
  21127. _lensFlare.hasVertexTexture = true;
  21128. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21129. }
  21130. _lensFlare.attributes = {};
  21131. _lensFlare.uniforms = {};
  21132. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21133. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21134. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21135. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21136. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21137. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21138. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21139. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21140. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21141. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21142. };
  21143. /*
  21144. * Render lens flares
  21145. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21146. * reads these back and calculates occlusion.
  21147. * Then _lensFlare.update_lensFlares() is called to re-position and
  21148. * update transparency of flares. Then they are rendered.
  21149. *
  21150. */
  21151. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21152. var flares = scene.__webglFlares,
  21153. nFlares = flares.length;
  21154. if ( ! nFlares ) return;
  21155. var tempPosition = new THREE.Vector3();
  21156. var invAspect = viewportHeight / viewportWidth,
  21157. halfViewportWidth = viewportWidth * 0.5,
  21158. halfViewportHeight = viewportHeight * 0.5;
  21159. var size = 16 / viewportHeight,
  21160. scale = new THREE.Vector2( size * invAspect, size );
  21161. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21162. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21163. var uniforms = _lensFlare.uniforms,
  21164. attributes = _lensFlare.attributes;
  21165. // set _lensFlare program and reset blending
  21166. _gl.useProgram( _lensFlare.program );
  21167. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21168. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21169. // loop through all lens flares to update their occlusion and positions
  21170. // setup gl and common used attribs/unforms
  21171. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21172. _gl.uniform1i( uniforms.map, 1 );
  21173. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21174. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21175. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21176. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21177. _gl.disable( _gl.CULL_FACE );
  21178. _gl.depthMask( false );
  21179. var i, j, jl, flare, sprite;
  21180. for ( i = 0; i < nFlares; i ++ ) {
  21181. size = 16 / viewportHeight;
  21182. scale.set( size * invAspect, size );
  21183. // calc object screen position
  21184. flare = flares[ i ];
  21185. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21186. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21187. tempPosition.applyProjection( camera.projectionMatrix );
  21188. // setup arrays for gl programs
  21189. screenPosition.copy( tempPosition )
  21190. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21191. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21192. // screen cull
  21193. if ( _lensFlare.hasVertexTexture || (
  21194. screenPositionPixels.x > 0 &&
  21195. screenPositionPixels.x < viewportWidth &&
  21196. screenPositionPixels.y > 0 &&
  21197. screenPositionPixels.y < viewportHeight ) ) {
  21198. // save current RGB to temp texture
  21199. _gl.activeTexture( _gl.TEXTURE1 );
  21200. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21201. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21202. // render pink quad
  21203. _gl.uniform1i( uniforms.renderType, 0 );
  21204. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21205. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21206. _gl.disable( _gl.BLEND );
  21207. _gl.enable( _gl.DEPTH_TEST );
  21208. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21209. // copy result to occlusionMap
  21210. _gl.activeTexture( _gl.TEXTURE0 );
  21211. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21212. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21213. // restore graphics
  21214. _gl.uniform1i( uniforms.renderType, 1 );
  21215. _gl.disable( _gl.DEPTH_TEST );
  21216. _gl.activeTexture( _gl.TEXTURE1 );
  21217. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21218. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21219. // update object positions
  21220. flare.positionScreen.copy( screenPosition )
  21221. if ( flare.customUpdateCallback ) {
  21222. flare.customUpdateCallback( flare );
  21223. } else {
  21224. flare.updateLensFlares();
  21225. }
  21226. // render flares
  21227. _gl.uniform1i( uniforms.renderType, 2 );
  21228. _gl.enable( _gl.BLEND );
  21229. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21230. sprite = flare.lensFlares[ j ];
  21231. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21232. screenPosition.x = sprite.x;
  21233. screenPosition.y = sprite.y;
  21234. screenPosition.z = sprite.z;
  21235. size = sprite.size * sprite.scale / viewportHeight;
  21236. scale.x = size * invAspect;
  21237. scale.y = size;
  21238. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21239. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21240. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21241. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21242. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21243. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21244. _renderer.setTexture( sprite.texture, 1 );
  21245. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21246. }
  21247. }
  21248. }
  21249. }
  21250. // restore gl
  21251. _gl.enable( _gl.CULL_FACE );
  21252. _gl.enable( _gl.DEPTH_TEST );
  21253. _gl.depthMask( true );
  21254. };
  21255. function createProgram ( shader, precision ) {
  21256. var program = _gl.createProgram();
  21257. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21258. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21259. var prefix = "precision " + precision + " float;\n";
  21260. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21261. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21262. _gl.compileShader( fragmentShader );
  21263. _gl.compileShader( vertexShader );
  21264. _gl.attachShader( program, fragmentShader );
  21265. _gl.attachShader( program, vertexShader );
  21266. _gl.linkProgram( program );
  21267. return program;
  21268. };
  21269. };
  21270. /**
  21271. * @author alteredq / http://alteredqualia.com/
  21272. */
  21273. THREE.ShadowMapPlugin = function () {
  21274. var _gl,
  21275. _renderer,
  21276. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21277. _frustum = new THREE.Frustum(),
  21278. _projScreenMatrix = new THREE.Matrix4(),
  21279. _min = new THREE.Vector3(),
  21280. _max = new THREE.Vector3(),
  21281. _matrixPosition = new THREE.Vector3();
  21282. this.init = function ( renderer ) {
  21283. _gl = renderer.context;
  21284. _renderer = renderer;
  21285. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21286. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21287. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21288. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21289. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21290. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21291. _depthMaterial._shadowPass = true;
  21292. _depthMaterialMorph._shadowPass = true;
  21293. _depthMaterialSkin._shadowPass = true;
  21294. _depthMaterialMorphSkin._shadowPass = true;
  21295. };
  21296. this.render = function ( scene, camera ) {
  21297. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21298. this.update( scene, camera );
  21299. };
  21300. this.update = function ( scene, camera ) {
  21301. var i, il, j, jl, n,
  21302. shadowMap, shadowMatrix, shadowCamera,
  21303. program, buffer, material,
  21304. webglObject, object, light,
  21305. renderList,
  21306. lights = [],
  21307. k = 0,
  21308. fog = null;
  21309. // set GL state for depth map
  21310. _gl.clearColor( 1, 1, 1, 1 );
  21311. _gl.disable( _gl.BLEND );
  21312. _gl.enable( _gl.CULL_FACE );
  21313. _gl.frontFace( _gl.CCW );
  21314. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21315. _gl.cullFace( _gl.FRONT );
  21316. } else {
  21317. _gl.cullFace( _gl.BACK );
  21318. }
  21319. _renderer.setDepthTest( true );
  21320. // preprocess lights
  21321. // - skip lights that are not casting shadows
  21322. // - create virtual lights for cascaded shadow maps
  21323. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21324. light = scene.__lights[ i ];
  21325. if ( ! light.castShadow ) continue;
  21326. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21327. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21328. var virtualLight;
  21329. if ( ! light.shadowCascadeArray[ n ] ) {
  21330. virtualLight = createVirtualLight( light, n );
  21331. virtualLight.originalCamera = camera;
  21332. var gyro = new THREE.Gyroscope();
  21333. gyro.position = light.shadowCascadeOffset;
  21334. gyro.add( virtualLight );
  21335. gyro.add( virtualLight.target );
  21336. camera.add( gyro );
  21337. light.shadowCascadeArray[ n ] = virtualLight;
  21338. console.log( "Created virtualLight", virtualLight );
  21339. } else {
  21340. virtualLight = light.shadowCascadeArray[ n ];
  21341. }
  21342. updateVirtualLight( light, n );
  21343. lights[ k ] = virtualLight;
  21344. k ++;
  21345. }
  21346. } else {
  21347. lights[ k ] = light;
  21348. k ++;
  21349. }
  21350. }
  21351. // render depth map
  21352. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21353. light = lights[ i ];
  21354. if ( ! light.shadowMap ) {
  21355. var shadowFilter = THREE.LinearFilter;
  21356. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21357. shadowFilter = THREE.NearestFilter;
  21358. }
  21359. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21360. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21361. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21362. light.shadowMatrix = new THREE.Matrix4();
  21363. }
  21364. if ( ! light.shadowCamera ) {
  21365. if ( light instanceof THREE.SpotLight ) {
  21366. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21367. } else if ( light instanceof THREE.DirectionalLight ) {
  21368. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21369. } else {
  21370. console.error( "Unsupported light type for shadow" );
  21371. continue;
  21372. }
  21373. scene.add( light.shadowCamera );
  21374. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21375. }
  21376. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21377. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21378. light.shadowCamera.add( light.cameraHelper );
  21379. }
  21380. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21381. updateShadowCamera( camera, light );
  21382. }
  21383. shadowMap = light.shadowMap;
  21384. shadowMatrix = light.shadowMatrix;
  21385. shadowCamera = light.shadowCamera;
  21386. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  21387. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  21388. shadowCamera.lookAt( _matrixPosition );
  21389. shadowCamera.updateMatrixWorld();
  21390. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21391. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21392. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21393. // compute shadow matrix
  21394. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21395. 0.0, 0.5, 0.0, 0.5,
  21396. 0.0, 0.0, 0.5, 0.5,
  21397. 0.0, 0.0, 0.0, 1.0 );
  21398. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21399. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21400. // update camera matrices and frustum
  21401. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21402. _frustum.setFromMatrix( _projScreenMatrix );
  21403. // render shadow map
  21404. _renderer.setRenderTarget( shadowMap );
  21405. _renderer.clear();
  21406. // set object matrices & frustum culling
  21407. renderList = scene.__webglObjects;
  21408. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21409. webglObject = renderList[ j ];
  21410. object = webglObject.object;
  21411. webglObject.render = false;
  21412. if ( object.visible && object.castShadow ) {
  21413. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21414. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21415. webglObject.render = true;
  21416. }
  21417. }
  21418. }
  21419. // render regular objects
  21420. var objectMaterial, useMorphing, useSkinning;
  21421. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21422. webglObject = renderList[ j ];
  21423. if ( webglObject.render ) {
  21424. object = webglObject.object;
  21425. buffer = webglObject.buffer;
  21426. // culling is overriden globally for all objects
  21427. // while rendering depth map
  21428. // need to deal with MeshFaceMaterial somehow
  21429. // in that case just use the first of material.materials for now
  21430. // (proper solution would require to break objects by materials
  21431. // similarly to regular rendering and then set corresponding
  21432. // depth materials per each chunk instead of just once per object)
  21433. objectMaterial = getObjectMaterial( object );
  21434. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21435. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21436. if ( object.customDepthMaterial ) {
  21437. material = object.customDepthMaterial;
  21438. } else if ( useSkinning ) {
  21439. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21440. } else if ( useMorphing ) {
  21441. material = _depthMaterialMorph;
  21442. } else {
  21443. material = _depthMaterial;
  21444. }
  21445. if ( buffer instanceof THREE.BufferGeometry ) {
  21446. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21447. } else {
  21448. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21449. }
  21450. }
  21451. }
  21452. // set matrices and render immediate objects
  21453. renderList = scene.__webglObjectsImmediate;
  21454. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21455. webglObject = renderList[ j ];
  21456. object = webglObject.object;
  21457. if ( object.visible && object.castShadow ) {
  21458. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21459. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21460. }
  21461. }
  21462. }
  21463. // restore GL state
  21464. var clearColor = _renderer.getClearColor(),
  21465. clearAlpha = _renderer.getClearAlpha();
  21466. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21467. _gl.enable( _gl.BLEND );
  21468. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21469. _gl.cullFace( _gl.BACK );
  21470. }
  21471. };
  21472. function createVirtualLight( light, cascade ) {
  21473. var virtualLight = new THREE.DirectionalLight();
  21474. virtualLight.isVirtual = true;
  21475. virtualLight.onlyShadow = true;
  21476. virtualLight.castShadow = true;
  21477. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21478. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21479. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21480. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21481. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21482. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21483. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21484. virtualLight.shadowDarkness = light.shadowDarkness;
  21485. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21486. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21487. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21488. virtualLight.pointsWorld = [];
  21489. virtualLight.pointsFrustum = [];
  21490. var pointsWorld = virtualLight.pointsWorld,
  21491. pointsFrustum = virtualLight.pointsFrustum;
  21492. for ( var i = 0; i < 8; i ++ ) {
  21493. pointsWorld[ i ] = new THREE.Vector3();
  21494. pointsFrustum[ i ] = new THREE.Vector3();
  21495. }
  21496. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21497. var farZ = light.shadowCascadeFarZ[ cascade ];
  21498. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21499. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21500. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21501. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21502. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21503. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21504. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21505. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21506. return virtualLight;
  21507. }
  21508. // Synchronize virtual light with the original light
  21509. function updateVirtualLight( light, cascade ) {
  21510. var virtualLight = light.shadowCascadeArray[ cascade ];
  21511. virtualLight.position.copy( light.position );
  21512. virtualLight.target.position.copy( light.target.position );
  21513. virtualLight.lookAt( virtualLight.target );
  21514. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21515. virtualLight.shadowDarkness = light.shadowDarkness;
  21516. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21517. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21518. var farZ = light.shadowCascadeFarZ[ cascade ];
  21519. var pointsFrustum = virtualLight.pointsFrustum;
  21520. pointsFrustum[ 0 ].z = nearZ;
  21521. pointsFrustum[ 1 ].z = nearZ;
  21522. pointsFrustum[ 2 ].z = nearZ;
  21523. pointsFrustum[ 3 ].z = nearZ;
  21524. pointsFrustum[ 4 ].z = farZ;
  21525. pointsFrustum[ 5 ].z = farZ;
  21526. pointsFrustum[ 6 ].z = farZ;
  21527. pointsFrustum[ 7 ].z = farZ;
  21528. }
  21529. // Fit shadow camera's ortho frustum to camera frustum
  21530. function updateShadowCamera( camera, light ) {
  21531. var shadowCamera = light.shadowCamera,
  21532. pointsFrustum = light.pointsFrustum,
  21533. pointsWorld = light.pointsWorld;
  21534. _min.set( Infinity, Infinity, Infinity );
  21535. _max.set( -Infinity, -Infinity, -Infinity );
  21536. for ( var i = 0; i < 8; i ++ ) {
  21537. var p = pointsWorld[ i ];
  21538. p.copy( pointsFrustum[ i ] );
  21539. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21540. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21541. if ( p.x < _min.x ) _min.x = p.x;
  21542. if ( p.x > _max.x ) _max.x = p.x;
  21543. if ( p.y < _min.y ) _min.y = p.y;
  21544. if ( p.y > _max.y ) _max.y = p.y;
  21545. if ( p.z < _min.z ) _min.z = p.z;
  21546. if ( p.z > _max.z ) _max.z = p.z;
  21547. }
  21548. shadowCamera.left = _min.x;
  21549. shadowCamera.right = _max.x;
  21550. shadowCamera.top = _max.y;
  21551. shadowCamera.bottom = _min.y;
  21552. // can't really fit near/far
  21553. //shadowCamera.near = _min.z;
  21554. //shadowCamera.far = _max.z;
  21555. shadowCamera.updateProjectionMatrix();
  21556. }
  21557. // For the moment just ignore objects that have multiple materials with different animation methods
  21558. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21559. function getObjectMaterial( object ) {
  21560. return object.material instanceof THREE.MeshFaceMaterial
  21561. ? object.material.materials[ 0 ]
  21562. : object.material;
  21563. };
  21564. };
  21565. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21566. /**
  21567. * @author mikael emtinger / http://gomo.se/
  21568. * @author alteredq / http://alteredqualia.com/
  21569. */
  21570. THREE.SpritePlugin = function () {
  21571. var _gl, _renderer, _texture;
  21572. var vertices, faces, vertexBuffer, elementBuffer;
  21573. var program, attributes, uniforms;
  21574. this.init = function ( renderer ) {
  21575. _gl = renderer.context;
  21576. _renderer = renderer;
  21577. vertices = new Float32Array( [
  21578. - 0.5, - 0.5, 0, 0,
  21579. 0.5, - 0.5, 1, 0,
  21580. 0.5, 0.5, 1, 1,
  21581. - 0.5, 0.5, 0, 1
  21582. ] );
  21583. faces = new Uint16Array( [
  21584. 0, 1, 2,
  21585. 0, 2, 3
  21586. ] );
  21587. vertexBuffer = _gl.createBuffer();
  21588. elementBuffer = _gl.createBuffer();
  21589. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21590. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  21591. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21592. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  21593. program = createProgram();
  21594. attributes = {
  21595. position: _gl.getAttribLocation ( program, 'position' ),
  21596. uv: _gl.getAttribLocation ( program, 'uv' )
  21597. };
  21598. uniforms = {
  21599. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  21600. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  21601. rotation: _gl.getUniformLocation( program, 'rotation' ),
  21602. scale: _gl.getUniformLocation( program, 'scale' ),
  21603. color: _gl.getUniformLocation( program, 'color' ),
  21604. map: _gl.getUniformLocation( program, 'map' ),
  21605. opacity: _gl.getUniformLocation( program, 'opacity' ),
  21606. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  21607. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  21608. fogType: _gl.getUniformLocation( program, 'fogType' ),
  21609. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  21610. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  21611. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  21612. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  21613. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  21614. };
  21615. var canvas = document.createElement( 'canvas' );
  21616. canvas.width = 8;
  21617. canvas.height = 8;
  21618. var context = canvas.getContext( '2d' );
  21619. context.fillStyle = '#ffffff';
  21620. context.fillRect( 0, 0, canvas.width, canvas.height );
  21621. _texture = new THREE.Texture( canvas );
  21622. _texture.needsUpdate = true;
  21623. };
  21624. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21625. var sprites = scene.__webglSprites,
  21626. nSprites = sprites.length;
  21627. if ( ! nSprites ) return;
  21628. // setup gl
  21629. _gl.useProgram( program );
  21630. _gl.enableVertexAttribArray( attributes.position );
  21631. _gl.enableVertexAttribArray( attributes.uv );
  21632. _gl.disable( _gl.CULL_FACE );
  21633. _gl.enable( _gl.BLEND );
  21634. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21635. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21636. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21637. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21638. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21639. _gl.activeTexture( _gl.TEXTURE0 );
  21640. _gl.uniform1i( uniforms.map, 0 );
  21641. var oldFogType = 0;
  21642. var sceneFogType = 0;
  21643. var fog = scene.fog;
  21644. if ( fog ) {
  21645. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21646. if ( fog instanceof THREE.Fog ) {
  21647. _gl.uniform1f( uniforms.fogNear, fog.near );
  21648. _gl.uniform1f( uniforms.fogFar, fog.far );
  21649. _gl.uniform1i( uniforms.fogType, 1 );
  21650. oldFogType = 1;
  21651. sceneFogType = 1;
  21652. } else if ( fog instanceof THREE.FogExp2 ) {
  21653. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21654. _gl.uniform1i( uniforms.fogType, 2 );
  21655. oldFogType = 2;
  21656. sceneFogType = 2;
  21657. }
  21658. } else {
  21659. _gl.uniform1i( uniforms.fogType, 0 );
  21660. oldFogType = 0;
  21661. sceneFogType = 0;
  21662. }
  21663. // update positions and sort
  21664. var i, sprite, material, fogType, scale = [];
  21665. for( i = 0; i < nSprites; i ++ ) {
  21666. sprite = sprites[ i ];
  21667. material = sprite.material;
  21668. if ( sprite.visible === false ) continue;
  21669. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21670. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21671. }
  21672. sprites.sort( painterSortStable );
  21673. // render all sprites
  21674. for( i = 0; i < nSprites; i ++ ) {
  21675. sprite = sprites[ i ];
  21676. if ( sprite.visible === false ) continue;
  21677. material = sprite.material;
  21678. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21679. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21680. scale[ 0 ] = sprite.scale.x;
  21681. scale[ 1 ] = sprite.scale.y;
  21682. if ( scene.fog && material.fog ) {
  21683. fogType = sceneFogType;
  21684. } else {
  21685. fogType = 0;
  21686. }
  21687. if ( oldFogType !== fogType ) {
  21688. _gl.uniform1i( uniforms.fogType, fogType );
  21689. oldFogType = fogType;
  21690. }
  21691. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21692. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21693. _gl.uniform1f( uniforms.opacity, material.opacity );
  21694. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21695. _gl.uniform1f( uniforms.rotation, material.rotation );
  21696. _gl.uniform2fv( uniforms.scale, scale );
  21697. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21698. _renderer.setDepthTest( material.depthTest );
  21699. _renderer.setDepthWrite( material.depthWrite );
  21700. if ( material.map && material.map.image && material.map.image.width ) {
  21701. _renderer.setTexture( material.map, 0 );
  21702. } else {
  21703. _renderer.setTexture( _texture, 0 );
  21704. }
  21705. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21706. }
  21707. // restore gl
  21708. _gl.enable( _gl.CULL_FACE );
  21709. };
  21710. function createProgram () {
  21711. var program = _gl.createProgram();
  21712. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21713. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21714. _gl.shaderSource( vertexShader, [
  21715. 'precision ' + _renderer.getPrecision() + ' float;',
  21716. 'uniform mat4 modelViewMatrix;',
  21717. 'uniform mat4 projectionMatrix;',
  21718. 'uniform float rotation;',
  21719. 'uniform vec2 scale;',
  21720. 'uniform vec2 uvOffset;',
  21721. 'uniform vec2 uvScale;',
  21722. 'attribute vec2 position;',
  21723. 'attribute vec2 uv;',
  21724. 'varying vec2 vUV;',
  21725. 'void main() {',
  21726. 'vUV = uvOffset + uv * uvScale;',
  21727. 'vec2 alignedPosition = position * scale;',
  21728. 'vec2 rotatedPosition;',
  21729. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  21730. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  21731. 'vec4 finalPosition;',
  21732. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  21733. 'finalPosition.xy += rotatedPosition;',
  21734. 'finalPosition = projectionMatrix * finalPosition;',
  21735. 'gl_Position = finalPosition;',
  21736. '}'
  21737. ].join( '\n' ) );
  21738. _gl.shaderSource( fragmentShader, [
  21739. 'precision ' + _renderer.getPrecision() + ' float;',
  21740. 'uniform vec3 color;',
  21741. 'uniform sampler2D map;',
  21742. 'uniform float opacity;',
  21743. 'uniform int fogType;',
  21744. 'uniform vec3 fogColor;',
  21745. 'uniform float fogDensity;',
  21746. 'uniform float fogNear;',
  21747. 'uniform float fogFar;',
  21748. 'uniform float alphaTest;',
  21749. 'varying vec2 vUV;',
  21750. 'void main() {',
  21751. 'vec4 texture = texture2D( map, vUV );',
  21752. 'if ( texture.a < alphaTest ) discard;',
  21753. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  21754. 'if ( fogType > 0 ) {',
  21755. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  21756. 'float fogFactor = 0.0;',
  21757. 'if ( fogType == 1 ) {',
  21758. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  21759. '} else {',
  21760. 'const float LOG2 = 1.442695;',
  21761. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  21762. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  21763. '}',
  21764. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  21765. '}',
  21766. '}'
  21767. ].join( '\n' ) );
  21768. _gl.compileShader( vertexShader );
  21769. _gl.compileShader( fragmentShader );
  21770. _gl.attachShader( program, vertexShader );
  21771. _gl.attachShader( program, fragmentShader );
  21772. _gl.linkProgram( program );
  21773. return program;
  21774. };
  21775. function painterSortStable ( a, b ) {
  21776. if ( a.z !== b.z ) {
  21777. return b.z - a.z;
  21778. } else {
  21779. return b.id - a.id;
  21780. }
  21781. };
  21782. };
  21783. /**
  21784. * @author alteredq / http://alteredqualia.com/
  21785. */
  21786. THREE.DepthPassPlugin = function () {
  21787. this.enabled = false;
  21788. this.renderTarget = null;
  21789. var _gl,
  21790. _renderer,
  21791. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21792. _frustum = new THREE.Frustum(),
  21793. _projScreenMatrix = new THREE.Matrix4();
  21794. this.init = function ( renderer ) {
  21795. _gl = renderer.context;
  21796. _renderer = renderer;
  21797. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21798. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21799. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21800. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21801. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21802. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21803. _depthMaterial._shadowPass = true;
  21804. _depthMaterialMorph._shadowPass = true;
  21805. _depthMaterialSkin._shadowPass = true;
  21806. _depthMaterialMorphSkin._shadowPass = true;
  21807. };
  21808. this.render = function ( scene, camera ) {
  21809. if ( ! this.enabled ) return;
  21810. this.update( scene, camera );
  21811. };
  21812. this.update = function ( scene, camera ) {
  21813. var i, il, j, jl, n,
  21814. program, buffer, material,
  21815. webglObject, object, light,
  21816. renderList,
  21817. fog = null;
  21818. // set GL state for depth map
  21819. _gl.clearColor( 1, 1, 1, 1 );
  21820. _gl.disable( _gl.BLEND );
  21821. _renderer.setDepthTest( true );
  21822. // update scene
  21823. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21824. // update camera matrices and frustum
  21825. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21826. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21827. _frustum.setFromMatrix( _projScreenMatrix );
  21828. // render depth map
  21829. _renderer.setRenderTarget( this.renderTarget );
  21830. _renderer.clear();
  21831. // set object matrices & frustum culling
  21832. renderList = scene.__webglObjects;
  21833. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21834. webglObject = renderList[ j ];
  21835. object = webglObject.object;
  21836. webglObject.render = false;
  21837. if ( object.visible ) {
  21838. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21839. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21840. webglObject.render = true;
  21841. }
  21842. }
  21843. }
  21844. // render regular objects
  21845. var objectMaterial, useMorphing, useSkinning;
  21846. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21847. webglObject = renderList[ j ];
  21848. if ( webglObject.render ) {
  21849. object = webglObject.object;
  21850. buffer = webglObject.buffer;
  21851. // todo: create proper depth material for particles
  21852. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21853. objectMaterial = getObjectMaterial( object );
  21854. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21855. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21856. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21857. if ( object.customDepthMaterial ) {
  21858. material = object.customDepthMaterial;
  21859. } else if ( useSkinning ) {
  21860. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21861. } else if ( useMorphing ) {
  21862. material = _depthMaterialMorph;
  21863. } else {
  21864. material = _depthMaterial;
  21865. }
  21866. if ( buffer instanceof THREE.BufferGeometry ) {
  21867. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21868. } else {
  21869. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21870. }
  21871. }
  21872. }
  21873. // set matrices and render immediate objects
  21874. renderList = scene.__webglObjectsImmediate;
  21875. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21876. webglObject = renderList[ j ];
  21877. object = webglObject.object;
  21878. if ( object.visible ) {
  21879. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21880. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21881. }
  21882. }
  21883. // restore GL state
  21884. var clearColor = _renderer.getClearColor(),
  21885. clearAlpha = _renderer.getClearAlpha();
  21886. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21887. _gl.enable( _gl.BLEND );
  21888. };
  21889. // For the moment just ignore objects that have multiple materials with different animation methods
  21890. // Only the first material will be taken into account for deciding which depth material to use
  21891. function getObjectMaterial( object ) {
  21892. return object.material instanceof THREE.MeshFaceMaterial
  21893. ? object.material.materials[ 0 ]
  21894. : object.material;
  21895. };
  21896. };
  21897. /**
  21898. * @author mikael emtinger / http://gomo.se/
  21899. */
  21900. THREE.ShaderFlares = {
  21901. 'lensFlareVertexTexture': {
  21902. vertexShader: [
  21903. "uniform lowp int renderType;",
  21904. "uniform vec3 screenPosition;",
  21905. "uniform vec2 scale;",
  21906. "uniform float rotation;",
  21907. "uniform sampler2D occlusionMap;",
  21908. "attribute vec2 position;",
  21909. "attribute vec2 uv;",
  21910. "varying vec2 vUV;",
  21911. "varying float vVisibility;",
  21912. "void main() {",
  21913. "vUV = uv;",
  21914. "vec2 pos = position;",
  21915. "if( renderType == 2 ) {",
  21916. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  21917. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  21918. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  21919. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  21920. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  21921. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  21922. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  21923. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  21924. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21925. "vVisibility = visibility.r / 9.0;",
  21926. "vVisibility *= 1.0 - visibility.g / 9.0;",
  21927. "vVisibility *= visibility.b / 9.0;",
  21928. "vVisibility *= 1.0 - visibility.a / 9.0;",
  21929. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21930. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21931. "}",
  21932. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21933. "}"
  21934. ].join( "\n" ),
  21935. fragmentShader: [
  21936. "uniform lowp int renderType;",
  21937. "uniform sampler2D map;",
  21938. "uniform float opacity;",
  21939. "uniform vec3 color;",
  21940. "varying vec2 vUV;",
  21941. "varying float vVisibility;",
  21942. "void main() {",
  21943. // pink square
  21944. "if( renderType == 0 ) {",
  21945. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21946. // restore
  21947. "} else if( renderType == 1 ) {",
  21948. "gl_FragColor = texture2D( map, vUV );",
  21949. // flare
  21950. "} else {",
  21951. "vec4 texture = texture2D( map, vUV );",
  21952. "texture.a *= opacity * vVisibility;",
  21953. "gl_FragColor = texture;",
  21954. "gl_FragColor.rgb *= color;",
  21955. "}",
  21956. "}"
  21957. ].join( "\n" )
  21958. },
  21959. 'lensFlare': {
  21960. vertexShader: [
  21961. "uniform lowp int renderType;",
  21962. "uniform vec3 screenPosition;",
  21963. "uniform vec2 scale;",
  21964. "uniform float rotation;",
  21965. "attribute vec2 position;",
  21966. "attribute vec2 uv;",
  21967. "varying vec2 vUV;",
  21968. "void main() {",
  21969. "vUV = uv;",
  21970. "vec2 pos = position;",
  21971. "if( renderType == 2 ) {",
  21972. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21973. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21974. "}",
  21975. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21976. "}"
  21977. ].join( "\n" ),
  21978. fragmentShader: [
  21979. "precision mediump float;",
  21980. "uniform lowp int renderType;",
  21981. "uniform sampler2D map;",
  21982. "uniform sampler2D occlusionMap;",
  21983. "uniform float opacity;",
  21984. "uniform vec3 color;",
  21985. "varying vec2 vUV;",
  21986. "void main() {",
  21987. // pink square
  21988. "if( renderType == 0 ) {",
  21989. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21990. // restore
  21991. "} else if( renderType == 1 ) {",
  21992. "gl_FragColor = texture2D( map, vUV );",
  21993. // flare
  21994. "} else {",
  21995. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  21996. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  21997. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  21998. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21999. "visibility = ( 1.0 - visibility / 4.0 );",
  22000. "vec4 texture = texture2D( map, vUV );",
  22001. "texture.a *= opacity * visibility;",
  22002. "gl_FragColor = texture;",
  22003. "gl_FragColor.rgb *= color;",
  22004. "}",
  22005. "}"
  22006. ].join( "\n" )
  22007. }
  22008. };