three.js 802 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '59dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. String.prototype.trim = String.prototype.trim || function () {
  16. return this.replace( /^\s+|\s+$/g, '' );
  17. };
  18. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  19. THREE.extend = function ( obj, source ) {
  20. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  21. if ( Object.keys ) {
  22. var keys = Object.keys( source );
  23. for (var i = 0, il = keys.length; i < il; i++) {
  24. var prop = keys[i];
  25. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  26. }
  27. } else {
  28. var safeHasOwnProperty = {}.hasOwnProperty;
  29. for ( var prop in source ) {
  30. if ( safeHasOwnProperty.call( source, prop ) ) {
  31. obj[prop] = source[prop];
  32. }
  33. }
  34. }
  35. return obj;
  36. };
  37. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  38. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  39. // requestAnimationFrame polyfill by Erik Möller
  40. // fixes from Paul Irish and Tino Zijdel
  41. ( function () {
  42. var lastTime = 0;
  43. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  44. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  45. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  46. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  47. }
  48. if ( window.requestAnimationFrame === undefined ) {
  49. window.requestAnimationFrame = function ( callback ) {
  50. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  51. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  52. lastTime = currTime + timeToCall;
  53. return id;
  54. };
  55. }
  56. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  57. }() );
  58. // GL STATE CONSTANTS
  59. THREE.CullFaceNone = 0;
  60. THREE.CullFaceBack = 1;
  61. THREE.CullFaceFront = 2;
  62. THREE.CullFaceFrontBack = 3;
  63. THREE.FrontFaceDirectionCW = 0;
  64. THREE.FrontFaceDirectionCCW = 1;
  65. // SHADOWING TYPES
  66. THREE.BasicShadowMap = 0;
  67. THREE.PCFShadowMap = 1;
  68. THREE.PCFSoftShadowMap = 2;
  69. // MATERIAL CONSTANTS
  70. // side
  71. THREE.FrontSide = 0;
  72. THREE.BackSide = 1;
  73. THREE.DoubleSide = 2;
  74. // shading
  75. THREE.NoShading = 0;
  76. THREE.FlatShading = 1;
  77. THREE.SmoothShading = 2;
  78. // colors
  79. THREE.NoColors = 0;
  80. THREE.FaceColors = 1;
  81. THREE.VertexColors = 2;
  82. // blending modes
  83. THREE.NoBlending = 0;
  84. THREE.NormalBlending = 1;
  85. THREE.AdditiveBlending = 2;
  86. THREE.SubtractiveBlending = 3;
  87. THREE.MultiplyBlending = 4;
  88. THREE.CustomBlending = 5;
  89. // custom blending equations
  90. // (numbers start from 100 not to clash with other
  91. // mappings to OpenGL constants defined in Texture.js)
  92. THREE.AddEquation = 100;
  93. THREE.SubtractEquation = 101;
  94. THREE.ReverseSubtractEquation = 102;
  95. // custom blending destination factors
  96. THREE.ZeroFactor = 200;
  97. THREE.OneFactor = 201;
  98. THREE.SrcColorFactor = 202;
  99. THREE.OneMinusSrcColorFactor = 203;
  100. THREE.SrcAlphaFactor = 204;
  101. THREE.OneMinusSrcAlphaFactor = 205;
  102. THREE.DstAlphaFactor = 206;
  103. THREE.OneMinusDstAlphaFactor = 207;
  104. // custom blending source factors
  105. //THREE.ZeroFactor = 200;
  106. //THREE.OneFactor = 201;
  107. //THREE.SrcAlphaFactor = 204;
  108. //THREE.OneMinusSrcAlphaFactor = 205;
  109. //THREE.DstAlphaFactor = 206;
  110. //THREE.OneMinusDstAlphaFactor = 207;
  111. THREE.DstColorFactor = 208;
  112. THREE.OneMinusDstColorFactor = 209;
  113. THREE.SrcAlphaSaturateFactor = 210;
  114. // TEXTURE CONSTANTS
  115. THREE.MultiplyOperation = 0;
  116. THREE.MixOperation = 1;
  117. THREE.AddOperation = 2;
  118. // Mapping modes
  119. THREE.UVMapping = function () {};
  120. THREE.CubeReflectionMapping = function () {};
  121. THREE.CubeRefractionMapping = function () {};
  122. THREE.SphericalReflectionMapping = function () {};
  123. THREE.SphericalRefractionMapping = function () {};
  124. // Wrapping modes
  125. THREE.RepeatWrapping = 1000;
  126. THREE.ClampToEdgeWrapping = 1001;
  127. THREE.MirroredRepeatWrapping = 1002;
  128. // Filters
  129. THREE.NearestFilter = 1003;
  130. THREE.NearestMipMapNearestFilter = 1004;
  131. THREE.NearestMipMapLinearFilter = 1005;
  132. THREE.LinearFilter = 1006;
  133. THREE.LinearMipMapNearestFilter = 1007;
  134. THREE.LinearMipMapLinearFilter = 1008;
  135. // Data types
  136. THREE.UnsignedByteType = 1009;
  137. THREE.ByteType = 1010;
  138. THREE.ShortType = 1011;
  139. THREE.UnsignedShortType = 1012;
  140. THREE.IntType = 1013;
  141. THREE.UnsignedIntType = 1014;
  142. THREE.FloatType = 1015;
  143. // Pixel types
  144. //THREE.UnsignedByteType = 1009;
  145. THREE.UnsignedShort4444Type = 1016;
  146. THREE.UnsignedShort5551Type = 1017;
  147. THREE.UnsignedShort565Type = 1018;
  148. // Pixel formats
  149. THREE.AlphaFormat = 1019;
  150. THREE.RGBFormat = 1020;
  151. THREE.RGBAFormat = 1021;
  152. THREE.LuminanceFormat = 1022;
  153. THREE.LuminanceAlphaFormat = 1023;
  154. // Compressed texture formats
  155. THREE.RGB_S3TC_DXT1_Format = 2001;
  156. THREE.RGBA_S3TC_DXT1_Format = 2002;
  157. THREE.RGBA_S3TC_DXT3_Format = 2003;
  158. THREE.RGBA_S3TC_DXT5_Format = 2004;
  159. /*
  160. // Potential future PVRTC compressed texture formats
  161. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  162. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  163. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  164. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  165. */
  166. /**
  167. * @author mrdoob / http://mrdoob.com/
  168. */
  169. THREE.Color = function ( value ) {
  170. if ( value !== undefined ) this.set( value );
  171. return this;
  172. };
  173. THREE.Color.prototype = {
  174. constructor: THREE.Color,
  175. r: 1, g: 1, b: 1,
  176. set: function ( value ) {
  177. if ( value instanceof THREE.Color ) {
  178. this.copy( value );
  179. } else if ( typeof value === 'number' ) {
  180. this.setHex( value );
  181. } else if ( typeof value === 'string' ) {
  182. this.setStyle( value );
  183. }
  184. return this;
  185. },
  186. setHex: function ( hex ) {
  187. hex = Math.floor( hex );
  188. this.r = ( hex >> 16 & 255 ) / 255;
  189. this.g = ( hex >> 8 & 255 ) / 255;
  190. this.b = ( hex & 255 ) / 255;
  191. return this;
  192. },
  193. setRGB: function ( r, g, b ) {
  194. this.r = r;
  195. this.g = g;
  196. this.b = b;
  197. return this;
  198. },
  199. setHSL: function ( h, s, l ) {
  200. // h,s,l ranges are in 0.0 - 1.0
  201. if ( s === 0 ) {
  202. this.r = this.g = this.b = l;
  203. } else {
  204. var hue2rgb = function ( p, q, t ) {
  205. if ( t < 0 ) t += 1;
  206. if ( t > 1 ) t -= 1;
  207. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  208. if ( t < 1 / 2 ) return q;
  209. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  210. return p;
  211. };
  212. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  213. var q = ( 2 * l ) - p;
  214. this.r = hue2rgb( q, p, h + 1 / 3 );
  215. this.g = hue2rgb( q, p, h );
  216. this.b = hue2rgb( q, p, h - 1 / 3 );
  217. }
  218. return this;
  219. },
  220. setStyle: function ( style ) {
  221. // rgb(255,0,0)
  222. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  223. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  224. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  225. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  226. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  227. return this;
  228. }
  229. // rgb(100%,0%,0%)
  230. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  231. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  232. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  233. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  234. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  235. return this;
  236. }
  237. // #ff0000
  238. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  239. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  240. this.setHex( parseInt( color[ 1 ], 16 ) );
  241. return this;
  242. }
  243. // #f00
  244. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  245. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  246. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  247. return this;
  248. }
  249. // red
  250. if ( /^(\w+)$/i.test( style ) ) {
  251. this.setHex( THREE.ColorKeywords[ style ] );
  252. return this;
  253. }
  254. },
  255. copy: function ( color ) {
  256. this.r = color.r;
  257. this.g = color.g;
  258. this.b = color.b;
  259. return this;
  260. },
  261. copyGammaToLinear: function ( color ) {
  262. this.r = color.r * color.r;
  263. this.g = color.g * color.g;
  264. this.b = color.b * color.b;
  265. return this;
  266. },
  267. copyLinearToGamma: function ( color ) {
  268. this.r = Math.sqrt( color.r );
  269. this.g = Math.sqrt( color.g );
  270. this.b = Math.sqrt( color.b );
  271. return this;
  272. },
  273. convertGammaToLinear: function () {
  274. var r = this.r, g = this.g, b = this.b;
  275. this.r = r * r;
  276. this.g = g * g;
  277. this.b = b * b;
  278. return this;
  279. },
  280. convertLinearToGamma: function () {
  281. this.r = Math.sqrt( this.r );
  282. this.g = Math.sqrt( this.g );
  283. this.b = Math.sqrt( this.b );
  284. return this;
  285. },
  286. getHex: function () {
  287. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  288. },
  289. getHexString: function () {
  290. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  291. },
  292. getHSL: function () {
  293. var hsl = { h: 0, s: 0, l: 0 };
  294. return function () {
  295. // h,s,l ranges are in 0.0 - 1.0
  296. var r = this.r, g = this.g, b = this.b;
  297. var max = Math.max( r, g, b );
  298. var min = Math.min( r, g, b );
  299. var hue, saturation;
  300. var lightness = ( min + max ) / 2.0;
  301. if ( min === max ) {
  302. hue = 0;
  303. saturation = 0;
  304. } else {
  305. var delta = max - min;
  306. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  307. switch ( max ) {
  308. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  309. case g: hue = ( b - r ) / delta + 2; break;
  310. case b: hue = ( r - g ) / delta + 4; break;
  311. }
  312. hue /= 6;
  313. }
  314. hsl.h = hue;
  315. hsl.s = saturation;
  316. hsl.l = lightness;
  317. return hsl;
  318. };
  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. clone: function () {
  369. return new THREE.Color().setRGB( this.r, this.g, this.b );
  370. }
  371. };
  372. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  373. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  374. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  375. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  376. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  377. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  378. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  379. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  380. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  381. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  382. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  383. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  384. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  385. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  386. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  387. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  388. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  389. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  390. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  391. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  392. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  393. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  394. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  395. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  396. /**
  397. * @author mikael emtinger / http://gomo.se/
  398. * @author alteredq / http://alteredqualia.com/
  399. * @author WestLangley / http://github.com/WestLangley
  400. * @author bhouston / http://exocortex.com
  401. */
  402. THREE.Quaternion = function( x, y, z, w ) {
  403. this.x = x || 0;
  404. this.y = y || 0;
  405. this.z = z || 0;
  406. this.w = ( w !== undefined ) ? w : 1;
  407. };
  408. THREE.Quaternion.prototype = {
  409. constructor: THREE.Quaternion,
  410. set: function ( x, y, z, w ) {
  411. this.x = x;
  412. this.y = y;
  413. this.z = z;
  414. this.w = w;
  415. return this;
  416. },
  417. copy: function ( q ) {
  418. this.x = q.x;
  419. this.y = q.y;
  420. this.z = q.z;
  421. this.w = q.w;
  422. return this;
  423. },
  424. setFromEuler: function ( v, order ) {
  425. // http://www.mathworks.com/matlabcentral/fileexchange/
  426. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  427. // content/SpinCalc.m
  428. var c1 = Math.cos( v.x / 2 );
  429. var c2 = Math.cos( v.y / 2 );
  430. var c3 = Math.cos( v.z / 2 );
  431. var s1 = Math.sin( v.x / 2 );
  432. var s2 = Math.sin( v.y / 2 );
  433. var s3 = Math.sin( v.z / 2 );
  434. if ( order === undefined || order === 'XYZ' ) {
  435. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  436. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  437. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  438. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  439. } else if ( order === 'YXZ' ) {
  440. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  441. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  442. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  443. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  444. } else if ( order === 'ZXY' ) {
  445. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  446. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  447. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  448. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  449. } else if ( order === 'ZYX' ) {
  450. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  451. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  452. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  453. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  454. } else if ( order === 'YZX' ) {
  455. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  456. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  457. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  458. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  459. } else if ( order === 'XZY' ) {
  460. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  461. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  462. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  463. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  464. }
  465. return this;
  466. },
  467. setFromAxisAngle: function ( axis, angle ) {
  468. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  469. // axis have to be normalized
  470. var halfAngle = angle / 2,
  471. s = Math.sin( halfAngle );
  472. this.x = axis.x * s;
  473. this.y = axis.y * s;
  474. this.z = axis.z * s;
  475. this.w = Math.cos( halfAngle );
  476. return this;
  477. },
  478. setFromRotationMatrix: function ( m ) {
  479. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  480. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  481. var te = m.elements,
  482. m11 = te[0], m12 = te[4], m13 = te[8],
  483. m21 = te[1], m22 = te[5], m23 = te[9],
  484. m31 = te[2], m32 = te[6], m33 = te[10],
  485. trace = m11 + m22 + m33,
  486. s;
  487. if ( trace > 0 ) {
  488. s = 0.5 / Math.sqrt( trace + 1.0 );
  489. this.w = 0.25 / s;
  490. this.x = ( m32 - m23 ) * s;
  491. this.y = ( m13 - m31 ) * s;
  492. this.z = ( m21 - m12 ) * s;
  493. } else if ( m11 > m22 && m11 > m33 ) {
  494. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  495. this.w = (m32 - m23 ) / s;
  496. this.x = 0.25 * s;
  497. this.y = (m12 + m21 ) / s;
  498. this.z = (m13 + m31 ) / s;
  499. } else if ( m22 > m33 ) {
  500. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  501. this.w = (m13 - m31 ) / s;
  502. this.x = (m12 + m21 ) / s;
  503. this.y = 0.25 * s;
  504. this.z = (m23 + m32 ) / s;
  505. } else {
  506. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  507. this.w = ( m21 - m12 ) / s;
  508. this.x = ( m13 + m31 ) / s;
  509. this.y = ( m23 + m32 ) / s;
  510. this.z = 0.25 * s;
  511. }
  512. return this;
  513. },
  514. inverse: function () {
  515. this.conjugate().normalize();
  516. return this;
  517. },
  518. conjugate: function () {
  519. this.x *= -1;
  520. this.y *= -1;
  521. this.z *= -1;
  522. return this;
  523. },
  524. lengthSq: function () {
  525. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  526. },
  527. length: function () {
  528. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  529. },
  530. normalize: function () {
  531. var l = this.length();
  532. if ( l === 0 ) {
  533. this.x = 0;
  534. this.y = 0;
  535. this.z = 0;
  536. this.w = 1;
  537. } else {
  538. l = 1 / l;
  539. this.x = this.x * l;
  540. this.y = this.y * l;
  541. this.z = this.z * l;
  542. this.w = this.w * l;
  543. }
  544. return this;
  545. },
  546. multiply: function ( q, p ) {
  547. if ( p !== undefined ) {
  548. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  549. return this.multiplyQuaternions( q, p );
  550. }
  551. return this.multiplyQuaternions( this, q );
  552. },
  553. multiplyQuaternions: function ( a, b ) {
  554. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  555. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  556. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  557. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  558. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  559. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  560. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  561. return this;
  562. },
  563. multiplyVector3: function ( vector ) {
  564. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  565. return vector.applyQuaternion( this );
  566. },
  567. slerp: function ( qb, t ) {
  568. var x = this.x, y = this.y, z = this.z, w = this.w;
  569. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  570. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  571. if ( cosHalfTheta < 0 ) {
  572. this.w = -qb.w;
  573. this.x = -qb.x;
  574. this.y = -qb.y;
  575. this.z = -qb.z;
  576. cosHalfTheta = -cosHalfTheta;
  577. } else {
  578. this.copy( qb );
  579. }
  580. if ( cosHalfTheta >= 1.0 ) {
  581. this.w = w;
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. }
  587. var halfTheta = Math.acos( cosHalfTheta );
  588. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  589. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  590. this.w = 0.5 * ( w + this.w );
  591. this.x = 0.5 * ( x + this.x );
  592. this.y = 0.5 * ( y + this.y );
  593. this.z = 0.5 * ( z + this.z );
  594. return this;
  595. }
  596. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  597. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  598. this.w = ( w * ratioA + this.w * ratioB );
  599. this.x = ( x * ratioA + this.x * ratioB );
  600. this.y = ( y * ratioA + this.y * ratioB );
  601. this.z = ( z * ratioA + this.z * ratioB );
  602. return this;
  603. },
  604. equals: function ( v ) {
  605. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  606. },
  607. fromArray: function ( array ) {
  608. this.x = array[ 0 ];
  609. this.y = array[ 1 ];
  610. this.z = array[ 2 ];
  611. this.w = array[ 3 ];
  612. return this;
  613. },
  614. toArray: function () {
  615. return [ this.x, this.y, this.z, this.w ];
  616. },
  617. clone: function () {
  618. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  619. }
  620. };
  621. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  622. return qm.copy( qa ).slerp( qb, t );
  623. }
  624. /**
  625. * @author mrdoob / http://mrdoob.com/
  626. * @author philogb / http://blog.thejit.org/
  627. * @author egraether / http://egraether.com/
  628. * @author zz85 / http://www.lab4games.net/zz85/blog
  629. */
  630. THREE.Vector2 = function ( x, y ) {
  631. this.x = x || 0;
  632. this.y = y || 0;
  633. };
  634. THREE.Vector2.prototype = {
  635. constructor: THREE.Vector2,
  636. set: function ( x, y ) {
  637. this.x = x;
  638. this.y = y;
  639. return this;
  640. },
  641. setX: function ( x ) {
  642. this.x = x;
  643. return this;
  644. },
  645. setY: function ( y ) {
  646. this.y = y;
  647. return this;
  648. },
  649. setComponent: function ( index, value ) {
  650. switch ( index ) {
  651. case 0: this.x = value; break;
  652. case 1: this.y = value; break;
  653. default: throw new Error( "index is out of range: " + index );
  654. }
  655. },
  656. getComponent: function ( index ) {
  657. switch ( index ) {
  658. case 0: return this.x;
  659. case 1: return this.y;
  660. default: throw new Error( "index is out of range: " + index );
  661. }
  662. },
  663. copy: function ( v ) {
  664. this.x = v.x;
  665. this.y = v.y;
  666. return this;
  667. },
  668. add: function ( v, w ) {
  669. if ( w !== undefined ) {
  670. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  671. return this.addVectors( v, w );
  672. }
  673. this.x += v.x;
  674. this.y += v.y;
  675. return this;
  676. },
  677. addVectors: function ( a, b ) {
  678. this.x = a.x + b.x;
  679. this.y = a.y + b.y;
  680. return this;
  681. },
  682. addScalar: function ( s ) {
  683. this.x += s;
  684. this.y += s;
  685. return this;
  686. },
  687. sub: function ( v, w ) {
  688. if ( w !== undefined ) {
  689. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  690. return this.subVectors( v, w );
  691. }
  692. this.x -= v.x;
  693. this.y -= v.y;
  694. return this;
  695. },
  696. subVectors: function ( a, b ) {
  697. this.x = a.x - b.x;
  698. this.y = a.y - b.y;
  699. return this;
  700. },
  701. multiplyScalar: function ( s ) {
  702. this.x *= s;
  703. this.y *= s;
  704. return this;
  705. },
  706. divideScalar: function ( s ) {
  707. if ( s !== 0 ) {
  708. this.x /= s;
  709. this.y /= s;
  710. } else {
  711. this.set( 0, 0 );
  712. }
  713. return this;
  714. },
  715. min: function ( v ) {
  716. if ( this.x > v.x ) {
  717. this.x = v.x;
  718. }
  719. if ( this.y > v.y ) {
  720. this.y = v.y;
  721. }
  722. return this;
  723. },
  724. max: function ( v ) {
  725. if ( this.x < v.x ) {
  726. this.x = v.x;
  727. }
  728. if ( this.y < v.y ) {
  729. this.y = v.y;
  730. }
  731. return this;
  732. },
  733. clamp: function ( min, max ) {
  734. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  735. if ( this.x < min.x ) {
  736. this.x = min.x;
  737. } else if ( this.x > max.x ) {
  738. this.x = max.x;
  739. }
  740. if ( this.y < min.y ) {
  741. this.y = min.y;
  742. } else if ( this.y > max.y ) {
  743. this.y = max.y;
  744. }
  745. return this;
  746. },
  747. negate: function() {
  748. return this.multiplyScalar( - 1 );
  749. },
  750. dot: function ( v ) {
  751. return this.x * v.x + this.y * v.y;
  752. },
  753. lengthSq: function () {
  754. return this.x * this.x + this.y * this.y;
  755. },
  756. length: function () {
  757. return Math.sqrt( this.x * this.x + this.y * this.y );
  758. },
  759. normalize: function () {
  760. return this.divideScalar( this.length() );
  761. },
  762. distanceTo: function ( v ) {
  763. return Math.sqrt( this.distanceToSquared( v ) );
  764. },
  765. distanceToSquared: function ( v ) {
  766. var dx = this.x - v.x, dy = this.y - v.y;
  767. return dx * dx + dy * dy;
  768. },
  769. setLength: function ( l ) {
  770. var oldLength = this.length();
  771. if ( oldLength !== 0 && l !== oldLength ) {
  772. this.multiplyScalar( l / oldLength );
  773. }
  774. return this;
  775. },
  776. lerp: function ( v, alpha ) {
  777. this.x += ( v.x - this.x ) * alpha;
  778. this.y += ( v.y - this.y ) * alpha;
  779. return this;
  780. },
  781. equals: function( v ) {
  782. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  783. },
  784. fromArray: function ( array ) {
  785. this.x = array[ 0 ];
  786. this.y = array[ 1 ];
  787. return this;
  788. },
  789. toArray: function () {
  790. return [ this.x, this.y ];
  791. },
  792. clone: function () {
  793. return new THREE.Vector2( this.x, this.y );
  794. }
  795. };
  796. /**
  797. * @author mrdoob / http://mrdoob.com/
  798. * @author *kile / http://kile.stravaganza.org/
  799. * @author philogb / http://blog.thejit.org/
  800. * @author mikael emtinger / http://gomo.se/
  801. * @author egraether / http://egraether.com/
  802. * @author WestLangley / http://github.com/WestLangley
  803. */
  804. THREE.Vector3 = function ( x, y, z ) {
  805. this.x = x || 0;
  806. this.y = y || 0;
  807. this.z = z || 0;
  808. };
  809. THREE.Vector3.prototype = {
  810. constructor: THREE.Vector3,
  811. set: function ( x, y, z ) {
  812. this.x = x;
  813. this.y = y;
  814. this.z = z;
  815. return this;
  816. },
  817. setX: function ( x ) {
  818. this.x = x;
  819. return this;
  820. },
  821. setY: function ( y ) {
  822. this.y = y;
  823. return this;
  824. },
  825. setZ: function ( z ) {
  826. this.z = z;
  827. return this;
  828. },
  829. setComponent: function ( index, value ) {
  830. switch ( index ) {
  831. case 0: this.x = value; break;
  832. case 1: this.y = value; break;
  833. case 2: this.z = value; break;
  834. default: throw new Error( "index is out of range: " + index );
  835. }
  836. },
  837. getComponent: function ( index ) {
  838. switch ( index ) {
  839. case 0: return this.x;
  840. case 1: return this.y;
  841. case 2: return this.z;
  842. default: throw new Error( "index is out of range: " + index );
  843. }
  844. },
  845. copy: function ( v ) {
  846. this.x = v.x;
  847. this.y = v.y;
  848. this.z = v.z;
  849. return this;
  850. },
  851. add: function ( v, w ) {
  852. if ( w !== undefined ) {
  853. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  854. return this.addVectors( v, w );
  855. }
  856. this.x += v.x;
  857. this.y += v.y;
  858. this.z += v.z;
  859. return this;
  860. },
  861. addScalar: function ( s ) {
  862. this.x += s;
  863. this.y += s;
  864. this.z += s;
  865. return this;
  866. },
  867. addVectors: function ( a, b ) {
  868. this.x = a.x + b.x;
  869. this.y = a.y + b.y;
  870. this.z = a.z + b.z;
  871. return this;
  872. },
  873. sub: function ( v, w ) {
  874. if ( w !== undefined ) {
  875. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  876. return this.subVectors( v, w );
  877. }
  878. this.x -= v.x;
  879. this.y -= v.y;
  880. this.z -= v.z;
  881. return this;
  882. },
  883. subVectors: function ( a, b ) {
  884. this.x = a.x - b.x;
  885. this.y = a.y - b.y;
  886. this.z = a.z - b.z;
  887. return this;
  888. },
  889. multiply: function ( v, w ) {
  890. if ( w !== undefined ) {
  891. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  892. return this.multiplyVectors( v, w );
  893. }
  894. this.x *= v.x;
  895. this.y *= v.y;
  896. this.z *= v.z;
  897. return this;
  898. },
  899. multiplyScalar: function ( s ) {
  900. this.x *= s;
  901. this.y *= s;
  902. this.z *= s;
  903. return this;
  904. },
  905. multiplyVectors: function ( a, b ) {
  906. this.x = a.x * b.x;
  907. this.y = a.y * b.y;
  908. this.z = a.z * b.z;
  909. return this;
  910. },
  911. applyMatrix3: function ( m ) {
  912. var x = this.x;
  913. var y = this.y;
  914. var z = this.z;
  915. var e = m.elements;
  916. this.x = e[0] * x + e[3] * y + e[6] * z;
  917. this.y = e[1] * x + e[4] * y + e[7] * z;
  918. this.z = e[2] * x + e[5] * y + e[8] * z;
  919. return this;
  920. },
  921. applyMatrix4: function ( m ) {
  922. // input: THREE.Matrix4 affine matrix
  923. var x = this.x, y = this.y, z = this.z;
  924. var e = m.elements;
  925. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  926. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  927. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  928. return this;
  929. },
  930. applyProjection: function ( m ) {
  931. // input: THREE.Matrix4 projection matrix
  932. var x = this.x, y = this.y, z = this.z;
  933. var e = m.elements;
  934. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  935. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  936. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  937. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  938. return this;
  939. },
  940. applyQuaternion: function ( q ) {
  941. var x = this.x;
  942. var y = this.y;
  943. var z = this.z;
  944. var qx = q.x;
  945. var qy = q.y;
  946. var qz = q.z;
  947. var qw = q.w;
  948. // calculate quat * vector
  949. var ix = qw * x + qy * z - qz * y;
  950. var iy = qw * y + qz * x - qx * z;
  951. var iz = qw * z + qx * y - qy * x;
  952. var iw = -qx * x - qy * y - qz * z;
  953. // calculate result * inverse quat
  954. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  955. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  956. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  957. return this;
  958. },
  959. transformDirection: function ( m ) {
  960. // input: THREE.Matrix4 affine matrix
  961. // vector interpreted as a direction
  962. var x = this.x, y = this.y, z = this.z;
  963. var e = m.elements;
  964. this.x = e[0] * x + e[4] * y + e[8] * z;
  965. this.y = e[1] * x + e[5] * y + e[9] * z;
  966. this.z = e[2] * x + e[6] * y + e[10] * z;
  967. this.normalize();
  968. return this;
  969. },
  970. divide: function ( v ) {
  971. this.x /= v.x;
  972. this.y /= v.y;
  973. this.z /= v.z;
  974. return this;
  975. },
  976. divideScalar: function ( s ) {
  977. if ( s !== 0 ) {
  978. this.x /= s;
  979. this.y /= s;
  980. this.z /= s;
  981. } else {
  982. this.x = 0;
  983. this.y = 0;
  984. this.z = 0;
  985. }
  986. return this;
  987. },
  988. min: function ( v ) {
  989. if ( this.x > v.x ) {
  990. this.x = v.x;
  991. }
  992. if ( this.y > v.y ) {
  993. this.y = v.y;
  994. }
  995. if ( this.z > v.z ) {
  996. this.z = v.z;
  997. }
  998. return this;
  999. },
  1000. max: function ( v ) {
  1001. if ( this.x < v.x ) {
  1002. this.x = v.x;
  1003. }
  1004. if ( this.y < v.y ) {
  1005. this.y = v.y;
  1006. }
  1007. if ( this.z < v.z ) {
  1008. this.z = v.z;
  1009. }
  1010. return this;
  1011. },
  1012. clamp: function ( min, max ) {
  1013. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1014. if ( this.x < min.x ) {
  1015. this.x = min.x;
  1016. } else if ( this.x > max.x ) {
  1017. this.x = max.x;
  1018. }
  1019. if ( this.y < min.y ) {
  1020. this.y = min.y;
  1021. } else if ( this.y > max.y ) {
  1022. this.y = max.y;
  1023. }
  1024. if ( this.z < min.z ) {
  1025. this.z = min.z;
  1026. } else if ( this.z > max.z ) {
  1027. this.z = max.z;
  1028. }
  1029. return this;
  1030. },
  1031. negate: function () {
  1032. return this.multiplyScalar( - 1 );
  1033. },
  1034. dot: function ( v ) {
  1035. return this.x * v.x + this.y * v.y + this.z * v.z;
  1036. },
  1037. lengthSq: function () {
  1038. return this.x * this.x + this.y * this.y + this.z * this.z;
  1039. },
  1040. length: function () {
  1041. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1042. },
  1043. lengthManhattan: function () {
  1044. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1045. },
  1046. normalize: function () {
  1047. return this.divideScalar( this.length() );
  1048. },
  1049. setLength: function ( l ) {
  1050. var oldLength = this.length();
  1051. if ( oldLength !== 0 && l !== oldLength ) {
  1052. this.multiplyScalar( l / oldLength );
  1053. }
  1054. return this;
  1055. },
  1056. lerp: function ( v, alpha ) {
  1057. this.x += ( v.x - this.x ) * alpha;
  1058. this.y += ( v.y - this.y ) * alpha;
  1059. this.z += ( v.z - this.z ) * alpha;
  1060. return this;
  1061. },
  1062. cross: function ( v, w ) {
  1063. if ( w !== undefined ) {
  1064. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1065. return this.crossVectors( v, w );
  1066. }
  1067. var x = this.x, y = this.y, z = this.z;
  1068. this.x = y * v.z - z * v.y;
  1069. this.y = z * v.x - x * v.z;
  1070. this.z = x * v.y - y * v.x;
  1071. return this;
  1072. },
  1073. crossVectors: function ( a, b ) {
  1074. this.x = a.y * b.z - a.z * b.y;
  1075. this.y = a.z * b.x - a.x * b.z;
  1076. this.z = a.x * b.y - a.y * b.x;
  1077. return this;
  1078. },
  1079. angleTo: function ( v ) {
  1080. var theta = this.dot( v ) / ( this.length() * v.length() );
  1081. // clamp, to handle numerical problems
  1082. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1083. },
  1084. distanceTo: function ( v ) {
  1085. return Math.sqrt( this.distanceToSquared( v ) );
  1086. },
  1087. distanceToSquared: function ( v ) {
  1088. var dx = this.x - v.x;
  1089. var dy = this.y - v.y;
  1090. var dz = this.z - v.z;
  1091. return dx * dx + dy * dy + dz * dz;
  1092. },
  1093. setEulerFromRotationMatrix: function ( m, order ) {
  1094. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1095. // clamp, to handle numerical problems
  1096. function clamp( x ) {
  1097. return Math.min( Math.max( x, -1 ), 1 );
  1098. }
  1099. var te = m.elements;
  1100. var m11 = te[0], m12 = te[4], m13 = te[8];
  1101. var m21 = te[1], m22 = te[5], m23 = te[9];
  1102. var m31 = te[2], m32 = te[6], m33 = te[10];
  1103. if ( order === undefined || order === 'XYZ' ) {
  1104. this.y = Math.asin( clamp( m13 ) );
  1105. if ( Math.abs( m13 ) < 0.99999 ) {
  1106. this.x = Math.atan2( - m23, m33 );
  1107. this.z = Math.atan2( - m12, m11 );
  1108. } else {
  1109. this.x = Math.atan2( m32, m22 );
  1110. this.z = 0;
  1111. }
  1112. } else if ( order === 'YXZ' ) {
  1113. this.x = Math.asin( - clamp( m23 ) );
  1114. if ( Math.abs( m23 ) < 0.99999 ) {
  1115. this.y = Math.atan2( m13, m33 );
  1116. this.z = Math.atan2( m21, m22 );
  1117. } else {
  1118. this.y = Math.atan2( - m31, m11 );
  1119. this.z = 0;
  1120. }
  1121. } else if ( order === 'ZXY' ) {
  1122. this.x = Math.asin( clamp( m32 ) );
  1123. if ( Math.abs( m32 ) < 0.99999 ) {
  1124. this.y = Math.atan2( - m31, m33 );
  1125. this.z = Math.atan2( - m12, m22 );
  1126. } else {
  1127. this.y = 0;
  1128. this.z = Math.atan2( m21, m11 );
  1129. }
  1130. } else if ( order === 'ZYX' ) {
  1131. this.y = Math.asin( - clamp( m31 ) );
  1132. if ( Math.abs( m31 ) < 0.99999 ) {
  1133. this.x = Math.atan2( m32, m33 );
  1134. this.z = Math.atan2( m21, m11 );
  1135. } else {
  1136. this.x = 0;
  1137. this.z = Math.atan2( - m12, m22 );
  1138. }
  1139. } else if ( order === 'YZX' ) {
  1140. this.z = Math.asin( clamp( m21 ) );
  1141. if ( Math.abs( m21 ) < 0.99999 ) {
  1142. this.x = Math.atan2( - m23, m22 );
  1143. this.y = Math.atan2( - m31, m11 );
  1144. } else {
  1145. this.x = 0;
  1146. this.y = Math.atan2( m13, m33 );
  1147. }
  1148. } else if ( order === 'XZY' ) {
  1149. this.z = Math.asin( - clamp( m12 ) );
  1150. if ( Math.abs( m12 ) < 0.99999 ) {
  1151. this.x = Math.atan2( m32, m22 );
  1152. this.y = Math.atan2( m13, m11 );
  1153. } else {
  1154. this.x = Math.atan2( - m23, m33 );
  1155. this.y = 0;
  1156. }
  1157. }
  1158. return this;
  1159. },
  1160. setEulerFromQuaternion: function ( q, order ) {
  1161. // q is assumed to be normalized
  1162. // clamp, to handle numerical problems
  1163. function clamp( x ) {
  1164. return Math.min( Math.max( x, -1 ), 1 );
  1165. }
  1166. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1167. var sqx = q.x * q.x;
  1168. var sqy = q.y * q.y;
  1169. var sqz = q.z * q.z;
  1170. var sqw = q.w * q.w;
  1171. if ( order === undefined || order === 'XYZ' ) {
  1172. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1173. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1174. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1175. } else if ( order === 'YXZ' ) {
  1176. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1177. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1178. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1179. } else if ( order === 'ZXY' ) {
  1180. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1181. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1182. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1183. } else if ( order === 'ZYX' ) {
  1184. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1185. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1186. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1187. } else if ( order === 'YZX' ) {
  1188. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1189. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1190. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1191. } else if ( order === 'XZY' ) {
  1192. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1193. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1194. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1195. }
  1196. return this;
  1197. },
  1198. getPositionFromMatrix: function ( m ) {
  1199. this.x = m.elements[12];
  1200. this.y = m.elements[13];
  1201. this.z = m.elements[14];
  1202. return this;
  1203. },
  1204. getScaleFromMatrix: function ( m ) {
  1205. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1206. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1207. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1208. this.x = sx;
  1209. this.y = sy;
  1210. this.z = sz;
  1211. return this;
  1212. },
  1213. getColumnFromMatrix: function ( index, matrix ) {
  1214. var offset = index * 4;
  1215. var me = matrix.elements;
  1216. this.x = me[ offset ];
  1217. this.y = me[ offset + 1 ];
  1218. this.z = me[ offset + 2 ];
  1219. return this;
  1220. },
  1221. equals: function ( v ) {
  1222. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1223. },
  1224. fromArray: function ( array ) {
  1225. this.x = array[ 0 ];
  1226. this.y = array[ 1 ];
  1227. this.z = array[ 2 ];
  1228. return this;
  1229. },
  1230. toArray: function () {
  1231. return [ this.x, this.y, this.z ];
  1232. },
  1233. clone: function () {
  1234. return new THREE.Vector3( this.x, this.y, this.z );
  1235. }
  1236. };
  1237. THREE.extend( THREE.Vector3.prototype, {
  1238. applyEuler: function () {
  1239. var q1 = new THREE.Quaternion();
  1240. return function ( v, eulerOrder ) {
  1241. var quaternion = q1.setFromEuler( v, eulerOrder );
  1242. this.applyQuaternion( quaternion );
  1243. return this;
  1244. };
  1245. }(),
  1246. applyAxisAngle: function () {
  1247. var q1 = new THREE.Quaternion();
  1248. return function ( axis, angle ) {
  1249. var quaternion = q1.setFromAxisAngle( axis, angle );
  1250. this.applyQuaternion( quaternion );
  1251. return this;
  1252. };
  1253. }(),
  1254. projectOnVector: function () {
  1255. var v1 = new THREE.Vector3();
  1256. return function ( vector ) {
  1257. v1.copy( vector ).normalize();
  1258. var d = this.dot( v1 );
  1259. return this.copy( v1 ).multiplyScalar( d );
  1260. };
  1261. }(),
  1262. projectOnPlane: function () {
  1263. var v1 = new THREE.Vector3();
  1264. return function ( planeNormal ) {
  1265. v1.copy( this ).projectOnVector( planeNormal );
  1266. return this.sub( v1 );
  1267. }
  1268. }(),
  1269. reflect: function () {
  1270. var v1 = new THREE.Vector3();
  1271. return function ( vector ) {
  1272. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1273. return this.subVectors( v1, this );
  1274. }
  1275. }()
  1276. } );
  1277. /**
  1278. * @author supereggbert / http://www.paulbrunt.co.uk/
  1279. * @author philogb / http://blog.thejit.org/
  1280. * @author mikael emtinger / http://gomo.se/
  1281. * @author egraether / http://egraether.com/
  1282. * @author WestLangley / http://github.com/WestLangley
  1283. */
  1284. THREE.Vector4 = function ( x, y, z, w ) {
  1285. this.x = x || 0;
  1286. this.y = y || 0;
  1287. this.z = z || 0;
  1288. this.w = ( w !== undefined ) ? w : 1;
  1289. };
  1290. THREE.Vector4.prototype = {
  1291. constructor: THREE.Vector4,
  1292. set: function ( x, y, z, w ) {
  1293. this.x = x;
  1294. this.y = y;
  1295. this.z = z;
  1296. this.w = w;
  1297. return this;
  1298. },
  1299. setX: function ( x ) {
  1300. this.x = x;
  1301. return this;
  1302. },
  1303. setY: function ( y ) {
  1304. this.y = y;
  1305. return this;
  1306. },
  1307. setZ: function ( z ) {
  1308. this.z = z;
  1309. return this;
  1310. },
  1311. setW: function ( w ) {
  1312. this.w = w;
  1313. return this;
  1314. },
  1315. setComponent: function ( index, value ) {
  1316. switch ( index ) {
  1317. case 0: this.x = value; break;
  1318. case 1: this.y = value; break;
  1319. case 2: this.z = value; break;
  1320. case 3: this.w = value; break;
  1321. default: throw new Error( "index is out of range: " + index );
  1322. }
  1323. },
  1324. getComponent: function ( index ) {
  1325. switch ( index ) {
  1326. case 0: return this.x;
  1327. case 1: return this.y;
  1328. case 2: return this.z;
  1329. case 3: return this.w;
  1330. default: throw new Error( "index is out of range: " + index );
  1331. }
  1332. },
  1333. copy: function ( v ) {
  1334. this.x = v.x;
  1335. this.y = v.y;
  1336. this.z = v.z;
  1337. this.w = ( v.w !== undefined ) ? v.w : 1;
  1338. return this;
  1339. },
  1340. add: function ( v, w ) {
  1341. if ( w !== undefined ) {
  1342. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1343. return this.addVectors( v, w );
  1344. }
  1345. this.x += v.x;
  1346. this.y += v.y;
  1347. this.z += v.z;
  1348. this.w += v.w;
  1349. return this;
  1350. },
  1351. addScalar: function ( s ) {
  1352. this.x += s;
  1353. this.y += s;
  1354. this.z += s;
  1355. this.w += s;
  1356. return this;
  1357. },
  1358. addVectors: function ( a, b ) {
  1359. this.x = a.x + b.x;
  1360. this.y = a.y + b.y;
  1361. this.z = a.z + b.z;
  1362. this.w = a.w + b.w;
  1363. return this;
  1364. },
  1365. sub: function ( v, w ) {
  1366. if ( w !== undefined ) {
  1367. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1368. return this.subVectors( v, w );
  1369. }
  1370. this.x -= v.x;
  1371. this.y -= v.y;
  1372. this.z -= v.z;
  1373. this.w -= v.w;
  1374. return this;
  1375. },
  1376. subVectors: function ( a, b ) {
  1377. this.x = a.x - b.x;
  1378. this.y = a.y - b.y;
  1379. this.z = a.z - b.z;
  1380. this.w = a.w - b.w;
  1381. return this;
  1382. },
  1383. multiplyScalar: function ( s ) {
  1384. this.x *= s;
  1385. this.y *= s;
  1386. this.z *= s;
  1387. this.w *= s;
  1388. return this;
  1389. },
  1390. applyMatrix4: function ( m ) {
  1391. var x = this.x;
  1392. var y = this.y;
  1393. var z = this.z;
  1394. var w = this.w;
  1395. var e = m.elements;
  1396. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1397. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1398. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1399. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1400. return this;
  1401. },
  1402. divideScalar: function ( s ) {
  1403. if ( s !== 0 ) {
  1404. this.x /= s;
  1405. this.y /= s;
  1406. this.z /= s;
  1407. this.w /= s;
  1408. } else {
  1409. this.x = 0;
  1410. this.y = 0;
  1411. this.z = 0;
  1412. this.w = 1;
  1413. }
  1414. return this;
  1415. },
  1416. setAxisAngleFromQuaternion: function ( q ) {
  1417. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1418. // q is assumed to be normalized
  1419. this.w = 2 * Math.acos( q.w );
  1420. var s = Math.sqrt( 1 - q.w * q.w );
  1421. if ( s < 0.0001 ) {
  1422. this.x = 1;
  1423. this.y = 0;
  1424. this.z = 0;
  1425. } else {
  1426. this.x = q.x / s;
  1427. this.y = q.y / s;
  1428. this.z = q.z / s;
  1429. }
  1430. return this;
  1431. },
  1432. setAxisAngleFromRotationMatrix: function ( m ) {
  1433. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1434. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1435. var angle, x, y, z, // variables for result
  1436. epsilon = 0.01, // margin to allow for rounding errors
  1437. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1438. te = m.elements,
  1439. m11 = te[0], m12 = te[4], m13 = te[8],
  1440. m21 = te[1], m22 = te[5], m23 = te[9],
  1441. m31 = te[2], m32 = te[6], m33 = te[10];
  1442. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1443. && ( Math.abs( m13 - m31 ) < epsilon )
  1444. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1445. // singularity found
  1446. // first check for identity matrix which must have +1 for all terms
  1447. // in leading diagonal and zero in other terms
  1448. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1449. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1450. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1451. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1452. // this singularity is identity matrix so angle = 0
  1453. this.set( 1, 0, 0, 0 );
  1454. return this; // zero angle, arbitrary axis
  1455. }
  1456. // otherwise this singularity is angle = 180
  1457. angle = Math.PI;
  1458. var xx = ( m11 + 1 ) / 2;
  1459. var yy = ( m22 + 1 ) / 2;
  1460. var zz = ( m33 + 1 ) / 2;
  1461. var xy = ( m12 + m21 ) / 4;
  1462. var xz = ( m13 + m31 ) / 4;
  1463. var yz = ( m23 + m32 ) / 4;
  1464. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1465. if ( xx < epsilon ) {
  1466. x = 0;
  1467. y = 0.707106781;
  1468. z = 0.707106781;
  1469. } else {
  1470. x = Math.sqrt( xx );
  1471. y = xy / x;
  1472. z = xz / x;
  1473. }
  1474. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1475. if ( yy < epsilon ) {
  1476. x = 0.707106781;
  1477. y = 0;
  1478. z = 0.707106781;
  1479. } else {
  1480. y = Math.sqrt( yy );
  1481. x = xy / y;
  1482. z = yz / y;
  1483. }
  1484. } else { // m33 is the largest diagonal term so base result on this
  1485. if ( zz < epsilon ) {
  1486. x = 0.707106781;
  1487. y = 0.707106781;
  1488. z = 0;
  1489. } else {
  1490. z = Math.sqrt( zz );
  1491. x = xz / z;
  1492. y = yz / z;
  1493. }
  1494. }
  1495. this.set( x, y, z, angle );
  1496. return this; // return 180 deg rotation
  1497. }
  1498. // as we have reached here there are no singularities so we can handle normally
  1499. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1500. + ( m13 - m31 ) * ( m13 - m31 )
  1501. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1502. if ( Math.abs( s ) < 0.001 ) s = 1;
  1503. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1504. // caught by singularity test above, but I've left it in just in case
  1505. this.x = ( m32 - m23 ) / s;
  1506. this.y = ( m13 - m31 ) / s;
  1507. this.z = ( m21 - m12 ) / s;
  1508. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1509. return this;
  1510. },
  1511. min: function ( v ) {
  1512. if ( this.x > v.x ) {
  1513. this.x = v.x;
  1514. }
  1515. if ( this.y > v.y ) {
  1516. this.y = v.y;
  1517. }
  1518. if ( this.z > v.z ) {
  1519. this.z = v.z;
  1520. }
  1521. if ( this.w > v.w ) {
  1522. this.w = v.w;
  1523. }
  1524. return this;
  1525. },
  1526. max: function ( v ) {
  1527. if ( this.x < v.x ) {
  1528. this.x = v.x;
  1529. }
  1530. if ( this.y < v.y ) {
  1531. this.y = v.y;
  1532. }
  1533. if ( this.z < v.z ) {
  1534. this.z = v.z;
  1535. }
  1536. if ( this.w < v.w ) {
  1537. this.w = v.w;
  1538. }
  1539. return this;
  1540. },
  1541. clamp: function ( min, max ) {
  1542. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1543. if ( this.x < min.x ) {
  1544. this.x = min.x;
  1545. } else if ( this.x > max.x ) {
  1546. this.x = max.x;
  1547. }
  1548. if ( this.y < min.y ) {
  1549. this.y = min.y;
  1550. } else if ( this.y > max.y ) {
  1551. this.y = max.y;
  1552. }
  1553. if ( this.z < min.z ) {
  1554. this.z = min.z;
  1555. } else if ( this.z > max.z ) {
  1556. this.z = max.z;
  1557. }
  1558. if ( this.w < min.w ) {
  1559. this.w = min.w;
  1560. } else if ( this.w > max.w ) {
  1561. this.w = max.w;
  1562. }
  1563. return this;
  1564. },
  1565. negate: function() {
  1566. return this.multiplyScalar( -1 );
  1567. },
  1568. dot: function ( v ) {
  1569. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1570. },
  1571. lengthSq: function () {
  1572. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1573. },
  1574. length: function () {
  1575. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1576. },
  1577. lengthManhattan: function () {
  1578. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1579. },
  1580. normalize: function () {
  1581. return this.divideScalar( this.length() );
  1582. },
  1583. setLength: function ( l ) {
  1584. var oldLength = this.length();
  1585. if ( oldLength !== 0 && l !== oldLength ) {
  1586. this.multiplyScalar( l / oldLength );
  1587. }
  1588. return this;
  1589. },
  1590. lerp: function ( v, alpha ) {
  1591. this.x += ( v.x - this.x ) * alpha;
  1592. this.y += ( v.y - this.y ) * alpha;
  1593. this.z += ( v.z - this.z ) * alpha;
  1594. this.w += ( v.w - this.w ) * alpha;
  1595. return this;
  1596. },
  1597. equals: function ( v ) {
  1598. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1599. },
  1600. fromArray: function ( array ) {
  1601. this.x = array[ 0 ];
  1602. this.y = array[ 1 ];
  1603. this.z = array[ 2 ];
  1604. this.w = array[ 3 ];
  1605. return this;
  1606. },
  1607. toArray: function () {
  1608. return [ this.x, this.y, this.z, this.w ];
  1609. },
  1610. clone: function () {
  1611. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1612. }
  1613. };
  1614. /**
  1615. * @author bhouston / http://exocortex.com
  1616. */
  1617. THREE.Line3 = function ( start, end ) {
  1618. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1619. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1620. };
  1621. THREE.Line3.prototype = {
  1622. constructor: THREE.Line3,
  1623. set: function ( start, end ) {
  1624. this.start.copy( start );
  1625. this.end.copy( end );
  1626. return this;
  1627. },
  1628. copy: function ( line ) {
  1629. this.start.copy( line.start );
  1630. this.end.copy( line.end );
  1631. return this;
  1632. },
  1633. center: function ( optionalTarget ) {
  1634. var result = optionalTarget || new THREE.Vector3();
  1635. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1636. },
  1637. delta: function ( optionalTarget ) {
  1638. var result = optionalTarget || new THREE.Vector3();
  1639. return result.subVectors( this.end, this.start );
  1640. },
  1641. distanceSq: function () {
  1642. return this.start.distanceToSquared( this.end );
  1643. },
  1644. distance: function () {
  1645. return this.start.distanceTo( this.end );
  1646. },
  1647. at: function ( t, optionalTarget ) {
  1648. var result = optionalTarget || new THREE.Vector3();
  1649. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1650. },
  1651. closestPointToPointParameter: function() {
  1652. var startP = new THREE.Vector3();
  1653. var startEnd = new THREE.Vector3();
  1654. return function ( point, clampToLine ) {
  1655. startP.subVectors( point, this.start );
  1656. startEnd.subVectors( this.end, this.start );
  1657. var startEnd2 = startEnd.dot( startEnd );
  1658. var startEnd_startP = startEnd.dot( startP );
  1659. var t = startEnd_startP / startEnd2;
  1660. if ( clampToLine ) {
  1661. t = THREE.Math.clamp( t, 0, 1 );
  1662. }
  1663. return t;
  1664. };
  1665. }(),
  1666. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1667. var t = this.closestPointToPointParameter( point, clampToLine );
  1668. var result = optionalTarget || new THREE.Vector3();
  1669. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1670. },
  1671. applyMatrix4: function ( matrix ) {
  1672. this.start.applyMatrix4( matrix );
  1673. this.end.applyMatrix4( matrix );
  1674. return this;
  1675. },
  1676. equals: function ( line ) {
  1677. return line.start.equals( this.start ) && line.end.equals( this.end );
  1678. },
  1679. clone: function () {
  1680. return new THREE.Line3().copy( this );
  1681. }
  1682. };
  1683. /**
  1684. * @author bhouston / http://exocortex.com
  1685. */
  1686. THREE.Box2 = function ( min, max ) {
  1687. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1688. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1689. };
  1690. THREE.Box2.prototype = {
  1691. constructor: THREE.Box2,
  1692. set: function ( min, max ) {
  1693. this.min.copy( min );
  1694. this.max.copy( max );
  1695. return this;
  1696. },
  1697. setFromPoints: function ( points ) {
  1698. if ( points.length > 0 ) {
  1699. var point = points[ 0 ];
  1700. this.min.copy( point );
  1701. this.max.copy( point );
  1702. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1703. point = points[ i ];
  1704. if ( point.x < this.min.x ) {
  1705. this.min.x = point.x;
  1706. } else if ( point.x > this.max.x ) {
  1707. this.max.x = point.x;
  1708. }
  1709. if ( point.y < this.min.y ) {
  1710. this.min.y = point.y;
  1711. } else if ( point.y > this.max.y ) {
  1712. this.max.y = point.y;
  1713. }
  1714. }
  1715. } else {
  1716. this.makeEmpty();
  1717. }
  1718. return this;
  1719. },
  1720. setFromCenterAndSize: function () {
  1721. var v1 = new THREE.Vector2();
  1722. return function ( center, size ) {
  1723. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1724. this.min.copy( center ).sub( halfSize );
  1725. this.max.copy( center ).add( halfSize );
  1726. return this;
  1727. };
  1728. }(),
  1729. copy: function ( box ) {
  1730. this.min.copy( box.min );
  1731. this.max.copy( box.max );
  1732. return this;
  1733. },
  1734. makeEmpty: function () {
  1735. this.min.x = this.min.y = Infinity;
  1736. this.max.x = this.max.y = -Infinity;
  1737. return this;
  1738. },
  1739. empty: function () {
  1740. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1741. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1742. },
  1743. center: function ( optionalTarget ) {
  1744. var result = optionalTarget || new THREE.Vector2();
  1745. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1746. },
  1747. size: function ( optionalTarget ) {
  1748. var result = optionalTarget || new THREE.Vector2();
  1749. return result.subVectors( this.max, this.min );
  1750. },
  1751. expandByPoint: function ( point ) {
  1752. this.min.min( point );
  1753. this.max.max( point );
  1754. return this;
  1755. },
  1756. expandByVector: function ( vector ) {
  1757. this.min.sub( vector );
  1758. this.max.add( vector );
  1759. return this;
  1760. },
  1761. expandByScalar: function ( scalar ) {
  1762. this.min.addScalar( -scalar );
  1763. this.max.addScalar( scalar );
  1764. return this;
  1765. },
  1766. containsPoint: function ( point ) {
  1767. if ( point.x < this.min.x || point.x > this.max.x ||
  1768. point.y < this.min.y || point.y > this.max.y ) {
  1769. return false;
  1770. }
  1771. return true;
  1772. },
  1773. containsBox: function ( box ) {
  1774. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1775. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1776. return true;
  1777. }
  1778. return false;
  1779. },
  1780. getParameter: function ( point ) {
  1781. // This can potentially have a divide by zero if the box
  1782. // has a size dimension of 0.
  1783. return new THREE.Vector2(
  1784. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1785. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1786. );
  1787. },
  1788. isIntersectionBox: function ( box ) {
  1789. // using 6 splitting planes to rule out intersections.
  1790. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1791. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1792. return false;
  1793. }
  1794. return true;
  1795. },
  1796. clampPoint: function ( point, optionalTarget ) {
  1797. var result = optionalTarget || new THREE.Vector2();
  1798. return result.copy( point ).clamp( this.min, this.max );
  1799. },
  1800. distanceToPoint: function () {
  1801. var v1 = new THREE.Vector2();
  1802. return function ( point ) {
  1803. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1804. return clampedPoint.sub( point ).length();
  1805. };
  1806. }(),
  1807. intersect: function ( box ) {
  1808. this.min.max( box.min );
  1809. this.max.min( box.max );
  1810. return this;
  1811. },
  1812. union: function ( box ) {
  1813. this.min.min( box.min );
  1814. this.max.max( box.max );
  1815. return this;
  1816. },
  1817. translate: function ( offset ) {
  1818. this.min.add( offset );
  1819. this.max.add( offset );
  1820. return this;
  1821. },
  1822. equals: function ( box ) {
  1823. return box.min.equals( this.min ) && box.max.equals( this.max );
  1824. },
  1825. clone: function () {
  1826. return new THREE.Box2().copy( this );
  1827. }
  1828. };
  1829. /**
  1830. * @author bhouston / http://exocortex.com
  1831. */
  1832. THREE.Box3 = function ( min, max ) {
  1833. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1834. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1835. };
  1836. THREE.Box3.prototype = {
  1837. constructor: THREE.Box3,
  1838. set: function ( min, max ) {
  1839. this.min.copy( min );
  1840. this.max.copy( max );
  1841. return this;
  1842. },
  1843. setFromPoints: function ( points ) {
  1844. if ( points.length > 0 ) {
  1845. var point = points[ 0 ];
  1846. this.min.copy( point );
  1847. this.max.copy( point );
  1848. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1849. point = points[ i ];
  1850. if ( point.x < this.min.x ) {
  1851. this.min.x = point.x;
  1852. } else if ( point.x > this.max.x ) {
  1853. this.max.x = point.x;
  1854. }
  1855. if ( point.y < this.min.y ) {
  1856. this.min.y = point.y;
  1857. } else if ( point.y > this.max.y ) {
  1858. this.max.y = point.y;
  1859. }
  1860. if ( point.z < this.min.z ) {
  1861. this.min.z = point.z;
  1862. } else if ( point.z > this.max.z ) {
  1863. this.max.z = point.z;
  1864. }
  1865. }
  1866. } else {
  1867. this.makeEmpty();
  1868. }
  1869. return this;
  1870. },
  1871. setFromCenterAndSize: function() {
  1872. var v1 = new THREE.Vector3();
  1873. return function ( center, size ) {
  1874. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1875. this.min.copy( center ).sub( halfSize );
  1876. this.max.copy( center ).add( halfSize );
  1877. return this;
  1878. };
  1879. }(),
  1880. copy: function ( box ) {
  1881. this.min.copy( box.min );
  1882. this.max.copy( box.max );
  1883. return this;
  1884. },
  1885. makeEmpty: function () {
  1886. this.min.x = this.min.y = this.min.z = Infinity;
  1887. this.max.x = this.max.y = this.max.z = -Infinity;
  1888. return this;
  1889. },
  1890. empty: function () {
  1891. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1892. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1893. },
  1894. center: function ( optionalTarget ) {
  1895. var result = optionalTarget || new THREE.Vector3();
  1896. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1897. },
  1898. size: function ( optionalTarget ) {
  1899. var result = optionalTarget || new THREE.Vector3();
  1900. return result.subVectors( this.max, this.min );
  1901. },
  1902. expandByPoint: function ( point ) {
  1903. this.min.min( point );
  1904. this.max.max( point );
  1905. return this;
  1906. },
  1907. expandByVector: function ( vector ) {
  1908. this.min.sub( vector );
  1909. this.max.add( vector );
  1910. return this;
  1911. },
  1912. expandByScalar: function ( scalar ) {
  1913. this.min.addScalar( -scalar );
  1914. this.max.addScalar( scalar );
  1915. return this;
  1916. },
  1917. containsPoint: function ( point ) {
  1918. if ( point.x < this.min.x || point.x > this.max.x ||
  1919. point.y < this.min.y || point.y > this.max.y ||
  1920. point.z < this.min.z || point.z > this.max.z ) {
  1921. return false;
  1922. }
  1923. return true;
  1924. },
  1925. containsBox: function ( box ) {
  1926. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1927. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1928. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1929. return true;
  1930. }
  1931. return false;
  1932. },
  1933. getParameter: function ( point ) {
  1934. // This can potentially have a divide by zero if the box
  1935. // has a size dimension of 0.
  1936. return new THREE.Vector3(
  1937. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1938. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1939. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1940. );
  1941. },
  1942. isIntersectionBox: function ( box ) {
  1943. // using 6 splitting planes to rule out intersections.
  1944. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1945. box.max.y < this.min.y || box.min.y > this.max.y ||
  1946. box.max.z < this.min.z || box.min.z > this.max.z ) {
  1947. return false;
  1948. }
  1949. return true;
  1950. },
  1951. clampPoint: function ( point, optionalTarget ) {
  1952. var result = optionalTarget || new THREE.Vector3();
  1953. return result.copy( point ).clamp( this.min, this.max );
  1954. },
  1955. distanceToPoint: function() {
  1956. var v1 = new THREE.Vector3();
  1957. return function ( point ) {
  1958. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1959. return clampedPoint.sub( point ).length();
  1960. };
  1961. }(),
  1962. getBoundingSphere: function() {
  1963. var v1 = new THREE.Vector3();
  1964. return function ( optionalTarget ) {
  1965. var result = optionalTarget || new THREE.Sphere();
  1966. result.center = this.center();
  1967. result.radius = this.size( v1 ).length() * 0.5;
  1968. return result;
  1969. };
  1970. }(),
  1971. intersect: function ( box ) {
  1972. this.min.max( box.min );
  1973. this.max.min( box.max );
  1974. return this;
  1975. },
  1976. union: function ( box ) {
  1977. this.min.min( box.min );
  1978. this.max.max( box.max );
  1979. return this;
  1980. },
  1981. applyMatrix4: function() {
  1982. var points = [
  1983. new THREE.Vector3(),
  1984. new THREE.Vector3(),
  1985. new THREE.Vector3(),
  1986. new THREE.Vector3(),
  1987. new THREE.Vector3(),
  1988. new THREE.Vector3(),
  1989. new THREE.Vector3(),
  1990. new THREE.Vector3()
  1991. ];
  1992. return function ( matrix ) {
  1993. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1994. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  1995. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  1996. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  1997. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  1998. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  1999. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2000. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2001. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2002. this.makeEmpty();
  2003. this.setFromPoints( points );
  2004. return this;
  2005. };
  2006. }(),
  2007. translate: function ( offset ) {
  2008. this.min.add( offset );
  2009. this.max.add( offset );
  2010. return this;
  2011. },
  2012. equals: function ( box ) {
  2013. return box.min.equals( this.min ) && box.max.equals( this.max );
  2014. },
  2015. clone: function () {
  2016. return new THREE.Box3().copy( this );
  2017. }
  2018. };
  2019. /**
  2020. * @author alteredq / http://alteredqualia.com/
  2021. * @author WestLangley / http://github.com/WestLangley
  2022. * @author bhouston / http://exocortex.com
  2023. */
  2024. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2025. this.elements = new Float32Array(9);
  2026. this.set(
  2027. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2028. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2029. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2030. );
  2031. };
  2032. THREE.Matrix3.prototype = {
  2033. constructor: THREE.Matrix3,
  2034. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2035. var te = this.elements;
  2036. te[0] = n11; te[3] = n12; te[6] = n13;
  2037. te[1] = n21; te[4] = n22; te[7] = n23;
  2038. te[2] = n31; te[5] = n32; te[8] = n33;
  2039. return this;
  2040. },
  2041. identity: function () {
  2042. this.set(
  2043. 1, 0, 0,
  2044. 0, 1, 0,
  2045. 0, 0, 1
  2046. );
  2047. return this;
  2048. },
  2049. copy: function ( m ) {
  2050. var me = m.elements;
  2051. this.set(
  2052. me[0], me[3], me[6],
  2053. me[1], me[4], me[7],
  2054. me[2], me[5], me[8]
  2055. );
  2056. return this;
  2057. },
  2058. multiplyVector3: function ( vector ) {
  2059. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2060. return vector.applyMatrix3( this );
  2061. },
  2062. multiplyVector3Array: function() {
  2063. var v1 = new THREE.Vector3();
  2064. return function ( a ) {
  2065. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2066. v1.x = a[ i ];
  2067. v1.y = a[ i + 1 ];
  2068. v1.z = a[ i + 2 ];
  2069. v1.applyMatrix3(this);
  2070. a[ i ] = v1.x;
  2071. a[ i + 1 ] = v1.y;
  2072. a[ i + 2 ] = v1.z;
  2073. }
  2074. return a;
  2075. };
  2076. }(),
  2077. multiplyScalar: function ( s ) {
  2078. var te = this.elements;
  2079. te[0] *= s; te[3] *= s; te[6] *= s;
  2080. te[1] *= s; te[4] *= s; te[7] *= s;
  2081. te[2] *= s; te[5] *= s; te[8] *= s;
  2082. return this;
  2083. },
  2084. determinant: function () {
  2085. var te = this.elements;
  2086. var a = te[0], b = te[1], c = te[2],
  2087. d = te[3], e = te[4], f = te[5],
  2088. g = te[6], h = te[7], i = te[8];
  2089. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2090. },
  2091. getInverse: function ( matrix, throwOnInvertible ) {
  2092. // input: THREE.Matrix4
  2093. // ( based on http://code.google.com/p/webgl-mjs/ )
  2094. var me = matrix.elements;
  2095. var te = this.elements;
  2096. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2097. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2098. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2099. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2100. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2101. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2102. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2103. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2104. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2105. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2106. // no inverse
  2107. if ( det === 0 ) {
  2108. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2109. if ( throwOnInvertible || false ) {
  2110. throw new Error( msg );
  2111. } else {
  2112. console.warn( msg );
  2113. }
  2114. this.identity();
  2115. return this;
  2116. }
  2117. this.multiplyScalar( 1.0 / det );
  2118. return this;
  2119. },
  2120. transpose: function () {
  2121. var tmp, m = this.elements;
  2122. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2123. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2124. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2125. return this;
  2126. },
  2127. getNormalMatrix: function ( m ) {
  2128. // input: THREE.Matrix4
  2129. this.getInverse( m ).transpose();
  2130. return this;
  2131. },
  2132. transposeIntoArray: function ( r ) {
  2133. var m = this.elements;
  2134. r[ 0 ] = m[ 0 ];
  2135. r[ 1 ] = m[ 3 ];
  2136. r[ 2 ] = m[ 6 ];
  2137. r[ 3 ] = m[ 1 ];
  2138. r[ 4 ] = m[ 4 ];
  2139. r[ 5 ] = m[ 7 ];
  2140. r[ 6 ] = m[ 2 ];
  2141. r[ 7 ] = m[ 5 ];
  2142. r[ 8 ] = m[ 8 ];
  2143. return this;
  2144. },
  2145. clone: function () {
  2146. var te = this.elements;
  2147. return new THREE.Matrix3(
  2148. te[0], te[3], te[6],
  2149. te[1], te[4], te[7],
  2150. te[2], te[5], te[8]
  2151. );
  2152. }
  2153. };
  2154. /**
  2155. * @author mrdoob / http://mrdoob.com/
  2156. * @author supereggbert / http://www.paulbrunt.co.uk/
  2157. * @author philogb / http://blog.thejit.org/
  2158. * @author jordi_ros / http://plattsoft.com
  2159. * @author D1plo1d / http://github.com/D1plo1d
  2160. * @author alteredq / http://alteredqualia.com/
  2161. * @author mikael emtinger / http://gomo.se/
  2162. * @author timknip / http://www.floorplanner.com/
  2163. * @author bhouston / http://exocortex.com
  2164. * @author WestLangley / http://github.com/WestLangley
  2165. */
  2166. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2167. var te = this.elements = new Float32Array( 16 );
  2168. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2169. // we should not support semi specification of Matrix4, it is just weird.
  2170. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2171. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2172. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2173. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2174. };
  2175. THREE.Matrix4.prototype = {
  2176. constructor: THREE.Matrix4,
  2177. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2178. var te = this.elements;
  2179. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2180. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2181. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2182. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2183. return this;
  2184. },
  2185. identity: function () {
  2186. this.set(
  2187. 1, 0, 0, 0,
  2188. 0, 1, 0, 0,
  2189. 0, 0, 1, 0,
  2190. 0, 0, 0, 1
  2191. );
  2192. return this;
  2193. },
  2194. copy: function ( m ) {
  2195. var me = m.elements;
  2196. this.set(
  2197. me[0], me[4], me[8], me[12],
  2198. me[1], me[5], me[9], me[13],
  2199. me[2], me[6], me[10], me[14],
  2200. me[3], me[7], me[11], me[15]
  2201. );
  2202. return this;
  2203. },
  2204. extractPosition: function ( m ) {
  2205. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2206. return this.copyPosition( m );
  2207. },
  2208. copyPosition: function ( m ) {
  2209. var te = this.elements;
  2210. var me = m.elements;
  2211. te[12] = me[12];
  2212. te[13] = me[13];
  2213. te[14] = me[14];
  2214. return this;
  2215. },
  2216. extractRotation: function () {
  2217. var v1 = new THREE.Vector3();
  2218. return function ( m ) {
  2219. var te = this.elements;
  2220. var me = m.elements;
  2221. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2222. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2223. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2224. te[0] = me[0] * scaleX;
  2225. te[1] = me[1] * scaleX;
  2226. te[2] = me[2] * scaleX;
  2227. te[4] = me[4] * scaleY;
  2228. te[5] = me[5] * scaleY;
  2229. te[6] = me[6] * scaleY;
  2230. te[8] = me[8] * scaleZ;
  2231. te[9] = me[9] * scaleZ;
  2232. te[10] = me[10] * scaleZ;
  2233. return this;
  2234. };
  2235. }(),
  2236. setRotationFromEuler: function ( v, order ) {
  2237. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromEuler() has been deprecated in favor of makeRotationFromEuler. Please update your code.' );
  2238. return this.makeRotationFromEuler( v, order );
  2239. },
  2240. makeRotationFromEuler: function ( v, order ) {
  2241. var te = this.elements;
  2242. var x = v.x, y = v.y, z = v.z;
  2243. var a = Math.cos( x ), b = Math.sin( x );
  2244. var c = Math.cos( y ), d = Math.sin( y );
  2245. var e = Math.cos( z ), f = Math.sin( z );
  2246. if ( order === undefined || order === 'XYZ' ) {
  2247. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2248. te[0] = c * e;
  2249. te[4] = - c * f;
  2250. te[8] = d;
  2251. te[1] = af + be * d;
  2252. te[5] = ae - bf * d;
  2253. te[9] = - b * c;
  2254. te[2] = bf - ae * d;
  2255. te[6] = be + af * d;
  2256. te[10] = a * c;
  2257. } else if ( order === 'YXZ' ) {
  2258. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2259. te[0] = ce + df * b;
  2260. te[4] = de * b - cf;
  2261. te[8] = a * d;
  2262. te[1] = a * f;
  2263. te[5] = a * e;
  2264. te[9] = - b;
  2265. te[2] = cf * b - de;
  2266. te[6] = df + ce * b;
  2267. te[10] = a * c;
  2268. } else if ( order === 'ZXY' ) {
  2269. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2270. te[0] = ce - df * b;
  2271. te[4] = - a * f;
  2272. te[8] = de + cf * b;
  2273. te[1] = cf + de * b;
  2274. te[5] = a * e;
  2275. te[9] = df - ce * b;
  2276. te[2] = - a * d;
  2277. te[6] = b;
  2278. te[10] = a * c;
  2279. } else if ( order === 'ZYX' ) {
  2280. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2281. te[0] = c * e;
  2282. te[4] = be * d - af;
  2283. te[8] = ae * d + bf;
  2284. te[1] = c * f;
  2285. te[5] = bf * d + ae;
  2286. te[9] = af * d - be;
  2287. te[2] = - d;
  2288. te[6] = b * c;
  2289. te[10] = a * c;
  2290. } else if ( order === 'YZX' ) {
  2291. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2292. te[0] = c * e;
  2293. te[4] = bd - ac * f;
  2294. te[8] = bc * f + ad;
  2295. te[1] = f;
  2296. te[5] = a * e;
  2297. te[9] = - b * e;
  2298. te[2] = - d * e;
  2299. te[6] = ad * f + bc;
  2300. te[10] = ac - bd * f;
  2301. } else if ( order === 'XZY' ) {
  2302. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2303. te[0] = c * e;
  2304. te[4] = - f;
  2305. te[8] = d * e;
  2306. te[1] = ac * f + bd;
  2307. te[5] = a * e;
  2308. te[9] = ad * f - bc;
  2309. te[2] = bc * f - ad;
  2310. te[6] = b * e;
  2311. te[10] = bd * f + ac;
  2312. }
  2313. // last column
  2314. te[3] = 0;
  2315. te[7] = 0;
  2316. te[11] = 0;
  2317. // bottom row
  2318. te[12] = 0;
  2319. te[13] = 0;
  2320. te[14] = 0;
  2321. te[15] = 1;
  2322. return this;
  2323. },
  2324. setRotationFromQuaternion: function ( q ) {
  2325. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2326. return this.makeRotationFromQuaternion( q );
  2327. },
  2328. makeRotationFromQuaternion: function ( q ) {
  2329. var te = this.elements;
  2330. var x = q.x, y = q.y, z = q.z, w = q.w;
  2331. var x2 = x + x, y2 = y + y, z2 = z + z;
  2332. var xx = x * x2, xy = x * y2, xz = x * z2;
  2333. var yy = y * y2, yz = y * z2, zz = z * z2;
  2334. var wx = w * x2, wy = w * y2, wz = w * z2;
  2335. te[0] = 1 - ( yy + zz );
  2336. te[4] = xy - wz;
  2337. te[8] = xz + wy;
  2338. te[1] = xy + wz;
  2339. te[5] = 1 - ( xx + zz );
  2340. te[9] = yz - wx;
  2341. te[2] = xz - wy;
  2342. te[6] = yz + wx;
  2343. te[10] = 1 - ( xx + yy );
  2344. // last column
  2345. te[3] = 0;
  2346. te[7] = 0;
  2347. te[11] = 0;
  2348. // bottom row
  2349. te[12] = 0;
  2350. te[13] = 0;
  2351. te[14] = 0;
  2352. te[15] = 1;
  2353. return this;
  2354. },
  2355. lookAt: function() {
  2356. var x = new THREE.Vector3();
  2357. var y = new THREE.Vector3();
  2358. var z = new THREE.Vector3();
  2359. return function ( eye, target, up ) {
  2360. var te = this.elements;
  2361. z.subVectors( eye, target ).normalize();
  2362. if ( z.length() === 0 ) {
  2363. z.z = 1;
  2364. }
  2365. x.crossVectors( up, z ).normalize();
  2366. if ( x.length() === 0 ) {
  2367. z.x += 0.0001;
  2368. x.crossVectors( up, z ).normalize();
  2369. }
  2370. y.crossVectors( z, x );
  2371. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2372. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2373. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2374. return this;
  2375. };
  2376. }(),
  2377. multiply: function ( m, n ) {
  2378. if ( n !== undefined ) {
  2379. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2380. return this.multiplyMatrices( m, n );
  2381. }
  2382. return this.multiplyMatrices( this, m );
  2383. },
  2384. multiplyMatrices: function ( a, b ) {
  2385. var ae = a.elements;
  2386. var be = b.elements;
  2387. var te = this.elements;
  2388. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2389. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2390. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2391. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2392. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2393. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2394. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2395. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2396. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2397. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2398. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2399. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2400. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2401. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2402. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2403. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2404. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2405. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2406. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2407. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2408. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2409. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2410. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2411. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2412. return this;
  2413. },
  2414. multiplyToArray: function ( a, b, r ) {
  2415. var te = this.elements;
  2416. this.multiplyMatrices( a, b );
  2417. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2418. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2419. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2420. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2421. return this;
  2422. },
  2423. multiplyScalar: function ( s ) {
  2424. var te = this.elements;
  2425. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2426. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2427. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2428. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2429. return this;
  2430. },
  2431. multiplyVector3: function ( vector ) {
  2432. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2433. return vector.applyProjection( this );
  2434. },
  2435. multiplyVector4: function ( vector ) {
  2436. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2437. return vector.applyMatrix4( this );
  2438. },
  2439. multiplyVector3Array: function() {
  2440. var v1 = new THREE.Vector3();
  2441. return function ( a ) {
  2442. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2443. v1.x = a[ i ];
  2444. v1.y = a[ i + 1 ];
  2445. v1.z = a[ i + 2 ];
  2446. v1.applyProjection( this );
  2447. a[ i ] = v1.x;
  2448. a[ i + 1 ] = v1.y;
  2449. a[ i + 2 ] = v1.z;
  2450. }
  2451. return a;
  2452. };
  2453. }(),
  2454. rotateAxis: function ( v ) {
  2455. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2456. v.transformDirection( this );
  2457. },
  2458. crossVector: function ( vector ) {
  2459. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2460. return vector.applyMatrix4( this );
  2461. },
  2462. determinant: function () {
  2463. var te = this.elements;
  2464. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2465. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2466. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2467. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2468. //TODO: make this more efficient
  2469. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2470. return (
  2471. n41 * (
  2472. +n14 * n23 * n32
  2473. -n13 * n24 * n32
  2474. -n14 * n22 * n33
  2475. +n12 * n24 * n33
  2476. +n13 * n22 * n34
  2477. -n12 * n23 * n34
  2478. ) +
  2479. n42 * (
  2480. +n11 * n23 * n34
  2481. -n11 * n24 * n33
  2482. +n14 * n21 * n33
  2483. -n13 * n21 * n34
  2484. +n13 * n24 * n31
  2485. -n14 * n23 * n31
  2486. ) +
  2487. n43 * (
  2488. +n11 * n24 * n32
  2489. -n11 * n22 * n34
  2490. -n14 * n21 * n32
  2491. +n12 * n21 * n34
  2492. +n14 * n22 * n31
  2493. -n12 * n24 * n31
  2494. ) +
  2495. n44 * (
  2496. -n13 * n22 * n31
  2497. -n11 * n23 * n32
  2498. +n11 * n22 * n33
  2499. +n13 * n21 * n32
  2500. -n12 * n21 * n33
  2501. +n12 * n23 * n31
  2502. )
  2503. );
  2504. },
  2505. transpose: function () {
  2506. var te = this.elements;
  2507. var tmp;
  2508. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2509. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2510. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2511. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2512. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2513. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2514. return this;
  2515. },
  2516. flattenToArray: function ( flat ) {
  2517. var te = this.elements;
  2518. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2519. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2520. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2521. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2522. return flat;
  2523. },
  2524. flattenToArrayOffset: function( flat, offset ) {
  2525. var te = this.elements;
  2526. flat[ offset ] = te[0];
  2527. flat[ offset + 1 ] = te[1];
  2528. flat[ offset + 2 ] = te[2];
  2529. flat[ offset + 3 ] = te[3];
  2530. flat[ offset + 4 ] = te[4];
  2531. flat[ offset + 5 ] = te[5];
  2532. flat[ offset + 6 ] = te[6];
  2533. flat[ offset + 7 ] = te[7];
  2534. flat[ offset + 8 ] = te[8];
  2535. flat[ offset + 9 ] = te[9];
  2536. flat[ offset + 10 ] = te[10];
  2537. flat[ offset + 11 ] = te[11];
  2538. flat[ offset + 12 ] = te[12];
  2539. flat[ offset + 13 ] = te[13];
  2540. flat[ offset + 14 ] = te[14];
  2541. flat[ offset + 15 ] = te[15];
  2542. return flat;
  2543. },
  2544. getPosition: function() {
  2545. var v1 = new THREE.Vector3();
  2546. return function () {
  2547. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2548. var te = this.elements;
  2549. return v1.set( te[12], te[13], te[14] );
  2550. };
  2551. }(),
  2552. setPosition: function ( v ) {
  2553. var te = this.elements;
  2554. te[12] = v.x;
  2555. te[13] = v.y;
  2556. te[14] = v.z;
  2557. return this;
  2558. },
  2559. getInverse: function ( m, throwOnInvertible ) {
  2560. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2561. var te = this.elements;
  2562. var me = m.elements;
  2563. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2564. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2565. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2566. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2567. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2568. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2569. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2570. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2571. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2572. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2573. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2574. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2575. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2576. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2577. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2578. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2579. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2580. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2581. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2582. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2583. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2584. if ( det == 0 ) {
  2585. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2586. if ( throwOnInvertible || false ) {
  2587. throw new Error( msg );
  2588. } else {
  2589. console.warn( msg );
  2590. }
  2591. this.identity();
  2592. return this;
  2593. }
  2594. this.multiplyScalar( 1 / det );
  2595. return this;
  2596. },
  2597. translate: function ( v ) {
  2598. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2599. },
  2600. rotateX: function ( angle ) {
  2601. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2602. },
  2603. rotateY: function ( angle ) {
  2604. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2605. },
  2606. rotateZ: function ( angle ) {
  2607. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2608. },
  2609. rotateByAxis: function ( axis, angle ) {
  2610. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2611. },
  2612. scale: function ( v ) {
  2613. var te = this.elements;
  2614. var x = v.x, y = v.y, z = v.z;
  2615. te[0] *= x; te[4] *= y; te[8] *= z;
  2616. te[1] *= x; te[5] *= y; te[9] *= z;
  2617. te[2] *= x; te[6] *= y; te[10] *= z;
  2618. te[3] *= x; te[7] *= y; te[11] *= z;
  2619. return this;
  2620. },
  2621. getMaxScaleOnAxis: function () {
  2622. var te = this.elements;
  2623. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2624. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2625. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2626. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2627. },
  2628. makeTranslation: function ( x, y, z ) {
  2629. this.set(
  2630. 1, 0, 0, x,
  2631. 0, 1, 0, y,
  2632. 0, 0, 1, z,
  2633. 0, 0, 0, 1
  2634. );
  2635. return this;
  2636. },
  2637. makeRotationX: function ( theta ) {
  2638. var c = Math.cos( theta ), s = Math.sin( theta );
  2639. this.set(
  2640. 1, 0, 0, 0,
  2641. 0, c, -s, 0,
  2642. 0, s, c, 0,
  2643. 0, 0, 0, 1
  2644. );
  2645. return this;
  2646. },
  2647. makeRotationY: function ( theta ) {
  2648. var c = Math.cos( theta ), s = Math.sin( theta );
  2649. this.set(
  2650. c, 0, s, 0,
  2651. 0, 1, 0, 0,
  2652. -s, 0, c, 0,
  2653. 0, 0, 0, 1
  2654. );
  2655. return this;
  2656. },
  2657. makeRotationZ: function ( theta ) {
  2658. var c = Math.cos( theta ), s = Math.sin( theta );
  2659. this.set(
  2660. c, -s, 0, 0,
  2661. s, c, 0, 0,
  2662. 0, 0, 1, 0,
  2663. 0, 0, 0, 1
  2664. );
  2665. return this;
  2666. },
  2667. makeRotationAxis: function ( axis, angle ) {
  2668. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2669. var c = Math.cos( angle );
  2670. var s = Math.sin( angle );
  2671. var t = 1 - c;
  2672. var x = axis.x, y = axis.y, z = axis.z;
  2673. var tx = t * x, ty = t * y;
  2674. this.set(
  2675. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2676. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2677. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2678. 0, 0, 0, 1
  2679. );
  2680. return this;
  2681. },
  2682. makeScale: function ( x, y, z ) {
  2683. this.set(
  2684. x, 0, 0, 0,
  2685. 0, y, 0, 0,
  2686. 0, 0, z, 0,
  2687. 0, 0, 0, 1
  2688. );
  2689. return this;
  2690. },
  2691. compose: function ( position, quaternion, scale ) {
  2692. console.warn( 'DEPRECATED: Matrix4\'s .compose() has been deprecated in favor of makeFromPositionQuaternionScale. Please update your code.' );
  2693. return this.makeFromPositionQuaternionScale( position, quaternion, scale );
  2694. },
  2695. makeFromPositionQuaternionScale: function ( position, quaternion, scale ) {
  2696. this.makeRotationFromQuaternion( quaternion );
  2697. this.scale( scale );
  2698. this.setPosition( position );
  2699. return this;
  2700. },
  2701. makeFromPositionEulerScale: function ( position, rotation, eulerOrder, scale ) {
  2702. this.makeRotationFromEuler( rotation, eulerOrder );
  2703. this.scale( scale );
  2704. this.setPosition( position );
  2705. return this;
  2706. },
  2707. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2708. var te = this.elements;
  2709. var x = 2 * near / ( right - left );
  2710. var y = 2 * near / ( top - bottom );
  2711. var a = ( right + left ) / ( right - left );
  2712. var b = ( top + bottom ) / ( top - bottom );
  2713. var c = - ( far + near ) / ( far - near );
  2714. var d = - 2 * far * near / ( far - near );
  2715. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2716. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2717. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2718. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2719. return this;
  2720. },
  2721. makePerspective: function ( fov, aspect, near, far ) {
  2722. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2723. var ymin = - ymax;
  2724. var xmin = ymin * aspect;
  2725. var xmax = ymax * aspect;
  2726. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2727. },
  2728. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2729. var te = this.elements;
  2730. var w = right - left;
  2731. var h = top - bottom;
  2732. var p = far - near;
  2733. var x = ( right + left ) / w;
  2734. var y = ( top + bottom ) / h;
  2735. var z = ( far + near ) / p;
  2736. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2737. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2738. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2739. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2740. return this;
  2741. },
  2742. clone: function () {
  2743. var te = this.elements;
  2744. return new THREE.Matrix4(
  2745. te[0], te[4], te[8], te[12],
  2746. te[1], te[5], te[9], te[13],
  2747. te[2], te[6], te[10], te[14],
  2748. te[3], te[7], te[11], te[15]
  2749. );
  2750. }
  2751. };
  2752. THREE.extend( THREE.Matrix4.prototype, {
  2753. decompose: function() {
  2754. var x = new THREE.Vector3();
  2755. var y = new THREE.Vector3();
  2756. var z = new THREE.Vector3();
  2757. var matrix = new THREE.Matrix4();
  2758. return function ( position, quaternion, scale ) {
  2759. var te = this.elements;
  2760. // grab the axis vectors
  2761. x.set( te[0], te[1], te[2] );
  2762. y.set( te[4], te[5], te[6] );
  2763. z.set( te[8], te[9], te[10] );
  2764. position = ( position instanceof THREE.Vector3 ) ? position : new THREE.Vector3();
  2765. quaternion = ( quaternion instanceof THREE.Quaternion ) ? quaternion : new THREE.Quaternion();
  2766. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2767. scale.x = x.length();
  2768. scale.y = y.length();
  2769. scale.z = z.length();
  2770. position.x = te[12];
  2771. position.y = te[13];
  2772. position.z = te[14];
  2773. // scale the rotation part
  2774. matrix.copy( this );
  2775. matrix.elements[0] /= scale.x;
  2776. matrix.elements[1] /= scale.x;
  2777. matrix.elements[2] /= scale.x;
  2778. matrix.elements[4] /= scale.y;
  2779. matrix.elements[5] /= scale.y;
  2780. matrix.elements[6] /= scale.y;
  2781. matrix.elements[8] /= scale.z;
  2782. matrix.elements[9] /= scale.z;
  2783. matrix.elements[10] /= scale.z;
  2784. quaternion.setFromRotationMatrix( matrix );
  2785. return [ position, quaternion, scale ];
  2786. };
  2787. }()
  2788. } );
  2789. /**
  2790. * @author bhouston / http://exocortex.com
  2791. */
  2792. THREE.Ray = function ( origin, direction ) {
  2793. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2794. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2795. };
  2796. THREE.Ray.prototype = {
  2797. constructor: THREE.Ray,
  2798. set: function ( origin, direction ) {
  2799. this.origin.copy( origin );
  2800. this.direction.copy( direction );
  2801. return this;
  2802. },
  2803. copy: function ( ray ) {
  2804. this.origin.copy( ray.origin );
  2805. this.direction.copy( ray.direction );
  2806. return this;
  2807. },
  2808. at: function( t, optionalTarget ) {
  2809. var result = optionalTarget || new THREE.Vector3();
  2810. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2811. },
  2812. recast: function() {
  2813. var v1 = new THREE.Vector3();
  2814. return function ( t ) {
  2815. this.origin.copy( this.at( t, v1 ) );
  2816. return this;
  2817. };
  2818. }(),
  2819. closestPointToPoint: function ( point, optionalTarget ) {
  2820. var result = optionalTarget || new THREE.Vector3();
  2821. result.subVectors( point, this.origin );
  2822. var directionDistance = result.dot( this.direction );
  2823. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2824. },
  2825. distanceToPoint: function() {
  2826. var v1 = new THREE.Vector3();
  2827. return function ( point ) {
  2828. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  2829. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2830. return v1.distanceTo( point );
  2831. };
  2832. }(),
  2833. isIntersectionSphere: function( sphere ) {
  2834. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2835. },
  2836. isIntersectionPlane: function ( plane ) {
  2837. // check if the line and plane are non-perpendicular, if they
  2838. // eventually they will intersect.
  2839. var denominator = plane.normal.dot( this.direction );
  2840. if ( denominator != 0 ) {
  2841. return true;
  2842. }
  2843. // line is coplanar, return origin
  2844. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2845. return true;
  2846. }
  2847. return false;
  2848. },
  2849. distanceToPlane: function ( plane ) {
  2850. var denominator = plane.normal.dot( this.direction );
  2851. if ( denominator == 0 ) {
  2852. // line is coplanar, return origin
  2853. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2854. return 0;
  2855. }
  2856. // Unsure if this is the correct method to handle this case.
  2857. return undefined;
  2858. }
  2859. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2860. return t;
  2861. },
  2862. intersectPlane: function ( plane, optionalTarget ) {
  2863. var t = this.distanceToPlane( plane );
  2864. if ( t === undefined ) {
  2865. return undefined;
  2866. }
  2867. return this.at( t, optionalTarget );
  2868. },
  2869. applyMatrix4: function ( matrix4 ) {
  2870. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2871. this.origin.applyMatrix4( matrix4 );
  2872. this.direction.sub( this.origin );
  2873. return this;
  2874. },
  2875. equals: function ( ray ) {
  2876. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2877. },
  2878. clone: function () {
  2879. return new THREE.Ray().copy( this );
  2880. }
  2881. };
  2882. /**
  2883. * @author bhouston / http://exocortex.com
  2884. * @author mrdoob / http://mrdoob.com/
  2885. */
  2886. THREE.Sphere = function ( center, radius ) {
  2887. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  2888. this.radius = ( radius !== undefined ) ? radius : 0;
  2889. };
  2890. THREE.Sphere.prototype = {
  2891. constructor: THREE.Sphere,
  2892. set: function ( center, radius ) {
  2893. this.center.copy( center );
  2894. this.radius = radius;
  2895. return this;
  2896. },
  2897. setFromCenterAndPoints: function ( center, points ) {
  2898. var maxRadiusSq = 0;
  2899. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2900. var radiusSq = center.distanceToSquared( points[ i ] );
  2901. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2902. }
  2903. this.center = center;
  2904. this.radius = Math.sqrt( maxRadiusSq );
  2905. return this;
  2906. },
  2907. copy: function ( sphere ) {
  2908. this.center.copy( sphere.center );
  2909. this.radius = sphere.radius;
  2910. return this;
  2911. },
  2912. empty: function () {
  2913. return ( this.radius <= 0 );
  2914. },
  2915. containsPoint: function ( point ) {
  2916. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2917. },
  2918. distanceToPoint: function ( point ) {
  2919. return ( point.distanceTo( this.center ) - this.radius );
  2920. },
  2921. intersectsSphere: function ( sphere ) {
  2922. var radiusSum = this.radius + sphere.radius;
  2923. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2924. },
  2925. clampPoint: function ( point, optionalTarget ) {
  2926. var deltaLengthSq = this.center.distanceToSquared( point );
  2927. var result = optionalTarget || new THREE.Vector3();
  2928. result.copy( point );
  2929. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2930. result.sub( this.center ).normalize();
  2931. result.multiplyScalar( this.radius ).add( this.center );
  2932. }
  2933. return result;
  2934. },
  2935. getBoundingBox: function ( optionalTarget ) {
  2936. var box = optionalTarget || new THREE.Box3();
  2937. box.set( this.center, this.center );
  2938. box.expandByScalar( this.radius );
  2939. return box;
  2940. },
  2941. applyMatrix4: function ( matrix ) {
  2942. this.center.applyMatrix4( matrix );
  2943. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2944. return this;
  2945. },
  2946. translate: function ( offset ) {
  2947. this.center.add( offset );
  2948. return this;
  2949. },
  2950. equals: function ( sphere ) {
  2951. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2952. },
  2953. clone: function () {
  2954. return new THREE.Sphere().copy( this );
  2955. }
  2956. };
  2957. /**
  2958. * @author mrdoob / http://mrdoob.com/
  2959. * @author alteredq / http://alteredqualia.com/
  2960. * @author bhouston / http://exocortex.com
  2961. */
  2962. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2963. this.planes = [
  2964. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2965. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2966. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2967. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2968. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2969. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2970. ];
  2971. };
  2972. THREE.Frustum.prototype = {
  2973. constructor: THREE.Frustum,
  2974. set: function ( p0, p1, p2, p3, p4, p5 ) {
  2975. var planes = this.planes;
  2976. planes[0].copy( p0 );
  2977. planes[1].copy( p1 );
  2978. planes[2].copy( p2 );
  2979. planes[3].copy( p3 );
  2980. planes[4].copy( p4 );
  2981. planes[5].copy( p5 );
  2982. return this;
  2983. },
  2984. copy: function ( frustum ) {
  2985. var planes = this.planes;
  2986. for( var i = 0; i < 6; i ++ ) {
  2987. planes[i].copy( frustum.planes[i] );
  2988. }
  2989. return this;
  2990. },
  2991. setFromMatrix: function ( m ) {
  2992. var planes = this.planes;
  2993. var me = m.elements;
  2994. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2995. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2996. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2997. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2998. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  2999. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3000. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3001. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3002. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3003. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3004. return this;
  3005. },
  3006. intersectsObject: function () {
  3007. var center = new THREE.Vector3();
  3008. return function ( object ) {
  3009. // this method is expanded inlined for performance reasons.
  3010. var matrix = object.matrixWorld;
  3011. var planes = this.planes;
  3012. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3013. center.getPositionFromMatrix( matrix );
  3014. for ( var i = 0; i < 6; i ++ ) {
  3015. var distance = planes[ i ].distanceToPoint( center );
  3016. if ( distance < negRadius ) {
  3017. return false;
  3018. }
  3019. }
  3020. return true;
  3021. };
  3022. }(),
  3023. intersectsSphere: function ( sphere ) {
  3024. var planes = this.planes;
  3025. var center = sphere.center;
  3026. var negRadius = -sphere.radius;
  3027. for ( var i = 0; i < 6; i ++ ) {
  3028. var distance = planes[ i ].distanceToPoint( center );
  3029. if ( distance < negRadius ) {
  3030. return false;
  3031. }
  3032. }
  3033. return true;
  3034. },
  3035. containsPoint: function ( point ) {
  3036. var planes = this.planes;
  3037. for ( var i = 0; i < 6; i ++ ) {
  3038. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3039. return false;
  3040. }
  3041. }
  3042. return true;
  3043. },
  3044. clone: function () {
  3045. return new THREE.Frustum().copy( this );
  3046. }
  3047. };
  3048. /**
  3049. * @author bhouston / http://exocortex.com
  3050. */
  3051. THREE.Plane = function ( normal, constant ) {
  3052. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3053. this.constant = ( constant !== undefined ) ? constant : 0;
  3054. };
  3055. THREE.Plane.prototype = {
  3056. constructor: THREE.Plane,
  3057. set: function ( normal, constant ) {
  3058. this.normal.copy( normal );
  3059. this.constant = constant;
  3060. return this;
  3061. },
  3062. setComponents: function ( x, y, z, w ) {
  3063. this.normal.set( x, y, z );
  3064. this.constant = w;
  3065. return this;
  3066. },
  3067. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3068. this.normal.copy( normal );
  3069. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3070. return this;
  3071. },
  3072. setFromCoplanarPoints: function() {
  3073. var v1 = new THREE.Vector3();
  3074. var v2 = new THREE.Vector3();
  3075. return function ( a, b, c ) {
  3076. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3077. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3078. this.setFromNormalAndCoplanarPoint( normal, a );
  3079. return this;
  3080. };
  3081. }(),
  3082. copy: function ( plane ) {
  3083. this.normal.copy( plane.normal );
  3084. this.constant = plane.constant;
  3085. return this;
  3086. },
  3087. normalize: function () {
  3088. // Note: will lead to a divide by zero if the plane is invalid.
  3089. var inverseNormalLength = 1.0 / this.normal.length();
  3090. this.normal.multiplyScalar( inverseNormalLength );
  3091. this.constant *= inverseNormalLength;
  3092. return this;
  3093. },
  3094. negate: function () {
  3095. this.constant *= -1;
  3096. this.normal.negate();
  3097. return this;
  3098. },
  3099. distanceToPoint: function ( point ) {
  3100. return this.normal.dot( point ) + this.constant;
  3101. },
  3102. distanceToSphere: function ( sphere ) {
  3103. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3104. },
  3105. projectPoint: function ( point, optionalTarget ) {
  3106. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3107. },
  3108. orthoPoint: function ( point, optionalTarget ) {
  3109. var perpendicularMagnitude = this.distanceToPoint( point );
  3110. var result = optionalTarget || new THREE.Vector3();
  3111. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3112. },
  3113. isIntersectionLine: function ( line ) {
  3114. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3115. var startSign = this.distanceToPoint( line.start );
  3116. var endSign = this.distanceToPoint( line.end );
  3117. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3118. },
  3119. intersectLine: function() {
  3120. var v1 = new THREE.Vector3();
  3121. return function ( line, optionalTarget ) {
  3122. var result = optionalTarget || new THREE.Vector3();
  3123. var direction = line.delta( v1 );
  3124. var denominator = this.normal.dot( direction );
  3125. if ( denominator == 0 ) {
  3126. // line is coplanar, return origin
  3127. if( this.distanceToPoint( line.start ) == 0 ) {
  3128. return result.copy( line.start );
  3129. }
  3130. // Unsure if this is the correct method to handle this case.
  3131. return undefined;
  3132. }
  3133. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3134. if( t < 0 || t > 1 ) {
  3135. return undefined;
  3136. }
  3137. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3138. };
  3139. }(),
  3140. coplanarPoint: function ( optionalTarget ) {
  3141. var result = optionalTarget || new THREE.Vector3();
  3142. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3143. },
  3144. applyMatrix4: function() {
  3145. var v1 = new THREE.Vector3();
  3146. var v2 = new THREE.Vector3();
  3147. return function ( matrix, optionalNormalMatrix ) {
  3148. // compute new normal based on theory here:
  3149. // http://www.songho.ca/opengl/gl_normaltransform.html
  3150. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3151. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3152. var newCoplanarPoint = this.coplanarPoint( v2 );
  3153. newCoplanarPoint.applyMatrix4( matrix );
  3154. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3155. return this;
  3156. };
  3157. }(),
  3158. translate: function ( offset ) {
  3159. this.constant = this.constant - offset.dot( this.normal );
  3160. return this;
  3161. },
  3162. equals: function ( plane ) {
  3163. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3164. },
  3165. clone: function () {
  3166. return new THREE.Plane().copy( this );
  3167. }
  3168. };
  3169. /**
  3170. * @author alteredq / http://alteredqualia.com/
  3171. */
  3172. THREE.Math = {
  3173. // Clamp value to range <a, b>
  3174. clamp: function ( x, a, b ) {
  3175. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3176. },
  3177. // Clamp value to range <a, inf)
  3178. clampBottom: function ( x, a ) {
  3179. return x < a ? a : x;
  3180. },
  3181. // Linear mapping from range <a1, a2> to range <b1, b2>
  3182. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3183. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3184. },
  3185. // http://en.wikipedia.org/wiki/Smoothstep
  3186. smoothstep: function ( x, min, max ) {
  3187. if ( x <= min ) return 0;
  3188. if ( x >= max ) return 1;
  3189. x = ( x - min )/( max - min );
  3190. return x*x*(3 - 2*x);
  3191. },
  3192. smootherstep: function ( x, min, max ) {
  3193. if ( x <= min ) return 0;
  3194. if ( x >= max ) return 1;
  3195. x = ( x - min )/( max - min );
  3196. return x*x*x*(x*(x*6 - 15) + 10);
  3197. },
  3198. // Random float from <0, 1> with 16 bits of randomness
  3199. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3200. random16: function () {
  3201. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3202. },
  3203. // Random integer from <low, high> interval
  3204. randInt: function ( low, high ) {
  3205. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3206. },
  3207. // Random float from <low, high> interval
  3208. randFloat: function ( low, high ) {
  3209. return low + Math.random() * ( high - low );
  3210. },
  3211. // Random float from <-range/2, range/2> interval
  3212. randFloatSpread: function ( range ) {
  3213. return range * ( 0.5 - Math.random() );
  3214. },
  3215. sign: function ( x ) {
  3216. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3217. },
  3218. degToRad: function() {
  3219. var degreeToRadiansFactor = Math.PI / 180;
  3220. return function ( degrees ) {
  3221. return degrees * degreeToRadiansFactor;
  3222. };
  3223. }(),
  3224. radToDeg: function() {
  3225. var radianToDegreesFactor = 180 / Math.PI;
  3226. return function ( radians ) {
  3227. return radians * radianToDegreesFactor;
  3228. };
  3229. }()
  3230. };
  3231. /**
  3232. * Spline from Tween.js, slightly optimized (and trashed)
  3233. * http://sole.github.com/tween.js/examples/05_spline.html
  3234. *
  3235. * @author mrdoob / http://mrdoob.com/
  3236. * @author alteredq / http://alteredqualia.com/
  3237. */
  3238. THREE.Spline = function ( points ) {
  3239. this.points = points;
  3240. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3241. point, intPoint, weight, w2, w3,
  3242. pa, pb, pc, pd;
  3243. this.initFromArray = function( a ) {
  3244. this.points = [];
  3245. for ( var i = 0; i < a.length; i++ ) {
  3246. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3247. }
  3248. };
  3249. this.getPoint = function ( k ) {
  3250. point = ( this.points.length - 1 ) * k;
  3251. intPoint = Math.floor( point );
  3252. weight = point - intPoint;
  3253. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3254. c[ 1 ] = intPoint;
  3255. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3256. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3257. pa = this.points[ c[ 0 ] ];
  3258. pb = this.points[ c[ 1 ] ];
  3259. pc = this.points[ c[ 2 ] ];
  3260. pd = this.points[ c[ 3 ] ];
  3261. w2 = weight * weight;
  3262. w3 = weight * w2;
  3263. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3264. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3265. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3266. return v3;
  3267. };
  3268. this.getControlPointsArray = function () {
  3269. var i, p, l = this.points.length,
  3270. coords = [];
  3271. for ( i = 0; i < l; i ++ ) {
  3272. p = this.points[ i ];
  3273. coords[ i ] = [ p.x, p.y, p.z ];
  3274. }
  3275. return coords;
  3276. };
  3277. // approximate length by summing linear segments
  3278. this.getLength = function ( nSubDivisions ) {
  3279. var i, index, nSamples, position,
  3280. point = 0, intPoint = 0, oldIntPoint = 0,
  3281. oldPosition = new THREE.Vector3(),
  3282. tmpVec = new THREE.Vector3(),
  3283. chunkLengths = [],
  3284. totalLength = 0;
  3285. // first point has 0 length
  3286. chunkLengths[ 0 ] = 0;
  3287. if ( !nSubDivisions ) nSubDivisions = 100;
  3288. nSamples = this.points.length * nSubDivisions;
  3289. oldPosition.copy( this.points[ 0 ] );
  3290. for ( i = 1; i < nSamples; i ++ ) {
  3291. index = i / nSamples;
  3292. position = this.getPoint( index );
  3293. tmpVec.copy( position );
  3294. totalLength += tmpVec.distanceTo( oldPosition );
  3295. oldPosition.copy( position );
  3296. point = ( this.points.length - 1 ) * index;
  3297. intPoint = Math.floor( point );
  3298. if ( intPoint != oldIntPoint ) {
  3299. chunkLengths[ intPoint ] = totalLength;
  3300. oldIntPoint = intPoint;
  3301. }
  3302. }
  3303. // last point ends with total length
  3304. chunkLengths[ chunkLengths.length ] = totalLength;
  3305. return { chunks: chunkLengths, total: totalLength };
  3306. };
  3307. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3308. var i, j,
  3309. index, indexCurrent, indexNext,
  3310. linearDistance, realDistance,
  3311. sampling, position,
  3312. newpoints = [],
  3313. tmpVec = new THREE.Vector3(),
  3314. sl = this.getLength();
  3315. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3316. for ( i = 1; i < this.points.length; i++ ) {
  3317. //tmpVec.copy( this.points[ i - 1 ] );
  3318. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3319. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3320. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3321. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3322. indexNext = i / ( this.points.length - 1 );
  3323. for ( j = 1; j < sampling - 1; j++ ) {
  3324. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3325. position = this.getPoint( index );
  3326. newpoints.push( tmpVec.copy( position ).clone() );
  3327. }
  3328. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3329. }
  3330. this.points = newpoints;
  3331. };
  3332. // Catmull-Rom
  3333. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3334. var v0 = ( p2 - p0 ) * 0.5,
  3335. v1 = ( p3 - p1 ) * 0.5;
  3336. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3337. };
  3338. };
  3339. /**
  3340. * @author bhouston / http://exocortex.com
  3341. * @author mrdoob / http://mrdoob.com/
  3342. */
  3343. THREE.Triangle = function ( a, b, c ) {
  3344. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3345. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3346. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3347. };
  3348. THREE.Triangle.normal = function() {
  3349. var v0 = new THREE.Vector3();
  3350. return function ( a, b, c, optionalTarget ) {
  3351. var result = optionalTarget || new THREE.Vector3();
  3352. result.subVectors( c, b );
  3353. v0.subVectors( a, b );
  3354. result.cross( v0 );
  3355. var resultLengthSq = result.lengthSq();
  3356. if( resultLengthSq > 0 ) {
  3357. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3358. }
  3359. return result.set( 0, 0, 0 );
  3360. };
  3361. }();
  3362. // static/instance method to calculate barycoordinates
  3363. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3364. THREE.Triangle.barycoordFromPoint = function() {
  3365. var v0 = new THREE.Vector3();
  3366. var v1 = new THREE.Vector3();
  3367. var v2 = new THREE.Vector3();
  3368. return function ( point, a, b, c, optionalTarget ) {
  3369. v0.subVectors( c, a );
  3370. v1.subVectors( b, a );
  3371. v2.subVectors( point, a );
  3372. var dot00 = v0.dot( v0 );
  3373. var dot01 = v0.dot( v1 );
  3374. var dot02 = v0.dot( v2 );
  3375. var dot11 = v1.dot( v1 );
  3376. var dot12 = v1.dot( v2 );
  3377. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3378. var result = optionalTarget || new THREE.Vector3();
  3379. // colinear or singular triangle
  3380. if( denom == 0 ) {
  3381. // arbitrary location outside of triangle?
  3382. // not sure if this is the best idea, maybe should be returning undefined
  3383. return result.set( -2, -1, -1 );
  3384. }
  3385. var invDenom = 1 / denom;
  3386. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3387. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3388. // barycoordinates must always sum to 1
  3389. return result.set( 1 - u - v, v, u );
  3390. };
  3391. }();
  3392. THREE.Triangle.containsPoint = function() {
  3393. var v1 = new THREE.Vector3();
  3394. return function ( point, a, b, c ) {
  3395. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3396. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3397. };
  3398. }();
  3399. THREE.Triangle.prototype = {
  3400. constructor: THREE.Triangle,
  3401. set: function ( a, b, c ) {
  3402. this.a.copy( a );
  3403. this.b.copy( b );
  3404. this.c.copy( c );
  3405. return this;
  3406. },
  3407. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3408. this.a.copy( points[i0] );
  3409. this.b.copy( points[i1] );
  3410. this.c.copy( points[i2] );
  3411. return this;
  3412. },
  3413. copy: function ( triangle ) {
  3414. this.a.copy( triangle.a );
  3415. this.b.copy( triangle.b );
  3416. this.c.copy( triangle.c );
  3417. return this;
  3418. },
  3419. area: function() {
  3420. var v0 = new THREE.Vector3();
  3421. var v1 = new THREE.Vector3();
  3422. return function () {
  3423. v0.subVectors( this.c, this.b );
  3424. v1.subVectors( this.a, this.b );
  3425. return v0.cross( v1 ).length() * 0.5;
  3426. };
  3427. }(),
  3428. midpoint: function ( optionalTarget ) {
  3429. var result = optionalTarget || new THREE.Vector3();
  3430. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3431. },
  3432. normal: function ( optionalTarget ) {
  3433. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3434. },
  3435. plane: function ( optionalTarget ) {
  3436. var result = optionalTarget || new THREE.Plane();
  3437. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3438. },
  3439. barycoordFromPoint: function ( point, optionalTarget ) {
  3440. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3441. },
  3442. containsPoint: function ( point ) {
  3443. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3444. },
  3445. equals: function ( triangle ) {
  3446. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3447. },
  3448. clone: function () {
  3449. return new THREE.Triangle().copy( this );
  3450. }
  3451. };
  3452. /**
  3453. * @author mrdoob / http://mrdoob.com/
  3454. */
  3455. THREE.Vertex = function ( v ) {
  3456. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3457. return v;
  3458. };
  3459. /**
  3460. * @author mrdoob / http://mrdoob.com/
  3461. */
  3462. THREE.UV = function ( u, v ) {
  3463. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3464. return new THREE.Vector2( u, v );
  3465. };
  3466. /**
  3467. * @author alteredq / http://alteredqualia.com/
  3468. */
  3469. THREE.Clock = function ( autoStart ) {
  3470. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3471. this.startTime = 0;
  3472. this.oldTime = 0;
  3473. this.elapsedTime = 0;
  3474. this.running = false;
  3475. };
  3476. THREE.Clock.prototype = {
  3477. constructor: THREE.Clock,
  3478. start: function () {
  3479. this.startTime = window.performance !== undefined && window.performance.now !== undefined
  3480. ? window.performance.now()
  3481. : Date.now();
  3482. this.oldTime = this.startTime;
  3483. this.running = true;
  3484. },
  3485. stop: function () {
  3486. this.getElapsedTime();
  3487. this.running = false;
  3488. },
  3489. getElapsedTime: function () {
  3490. this.getDelta();
  3491. return this.elapsedTime;
  3492. },
  3493. getDelta: function () {
  3494. var diff = 0;
  3495. if ( this.autoStart && ! this.running ) {
  3496. this.start();
  3497. }
  3498. if ( this.running ) {
  3499. var newTime = window.performance !== undefined && window.performance.now !== undefined
  3500. ? window.performance.now()
  3501. : Date.now();
  3502. diff = 0.001 * ( newTime - this.oldTime );
  3503. this.oldTime = newTime;
  3504. this.elapsedTime += diff;
  3505. }
  3506. return diff;
  3507. }
  3508. };
  3509. /**
  3510. * https://github.com/mrdoob/eventdispatcher.js/
  3511. */
  3512. THREE.EventDispatcher = function () {}
  3513. THREE.EventDispatcher.prototype = {
  3514. constructor: THREE.EventDispatcher,
  3515. addEventListener: function ( type, listener ) {
  3516. if ( this._listeners === undefined ) this._listeners = {};
  3517. var listeners = this._listeners;
  3518. if ( listeners[ type ] === undefined ) {
  3519. listeners[ type ] = [];
  3520. }
  3521. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3522. listeners[ type ].push( listener );
  3523. }
  3524. },
  3525. hasEventListener: function ( type, listener ) {
  3526. if ( this._listeners === undefined ) return false;
  3527. var listeners = this._listeners;
  3528. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3529. return true;
  3530. }
  3531. return false;
  3532. },
  3533. removeEventListener: function ( type, listener ) {
  3534. if ( this._listeners === undefined ) return;
  3535. var listeners = this._listeners;
  3536. var index = listeners[ type ].indexOf( listener );
  3537. if ( index !== - 1 ) {
  3538. listeners[ type ].splice( index, 1 );
  3539. }
  3540. },
  3541. dispatchEvent: function ( event ) {
  3542. if ( this._listeners === undefined ) return;
  3543. var listeners = this._listeners;
  3544. var listenerArray = listeners[ event.type ];
  3545. if ( listenerArray !== undefined ) {
  3546. event.target = this;
  3547. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3548. listenerArray[ i ].call( this, event );
  3549. }
  3550. }
  3551. }
  3552. };
  3553. /**
  3554. * @author mrdoob / http://mrdoob.com/
  3555. * @author bhouston / http://exocortex.com/
  3556. */
  3557. ( function ( THREE ) {
  3558. THREE.Raycaster = function ( origin, direction, near, far ) {
  3559. this.ray = new THREE.Ray( origin, direction );
  3560. // normalized ray.direction required for accurate distance calculations
  3561. if ( this.ray.direction.lengthSq() > 0 ) {
  3562. this.ray.direction.normalize();
  3563. }
  3564. this.near = near || 0;
  3565. this.far = far || Infinity;
  3566. };
  3567. var sphere = new THREE.Sphere();
  3568. var localRay = new THREE.Ray();
  3569. var facePlane = new THREE.Plane();
  3570. var intersectPoint = new THREE.Vector3();
  3571. var matrixPosition = new THREE.Vector3();
  3572. var inverseMatrix = new THREE.Matrix4();
  3573. var descSort = function ( a, b ) {
  3574. return a.distance - b.distance;
  3575. };
  3576. var intersectObject = function ( object, raycaster, intersects ) {
  3577. if ( object instanceof THREE.Particle ) {
  3578. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3579. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3580. if ( distance > object.scale.x ) {
  3581. return intersects;
  3582. }
  3583. intersects.push( {
  3584. distance: distance,
  3585. point: object.position,
  3586. face: null,
  3587. object: object
  3588. } );
  3589. } else if ( object instanceof THREE.LOD ) {
  3590. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3591. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  3592. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  3593. } else if ( object instanceof THREE.Mesh ) {
  3594. // Checking boundingSphere distance to ray
  3595. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3596. sphere.set(
  3597. matrixPosition,
  3598. object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3599. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3600. return intersects;
  3601. }
  3602. // Checking faces
  3603. var geometry = object.geometry;
  3604. var vertices = geometry.vertices;
  3605. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3606. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3607. var side = object.material.side;
  3608. var a, b, c, d;
  3609. var precision = raycaster.precision;
  3610. inverseMatrix.getInverse( object.matrixWorld );
  3611. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3612. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3613. var face = geometry.faces[ f ];
  3614. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3615. if ( material === undefined ) continue;
  3616. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3617. var planeDistance = localRay.distanceToPlane( facePlane );
  3618. // bail if raycaster and plane are parallel
  3619. if ( Math.abs( planeDistance ) < precision ) continue;
  3620. // if negative distance, then plane is behind raycaster
  3621. if ( planeDistance < 0 ) continue;
  3622. // check if we hit the wrong side of a single sided face
  3623. side = material.side;
  3624. if ( side !== THREE.DoubleSide ) {
  3625. var planeSign = localRay.direction.dot( facePlane.normal );
  3626. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3627. }
  3628. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3629. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3630. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3631. if ( face instanceof THREE.Face3 ) {
  3632. a = vertices[ face.a ];
  3633. b = vertices[ face.b ];
  3634. c = vertices[ face.c ];
  3635. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3636. } else if ( face instanceof THREE.Face4 ) {
  3637. a = vertices[ face.a ];
  3638. b = vertices[ face.b ];
  3639. c = vertices[ face.c ];
  3640. d = vertices[ face.d ];
  3641. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3642. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3643. } else {
  3644. // This is added because if we call out of this if/else group when none of the cases
  3645. // match it will add a point to the intersection list erroneously.
  3646. throw Error( "face type not supported" );
  3647. }
  3648. intersects.push( {
  3649. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3650. point: raycaster.ray.at( planeDistance ),
  3651. face: face,
  3652. faceIndex: f,
  3653. object: object
  3654. } );
  3655. }
  3656. }
  3657. };
  3658. var intersectDescendants = function ( object, raycaster, intersects ) {
  3659. var descendants = object.getDescendants();
  3660. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3661. intersectObject( descendants[ i ], raycaster, intersects );
  3662. }
  3663. };
  3664. //
  3665. THREE.Raycaster.prototype.precision = 0.0001;
  3666. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3667. this.ray.set( origin, direction );
  3668. // normalized ray.direction required for accurate distance calculations
  3669. if ( this.ray.direction.length() > 0 ) {
  3670. this.ray.direction.normalize();
  3671. }
  3672. };
  3673. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3674. var intersects = [];
  3675. if ( recursive === true ) {
  3676. intersectDescendants( object, this, intersects );
  3677. }
  3678. intersectObject( object, this, intersects );
  3679. intersects.sort( descSort );
  3680. return intersects;
  3681. };
  3682. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3683. var intersects = [];
  3684. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3685. intersectObject( objects[ i ], this, intersects );
  3686. if ( recursive === true ) {
  3687. intersectDescendants( objects[ i ], this, intersects );
  3688. }
  3689. }
  3690. intersects.sort( descSort );
  3691. return intersects;
  3692. };
  3693. }( THREE ) );
  3694. /**
  3695. * @author mrdoob / http://mrdoob.com/
  3696. * @author mikael emtinger / http://gomo.se/
  3697. * @author alteredq / http://alteredqualia.com/
  3698. * @author WestLangley / http://github.com/WestLangley
  3699. */
  3700. THREE.Object3D = function () {
  3701. this.id = THREE.Object3DIdCount ++;
  3702. this.name = '';
  3703. this.parent = undefined;
  3704. this.children = [];
  3705. this.up = new THREE.Vector3( 0, 1, 0 );
  3706. this.position = new THREE.Vector3();
  3707. this.rotation = new THREE.Vector3();
  3708. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3709. this.scale = new THREE.Vector3( 1, 1, 1 );
  3710. this.renderDepth = null;
  3711. this.rotationAutoUpdate = true;
  3712. this.matrix = new THREE.Matrix4();
  3713. this.matrixWorld = new THREE.Matrix4();
  3714. this.matrixAutoUpdate = true;
  3715. this.matrixWorldNeedsUpdate = true;
  3716. this.quaternion = new THREE.Quaternion();
  3717. this.useQuaternion = false;
  3718. this.visible = true;
  3719. this.castShadow = false;
  3720. this.receiveShadow = false;
  3721. this.frustumCulled = true;
  3722. this.userData = {};
  3723. };
  3724. THREE.Object3D.prototype = {
  3725. constructor: THREE.Object3D,
  3726. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  3727. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  3728. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  3729. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  3730. applyMatrix: function () {
  3731. var m1 = new THREE.Matrix4();
  3732. return function ( matrix ) {
  3733. this.matrix.multiplyMatrices( matrix, this.matrix );
  3734. this.position.getPositionFromMatrix( this.matrix );
  3735. this.scale.getScaleFromMatrix( this.matrix );
  3736. m1.extractRotation( this.matrix );
  3737. if ( this.useQuaternion === true ) {
  3738. this.quaternion.setFromRotationMatrix( m1 );
  3739. } else {
  3740. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3741. }
  3742. }
  3743. }(),
  3744. rotateOnAxis: function() {
  3745. // rotate object on axis in object space
  3746. // axis is assumed to be normalized
  3747. var q1 = new THREE.Quaternion();
  3748. var q2 = new THREE.Quaternion();
  3749. return function ( axis, angle ) {
  3750. q1.setFromAxisAngle( axis, angle );
  3751. if ( this.useQuaternion === true ) {
  3752. this.quaternion.multiply( q1 );
  3753. } else {
  3754. q2.setFromEuler( this.rotation, this.eulerOrder );
  3755. q2.multiply( q1 );
  3756. this.rotation.setEulerFromQuaternion( q2, this.eulerOrder );
  3757. }
  3758. return this;
  3759. }
  3760. }(),
  3761. translateOnAxis: function () {
  3762. // translate object by distance along axis in object space
  3763. // axis is assumed to be normalized
  3764. var v1 = new THREE.Vector3();
  3765. return function ( axis, distance ) {
  3766. v1.copy( axis );
  3767. if ( this.useQuaternion === true ) {
  3768. v1.applyQuaternion( this.quaternion );
  3769. } else {
  3770. v1.applyEuler( this.rotation, this.eulerOrder );
  3771. }
  3772. this.position.add( v1.multiplyScalar( distance ) );
  3773. return this;
  3774. }
  3775. }(),
  3776. translate: function ( distance, axis ) {
  3777. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  3778. return this.translateOnAxis( axis, distance );
  3779. },
  3780. translateX: function () {
  3781. var v1 = new THREE.Vector3( 1, 0, 0 );
  3782. return function ( distance ) {
  3783. return this.translateOnAxis( v1, distance );
  3784. };
  3785. }(),
  3786. translateY: function () {
  3787. var v1 = new THREE.Vector3( 0, 1, 0 );
  3788. return function ( distance ) {
  3789. return this.translateOnAxis( v1, distance );
  3790. };
  3791. }(),
  3792. translateZ: function () {
  3793. var v1 = new THREE.Vector3( 0, 0, 1 );
  3794. return function ( distance ) {
  3795. return this.translateOnAxis( v1, distance );
  3796. };
  3797. }(),
  3798. localToWorld: function ( vector ) {
  3799. return vector.applyMatrix4( this.matrixWorld );
  3800. },
  3801. worldToLocal: function () {
  3802. var m1 = new THREE.Matrix4();
  3803. return function ( vector ) {
  3804. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  3805. };
  3806. }(),
  3807. lookAt: function () {
  3808. // This routine does not support objects with rotated and/or translated parent(s)
  3809. var m1 = new THREE.Matrix4();
  3810. return function ( vector ) {
  3811. m1.lookAt( vector, this.position, this.up );
  3812. if ( this.useQuaternion === true ) {
  3813. this.quaternion.setFromRotationMatrix( m1 );
  3814. } else {
  3815. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3816. }
  3817. };
  3818. }(),
  3819. add: function ( object ) {
  3820. if ( object === this ) {
  3821. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3822. return;
  3823. }
  3824. if ( object instanceof THREE.Object3D ) {
  3825. if ( object.parent !== undefined ) {
  3826. object.parent.remove( object );
  3827. }
  3828. object.parent = this;
  3829. this.children.push( object );
  3830. // add to scene
  3831. var scene = this;
  3832. while ( scene.parent !== undefined ) {
  3833. scene = scene.parent;
  3834. }
  3835. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3836. scene.__addObject( object );
  3837. }
  3838. }
  3839. },
  3840. remove: function ( object ) {
  3841. var index = this.children.indexOf( object );
  3842. if ( index !== - 1 ) {
  3843. object.parent = undefined;
  3844. this.children.splice( index, 1 );
  3845. // remove from scene
  3846. var scene = this;
  3847. while ( scene.parent !== undefined ) {
  3848. scene = scene.parent;
  3849. }
  3850. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3851. scene.__removeObject( object );
  3852. }
  3853. }
  3854. },
  3855. traverse: function ( callback ) {
  3856. callback( this );
  3857. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3858. this.children[ i ].traverse( callback );
  3859. }
  3860. },
  3861. getObjectById: function ( id, recursive ) {
  3862. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3863. var child = this.children[ i ];
  3864. if ( child.id === id ) {
  3865. return child;
  3866. }
  3867. if ( recursive === true ) {
  3868. child = child.getObjectById( id, recursive );
  3869. if ( child !== undefined ) {
  3870. return child;
  3871. }
  3872. }
  3873. }
  3874. return undefined;
  3875. },
  3876. getObjectByName: function ( name, recursive ) {
  3877. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3878. var child = this.children[ i ];
  3879. if ( child.name === name ) {
  3880. return child;
  3881. }
  3882. if ( recursive === true ) {
  3883. child = child.getObjectByName( name, recursive );
  3884. if ( child !== undefined ) {
  3885. return child;
  3886. }
  3887. }
  3888. }
  3889. return undefined;
  3890. },
  3891. getChildByName: function ( name, recursive ) {
  3892. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  3893. return this.getObjectByName( name, recursive );
  3894. },
  3895. getDescendants: function ( array ) {
  3896. if ( array === undefined ) array = [];
  3897. Array.prototype.push.apply( array, this.children );
  3898. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3899. this.children[ i ].getDescendants( array );
  3900. }
  3901. return array;
  3902. },
  3903. updateMatrix: function () {
  3904. // if we are not using a quaternion directly, convert Euler rotation to this.quaternion.
  3905. if ( this.useQuaternion === false ) {
  3906. this.matrix.makeFromPositionEulerScale( this.position, this.rotation, this.eulerOrder, this.scale );
  3907. } else {
  3908. this.matrix.makeFromPositionQuaternionScale( this.position, this.quaternion, this.scale );
  3909. }
  3910. this.matrixWorldNeedsUpdate = true;
  3911. },
  3912. updateMatrixWorld: function ( force ) {
  3913. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3914. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3915. if ( this.parent === undefined ) {
  3916. this.matrixWorld.copy( this.matrix );
  3917. } else {
  3918. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3919. }
  3920. this.matrixWorldNeedsUpdate = false;
  3921. force = true;
  3922. }
  3923. // update children
  3924. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3925. this.children[ i ].updateMatrixWorld( force );
  3926. }
  3927. },
  3928. clone: function ( object ) {
  3929. if ( object === undefined ) object = new THREE.Object3D();
  3930. object.name = this.name;
  3931. object.up.copy( this.up );
  3932. object.position.copy( this.position );
  3933. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3934. object.eulerOrder = this.eulerOrder;
  3935. object.scale.copy( this.scale );
  3936. object.renderDepth = this.renderDepth;
  3937. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3938. object.matrix.copy( this.matrix );
  3939. object.matrixWorld.copy( this.matrixWorld );
  3940. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3941. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3942. object.quaternion.copy( this.quaternion );
  3943. object.useQuaternion = this.useQuaternion;
  3944. object.visible = this.visible;
  3945. object.castShadow = this.castShadow;
  3946. object.receiveShadow = this.receiveShadow;
  3947. object.frustumCulled = this.frustumCulled;
  3948. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  3949. for ( var i = 0; i < this.children.length; i ++ ) {
  3950. var child = this.children[ i ];
  3951. object.add( child.clone() );
  3952. }
  3953. return object;
  3954. }
  3955. };
  3956. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3957. THREE.Object3DIdCount = 0;
  3958. /**
  3959. * @author mrdoob / http://mrdoob.com/
  3960. * @author supereggbert / http://www.paulbrunt.co.uk/
  3961. * @author julianwa / https://github.com/julianwa
  3962. */
  3963. THREE.Projector = function () {
  3964. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3965. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3966. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3967. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3968. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3969. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3970. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3971. _vector3 = new THREE.Vector3(),
  3972. _vector4 = new THREE.Vector4(),
  3973. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  3974. _boundingBox = new THREE.Box3(),
  3975. _points3 = new Array( 3 ),
  3976. _points4 = new Array( 4 ),
  3977. _viewMatrix = new THREE.Matrix4(),
  3978. _viewProjectionMatrix = new THREE.Matrix4(),
  3979. _modelMatrix,
  3980. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3981. _normalMatrix = new THREE.Matrix3(),
  3982. _normalViewMatrix = new THREE.Matrix3(),
  3983. _centroid = new THREE.Vector3(),
  3984. _frustum = new THREE.Frustum(),
  3985. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3986. _clippedVertex2PositionScreen = new THREE.Vector4();
  3987. this.projectVector = function ( vector, camera ) {
  3988. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3989. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3990. return vector.applyProjection( _viewProjectionMatrix );
  3991. };
  3992. this.unprojectVector = function ( vector, camera ) {
  3993. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3994. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3995. return vector.applyProjection( _viewProjectionMatrix );
  3996. };
  3997. this.pickingRay = function ( vector, camera ) {
  3998. // set two vectors with opposing z values
  3999. vector.z = -1.0;
  4000. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4001. this.unprojectVector( vector, camera );
  4002. this.unprojectVector( end, camera );
  4003. // find direction from vector to end
  4004. end.sub( vector ).normalize();
  4005. return new THREE.Raycaster( vector, end );
  4006. };
  4007. var projectGraph = function ( root, sortObjects ) {
  4008. _objectCount = 0;
  4009. _renderData.objects.length = 0;
  4010. _renderData.sprites.length = 0;
  4011. _renderData.lights.length = 0;
  4012. var projectObject = function ( parent ) {
  4013. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  4014. var object = parent.children[ c ];
  4015. if ( object.visible === false ) continue;
  4016. if ( object instanceof THREE.Light ) {
  4017. _renderData.lights.push( object );
  4018. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4019. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4020. _object = getNextObjectInPool();
  4021. _object.object = object;
  4022. if ( object.renderDepth !== null ) {
  4023. _object.z = object.renderDepth;
  4024. } else {
  4025. _vector3.getPositionFromMatrix( object.matrixWorld );
  4026. _vector3.applyProjection( _viewProjectionMatrix );
  4027. _object.z = _vector3.z;
  4028. }
  4029. _renderData.objects.push( _object );
  4030. }
  4031. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  4032. _object = getNextObjectInPool();
  4033. _object.object = object;
  4034. // TODO: Find an elegant and performant solution and remove this dupe code.
  4035. if ( object.renderDepth !== null ) {
  4036. _object.z = object.renderDepth;
  4037. } else {
  4038. _vector3.getPositionFromMatrix( object.matrixWorld );
  4039. _vector3.applyProjection( _viewProjectionMatrix );
  4040. _object.z = _vector3.z;
  4041. }
  4042. _renderData.sprites.push( _object );
  4043. } else {
  4044. _object = getNextObjectInPool();
  4045. _object.object = object;
  4046. if ( object.renderDepth !== null ) {
  4047. _object.z = object.renderDepth;
  4048. } else {
  4049. _vector3.getPositionFromMatrix( object.matrixWorld );
  4050. _vector3.applyProjection( _viewProjectionMatrix );
  4051. _object.z = _vector3.z;
  4052. }
  4053. _renderData.objects.push( _object );
  4054. }
  4055. projectObject( object );
  4056. }
  4057. };
  4058. projectObject( root );
  4059. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  4060. return _renderData;
  4061. };
  4062. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4063. var visible = false,
  4064. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4065. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4066. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4067. _face3Count = 0;
  4068. _face4Count = 0;
  4069. _lineCount = 0;
  4070. _particleCount = 0;
  4071. _renderData.elements.length = 0;
  4072. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4073. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4074. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4075. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4076. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4077. _frustum.setFromMatrix( _viewProjectionMatrix );
  4078. _renderData = projectGraph( scene, sortObjects );
  4079. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4080. object = _renderData.objects[ o ].object;
  4081. _modelMatrix = object.matrixWorld;
  4082. _vertexCount = 0;
  4083. if ( object instanceof THREE.Mesh ) {
  4084. geometry = object.geometry;
  4085. vertices = geometry.vertices;
  4086. faces = geometry.faces;
  4087. faceVertexUvs = geometry.faceVertexUvs;
  4088. _normalMatrix.getNormalMatrix( _modelMatrix );
  4089. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4090. objectMaterials = isFaceMaterial === true ? object.material : null;
  4091. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4092. _vertex = getNextVertexInPool();
  4093. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4094. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4095. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4096. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4097. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4098. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4099. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4100. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4101. }
  4102. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4103. face = faces[ f ];
  4104. var material = isFaceMaterial === true
  4105. ? objectMaterials.materials[ face.materialIndex ]
  4106. : object.material;
  4107. if ( material === undefined ) continue;
  4108. var side = material.side;
  4109. if ( face instanceof THREE.Face3 ) {
  4110. v1 = _vertexPool[ face.a ];
  4111. v2 = _vertexPool[ face.b ];
  4112. v3 = _vertexPool[ face.c ];
  4113. _points3[ 0 ] = v1.positionScreen;
  4114. _points3[ 1 ] = v2.positionScreen;
  4115. _points3[ 2 ] = v3.positionScreen;
  4116. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4117. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4118. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4119. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4120. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4121. _face = getNextFace3InPool();
  4122. _face.v1.copy( v1 );
  4123. _face.v2.copy( v2 );
  4124. _face.v3.copy( v3 );
  4125. } else {
  4126. continue;
  4127. }
  4128. } else {
  4129. continue;
  4130. }
  4131. } else if ( face instanceof THREE.Face4 ) {
  4132. v1 = _vertexPool[ face.a ];
  4133. v2 = _vertexPool[ face.b ];
  4134. v3 = _vertexPool[ face.c ];
  4135. v4 = _vertexPool[ face.d ];
  4136. _points4[ 0 ] = v1.positionScreen;
  4137. _points4[ 1 ] = v2.positionScreen;
  4138. _points4[ 2 ] = v3.positionScreen;
  4139. _points4[ 3 ] = v4.positionScreen;
  4140. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4141. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4142. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4143. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4144. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4145. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4146. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4147. _face = getNextFace4InPool();
  4148. _face.v1.copy( v1 );
  4149. _face.v2.copy( v2 );
  4150. _face.v3.copy( v3 );
  4151. _face.v4.copy( v4 );
  4152. } else {
  4153. continue;
  4154. }
  4155. } else {
  4156. continue;
  4157. }
  4158. }
  4159. _face.normalModel.copy( face.normal );
  4160. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4161. _face.normalModel.negate();
  4162. }
  4163. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4164. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4165. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4166. faceVertexNormals = face.vertexNormals;
  4167. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4168. var normalModel = _face.vertexNormalsModel[ n ];
  4169. normalModel.copy( faceVertexNormals[ n ] );
  4170. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4171. normalModel.negate();
  4172. }
  4173. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4174. var normalModelView = _face.vertexNormalsModelView[ n ];
  4175. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4176. }
  4177. _face.vertexNormalsLength = faceVertexNormals.length;
  4178. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4179. uvs = faceVertexUvs[ c ][ f ];
  4180. if ( uvs === undefined ) continue;
  4181. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4182. _face.uvs[ c ][ u ] = uvs[ u ];
  4183. }
  4184. }
  4185. _face.color = face.color;
  4186. _face.material = material;
  4187. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4188. _face.z = _centroid.z;
  4189. _renderData.elements.push( _face );
  4190. }
  4191. } else if ( object instanceof THREE.Line ) {
  4192. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4193. vertices = object.geometry.vertices;
  4194. v1 = getNextVertexInPool();
  4195. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4196. // Handle LineStrip and LinePieces
  4197. var step = object.type === THREE.LinePieces ? 2 : 1;
  4198. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4199. v1 = getNextVertexInPool();
  4200. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4201. if ( ( v + 1 ) % step > 0 ) continue;
  4202. v2 = _vertexPool[ _vertexCount - 2 ];
  4203. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4204. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4205. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4206. // Perform the perspective divide
  4207. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4208. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4209. _line = getNextLineInPool();
  4210. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4211. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4212. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4213. _line.material = object.material;
  4214. if ( object.material.vertexColors === THREE.VertexColors ) {
  4215. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4216. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4217. }
  4218. _renderData.elements.push( _line );
  4219. }
  4220. }
  4221. }
  4222. }
  4223. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4224. object = _renderData.sprites[ o ].object;
  4225. _modelMatrix = object.matrixWorld;
  4226. if ( object instanceof THREE.Particle ) {
  4227. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4228. _vector4.applyMatrix4( _viewProjectionMatrix );
  4229. _vector4.z /= _vector4.w;
  4230. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4231. _particle = getNextParticleInPool();
  4232. _particle.object = object;
  4233. _particle.x = _vector4.x / _vector4.w;
  4234. _particle.y = _vector4.y / _vector4.w;
  4235. _particle.z = _vector4.z;
  4236. _particle.rotation = object.rotation.z;
  4237. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4238. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4239. _particle.material = object.material;
  4240. _renderData.elements.push( _particle );
  4241. }
  4242. }
  4243. }
  4244. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4245. return _renderData;
  4246. };
  4247. // Pools
  4248. function getNextObjectInPool() {
  4249. if ( _objectCount === _objectPoolLength ) {
  4250. var object = new THREE.RenderableObject();
  4251. _objectPool.push( object );
  4252. _objectPoolLength ++;
  4253. _objectCount ++;
  4254. return object;
  4255. }
  4256. return _objectPool[ _objectCount ++ ];
  4257. }
  4258. function getNextVertexInPool() {
  4259. if ( _vertexCount === _vertexPoolLength ) {
  4260. var vertex = new THREE.RenderableVertex();
  4261. _vertexPool.push( vertex );
  4262. _vertexPoolLength ++;
  4263. _vertexCount ++;
  4264. return vertex;
  4265. }
  4266. return _vertexPool[ _vertexCount ++ ];
  4267. }
  4268. function getNextFace3InPool() {
  4269. if ( _face3Count === _face3PoolLength ) {
  4270. var face = new THREE.RenderableFace3();
  4271. _face3Pool.push( face );
  4272. _face3PoolLength ++;
  4273. _face3Count ++;
  4274. return face;
  4275. }
  4276. return _face3Pool[ _face3Count ++ ];
  4277. }
  4278. function getNextFace4InPool() {
  4279. if ( _face4Count === _face4PoolLength ) {
  4280. var face = new THREE.RenderableFace4();
  4281. _face4Pool.push( face );
  4282. _face4PoolLength ++;
  4283. _face4Count ++;
  4284. return face;
  4285. }
  4286. return _face4Pool[ _face4Count ++ ];
  4287. }
  4288. function getNextLineInPool() {
  4289. if ( _lineCount === _linePoolLength ) {
  4290. var line = new THREE.RenderableLine();
  4291. _linePool.push( line );
  4292. _linePoolLength ++;
  4293. _lineCount ++
  4294. return line;
  4295. }
  4296. return _linePool[ _lineCount ++ ];
  4297. }
  4298. function getNextParticleInPool() {
  4299. if ( _particleCount === _particlePoolLength ) {
  4300. var particle = new THREE.RenderableParticle();
  4301. _particlePool.push( particle );
  4302. _particlePoolLength ++;
  4303. _particleCount ++
  4304. return particle;
  4305. }
  4306. return _particlePool[ _particleCount ++ ];
  4307. }
  4308. //
  4309. function painterSort( a, b ) {
  4310. return b.z - a.z;
  4311. }
  4312. function clipLine( s1, s2 ) {
  4313. var alpha1 = 0, alpha2 = 1,
  4314. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4315. // Z = -1 and Z = +1, respectively.
  4316. bc1near = s1.z + s1.w,
  4317. bc2near = s2.z + s2.w,
  4318. bc1far = - s1.z + s1.w,
  4319. bc2far = - s2.z + s2.w;
  4320. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4321. // Both vertices lie entirely within all clip planes.
  4322. return true;
  4323. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4324. // Both vertices lie entirely outside one of the clip planes.
  4325. return false;
  4326. } else {
  4327. // The line segment spans at least one clip plane.
  4328. if ( bc1near < 0 ) {
  4329. // v1 lies outside the near plane, v2 inside
  4330. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4331. } else if ( bc2near < 0 ) {
  4332. // v2 lies outside the near plane, v1 inside
  4333. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4334. }
  4335. if ( bc1far < 0 ) {
  4336. // v1 lies outside the far plane, v2 inside
  4337. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4338. } else if ( bc2far < 0 ) {
  4339. // v2 lies outside the far plane, v2 inside
  4340. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4341. }
  4342. if ( alpha2 < alpha1 ) {
  4343. // The line segment spans two boundaries, but is outside both of them.
  4344. // (This can't happen when we're only clipping against just near/far but good
  4345. // to leave the check here for future usage if other clip planes are added.)
  4346. return false;
  4347. } else {
  4348. // Update the s1 and s2 vertices to match the clipped line segment.
  4349. s1.lerp( s2, alpha1 );
  4350. s2.lerp( s1, 1 - alpha2 );
  4351. return true;
  4352. }
  4353. }
  4354. }
  4355. };
  4356. /**
  4357. * @author mrdoob / http://mrdoob.com/
  4358. * @author alteredq / http://alteredqualia.com/
  4359. */
  4360. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4361. this.a = a;
  4362. this.b = b;
  4363. this.c = c;
  4364. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4365. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4366. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4367. this.vertexColors = color instanceof Array ? color : [];
  4368. this.vertexTangents = [];
  4369. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4370. this.centroid = new THREE.Vector3();
  4371. };
  4372. THREE.Face3.prototype = {
  4373. constructor: THREE.Face3,
  4374. clone: function () {
  4375. var face = new THREE.Face3( this.a, this.b, this.c );
  4376. face.normal.copy( this.normal );
  4377. face.color.copy( this.color );
  4378. face.centroid.copy( this.centroid );
  4379. face.materialIndex = this.materialIndex;
  4380. var i, il;
  4381. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4382. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4383. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4384. return face;
  4385. }
  4386. };
  4387. /**
  4388. * @author mrdoob / http://mrdoob.com/
  4389. * @author alteredq / http://alteredqualia.com/
  4390. */
  4391. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4392. this.a = a;
  4393. this.b = b;
  4394. this.c = c;
  4395. this.d = d;
  4396. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4397. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4398. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4399. this.vertexColors = color instanceof Array ? color : [];
  4400. this.vertexTangents = [];
  4401. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4402. this.centroid = new THREE.Vector3();
  4403. };
  4404. THREE.Face4.prototype = {
  4405. constructor: THREE.Face4,
  4406. clone: function () {
  4407. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4408. face.normal.copy( this.normal );
  4409. face.color.copy( this.color );
  4410. face.centroid.copy( this.centroid );
  4411. face.materialIndex = this.materialIndex;
  4412. var i, il;
  4413. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4414. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4415. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4416. return face;
  4417. }
  4418. };
  4419. /**
  4420. * @author mrdoob / http://mrdoob.com/
  4421. * @author kile / http://kile.stravaganza.org/
  4422. * @author alteredq / http://alteredqualia.com/
  4423. * @author mikael emtinger / http://gomo.se/
  4424. * @author zz85 / http://www.lab4games.net/zz85/blog
  4425. * @author bhouston / http://exocortex.com
  4426. */
  4427. THREE.Geometry = function () {
  4428. this.id = THREE.GeometryIdCount ++;
  4429. this.name = '';
  4430. this.vertices = [];
  4431. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4432. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4433. this.faces = [];
  4434. this.faceUvs = [[]];
  4435. this.faceVertexUvs = [[]];
  4436. this.morphTargets = [];
  4437. this.morphColors = [];
  4438. this.morphNormals = [];
  4439. this.skinWeights = [];
  4440. this.skinIndices = [];
  4441. this.lineDistances = [];
  4442. this.boundingBox = null;
  4443. this.boundingSphere = null;
  4444. this.hasTangents = false;
  4445. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4446. // update flags
  4447. this.verticesNeedUpdate = false;
  4448. this.elementsNeedUpdate = false;
  4449. this.uvsNeedUpdate = false;
  4450. this.normalsNeedUpdate = false;
  4451. this.tangentsNeedUpdate = false;
  4452. this.colorsNeedUpdate = false;
  4453. this.lineDistancesNeedUpdate = false;
  4454. this.buffersNeedUpdate = false;
  4455. };
  4456. THREE.Geometry.prototype = {
  4457. constructor: THREE.Geometry,
  4458. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4459. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4460. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4461. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4462. applyMatrix: function ( matrix ) {
  4463. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4464. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4465. var vertex = this.vertices[ i ];
  4466. vertex.applyMatrix4( matrix );
  4467. }
  4468. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4469. var face = this.faces[ i ];
  4470. face.normal.applyMatrix3( normalMatrix ).normalize();
  4471. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4472. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4473. }
  4474. face.centroid.applyMatrix4( matrix );
  4475. }
  4476. },
  4477. computeCentroids: function () {
  4478. var f, fl, face;
  4479. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4480. face = this.faces[ f ];
  4481. face.centroid.set( 0, 0, 0 );
  4482. if ( face instanceof THREE.Face3 ) {
  4483. face.centroid.add( this.vertices[ face.a ] );
  4484. face.centroid.add( this.vertices[ face.b ] );
  4485. face.centroid.add( this.vertices[ face.c ] );
  4486. face.centroid.divideScalar( 3 );
  4487. } else if ( face instanceof THREE.Face4 ) {
  4488. face.centroid.add( this.vertices[ face.a ] );
  4489. face.centroid.add( this.vertices[ face.b ] );
  4490. face.centroid.add( this.vertices[ face.c ] );
  4491. face.centroid.add( this.vertices[ face.d ] );
  4492. face.centroid.divideScalar( 4 );
  4493. }
  4494. }
  4495. },
  4496. computeFaceNormals: function () {
  4497. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4498. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4499. var face = this.faces[ f ];
  4500. var vA = this.vertices[ face.a ];
  4501. var vB = this.vertices[ face.b ];
  4502. var vC = this.vertices[ face.c ];
  4503. cb.subVectors( vC, vB );
  4504. ab.subVectors( vA, vB );
  4505. cb.cross( ab );
  4506. cb.normalize();
  4507. face.normal.copy( cb );
  4508. }
  4509. },
  4510. computeVertexNormals: function ( areaWeighted ) {
  4511. var v, vl, f, fl, face, vertices;
  4512. // create internal buffers for reuse when calling this method repeatedly
  4513. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4514. if ( this.__tmpVertices === undefined ) {
  4515. this.__tmpVertices = new Array( this.vertices.length );
  4516. vertices = this.__tmpVertices;
  4517. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4518. vertices[ v ] = new THREE.Vector3();
  4519. }
  4520. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4521. face = this.faces[ f ];
  4522. if ( face instanceof THREE.Face3 ) {
  4523. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4524. } else if ( face instanceof THREE.Face4 ) {
  4525. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4526. }
  4527. }
  4528. } else {
  4529. vertices = this.__tmpVertices;
  4530. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4531. vertices[ v ].set( 0, 0, 0 );
  4532. }
  4533. }
  4534. if ( areaWeighted ) {
  4535. // vertex normals weighted by triangle areas
  4536. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4537. var vA, vB, vC, vD;
  4538. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4539. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4540. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4541. face = this.faces[ f ];
  4542. if ( face instanceof THREE.Face3 ) {
  4543. vA = this.vertices[ face.a ];
  4544. vB = this.vertices[ face.b ];
  4545. vC = this.vertices[ face.c ];
  4546. cb.subVectors( vC, vB );
  4547. ab.subVectors( vA, vB );
  4548. cb.cross( ab );
  4549. vertices[ face.a ].add( cb );
  4550. vertices[ face.b ].add( cb );
  4551. vertices[ face.c ].add( cb );
  4552. } else if ( face instanceof THREE.Face4 ) {
  4553. vA = this.vertices[ face.a ];
  4554. vB = this.vertices[ face.b ];
  4555. vC = this.vertices[ face.c ];
  4556. vD = this.vertices[ face.d ];
  4557. // abd
  4558. db.subVectors( vD, vB );
  4559. ab.subVectors( vA, vB );
  4560. db.cross( ab );
  4561. vertices[ face.a ].add( db );
  4562. vertices[ face.b ].add( db );
  4563. vertices[ face.d ].add( db );
  4564. // bcd
  4565. dc.subVectors( vD, vC );
  4566. bc.subVectors( vB, vC );
  4567. dc.cross( bc );
  4568. vertices[ face.b ].add( dc );
  4569. vertices[ face.c ].add( dc );
  4570. vertices[ face.d ].add( dc );
  4571. }
  4572. }
  4573. } else {
  4574. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4575. face = this.faces[ f ];
  4576. if ( face instanceof THREE.Face3 ) {
  4577. vertices[ face.a ].add( face.normal );
  4578. vertices[ face.b ].add( face.normal );
  4579. vertices[ face.c ].add( face.normal );
  4580. } else if ( face instanceof THREE.Face4 ) {
  4581. vertices[ face.a ].add( face.normal );
  4582. vertices[ face.b ].add( face.normal );
  4583. vertices[ face.c ].add( face.normal );
  4584. vertices[ face.d ].add( face.normal );
  4585. }
  4586. }
  4587. }
  4588. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4589. vertices[ v ].normalize();
  4590. }
  4591. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4592. face = this.faces[ f ];
  4593. if ( face instanceof THREE.Face3 ) {
  4594. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4595. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4596. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4597. } else if ( face instanceof THREE.Face4 ) {
  4598. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4599. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4600. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4601. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4602. }
  4603. }
  4604. },
  4605. computeMorphNormals: function () {
  4606. var i, il, f, fl, face;
  4607. // save original normals
  4608. // - create temp variables on first access
  4609. // otherwise just copy (for faster repeated calls)
  4610. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4611. face = this.faces[ f ];
  4612. if ( ! face.__originalFaceNormal ) {
  4613. face.__originalFaceNormal = face.normal.clone();
  4614. } else {
  4615. face.__originalFaceNormal.copy( face.normal );
  4616. }
  4617. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4618. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4619. if ( ! face.__originalVertexNormals[ i ] ) {
  4620. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4621. } else {
  4622. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4623. }
  4624. }
  4625. }
  4626. // use temp geometry to compute face and vertex normals for each morph
  4627. var tmpGeo = new THREE.Geometry();
  4628. tmpGeo.faces = this.faces;
  4629. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4630. // create on first access
  4631. if ( ! this.morphNormals[ i ] ) {
  4632. this.morphNormals[ i ] = {};
  4633. this.morphNormals[ i ].faceNormals = [];
  4634. this.morphNormals[ i ].vertexNormals = [];
  4635. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4636. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4637. var faceNormal, vertexNormals;
  4638. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4639. face = this.faces[ f ];
  4640. faceNormal = new THREE.Vector3();
  4641. if ( face instanceof THREE.Face3 ) {
  4642. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4643. } else {
  4644. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4645. }
  4646. dstNormalsFace.push( faceNormal );
  4647. dstNormalsVertex.push( vertexNormals );
  4648. }
  4649. }
  4650. var morphNormals = this.morphNormals[ i ];
  4651. // set vertices to morph target
  4652. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4653. // compute morph normals
  4654. tmpGeo.computeFaceNormals();
  4655. tmpGeo.computeVertexNormals();
  4656. // store morph normals
  4657. var faceNormal, vertexNormals;
  4658. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4659. face = this.faces[ f ];
  4660. faceNormal = morphNormals.faceNormals[ f ];
  4661. vertexNormals = morphNormals.vertexNormals[ f ];
  4662. faceNormal.copy( face.normal );
  4663. if ( face instanceof THREE.Face3 ) {
  4664. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4665. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4666. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4667. } else {
  4668. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4669. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4670. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4671. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4672. }
  4673. }
  4674. }
  4675. // restore original normals
  4676. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4677. face = this.faces[ f ];
  4678. face.normal = face.__originalFaceNormal;
  4679. face.vertexNormals = face.__originalVertexNormals;
  4680. }
  4681. },
  4682. computeTangents: function () {
  4683. // based on http://www.terathon.com/code/tangent.html
  4684. // tangents go to vertices
  4685. var f, fl, v, vl, i, il, vertexIndex,
  4686. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4687. x1, x2, y1, y2, z1, z2,
  4688. s1, s2, t1, t2, r, t, test,
  4689. tan1 = [], tan2 = [],
  4690. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4691. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4692. n = new THREE.Vector3(), w;
  4693. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4694. tan1[ v ] = new THREE.Vector3();
  4695. tan2[ v ] = new THREE.Vector3();
  4696. }
  4697. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4698. vA = context.vertices[ a ];
  4699. vB = context.vertices[ b ];
  4700. vC = context.vertices[ c ];
  4701. uvA = uv[ ua ];
  4702. uvB = uv[ ub ];
  4703. uvC = uv[ uc ];
  4704. x1 = vB.x - vA.x;
  4705. x2 = vC.x - vA.x;
  4706. y1 = vB.y - vA.y;
  4707. y2 = vC.y - vA.y;
  4708. z1 = vB.z - vA.z;
  4709. z2 = vC.z - vA.z;
  4710. s1 = uvB.x - uvA.x;
  4711. s2 = uvC.x - uvA.x;
  4712. t1 = uvB.y - uvA.y;
  4713. t2 = uvC.y - uvA.y;
  4714. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4715. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4716. ( t2 * y1 - t1 * y2 ) * r,
  4717. ( t2 * z1 - t1 * z2 ) * r );
  4718. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4719. ( s1 * y2 - s2 * y1 ) * r,
  4720. ( s1 * z2 - s2 * z1 ) * r );
  4721. tan1[ a ].add( sdir );
  4722. tan1[ b ].add( sdir );
  4723. tan1[ c ].add( sdir );
  4724. tan2[ a ].add( tdir );
  4725. tan2[ b ].add( tdir );
  4726. tan2[ c ].add( tdir );
  4727. }
  4728. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4729. face = this.faces[ f ];
  4730. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4731. if ( face instanceof THREE.Face3 ) {
  4732. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4733. } else if ( face instanceof THREE.Face4 ) {
  4734. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4735. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4736. }
  4737. }
  4738. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4739. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4740. face = this.faces[ f ];
  4741. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4742. n.copy( face.vertexNormals[ i ] );
  4743. vertexIndex = face[ faceIndex[ i ] ];
  4744. t = tan1[ vertexIndex ];
  4745. // Gram-Schmidt orthogonalize
  4746. tmp.copy( t );
  4747. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4748. // Calculate handedness
  4749. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4750. test = tmp2.dot( tan2[ vertexIndex ] );
  4751. w = (test < 0.0) ? -1.0 : 1.0;
  4752. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4753. }
  4754. }
  4755. this.hasTangents = true;
  4756. },
  4757. computeLineDistances: function ( ) {
  4758. var d = 0;
  4759. var vertices = this.vertices;
  4760. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4761. if ( i > 0 ) {
  4762. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4763. }
  4764. this.lineDistances[ i ] = d;
  4765. }
  4766. },
  4767. computeBoundingBox: function () {
  4768. if ( this.boundingBox === null ) {
  4769. this.boundingBox = new THREE.Box3();
  4770. }
  4771. this.boundingBox.setFromPoints( this.vertices );
  4772. },
  4773. computeBoundingSphere: function () {
  4774. if ( this.boundingSphere === null ) {
  4775. this.boundingSphere = new THREE.Sphere();
  4776. }
  4777. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4778. },
  4779. /*
  4780. * Checks for duplicate vertices with hashmap.
  4781. * Duplicated vertices are removed
  4782. * and faces' vertices are updated.
  4783. */
  4784. mergeVertices: function () {
  4785. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4786. var unique = [], changes = [];
  4787. var v, key;
  4788. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4789. var precision = Math.pow( 10, precisionPoints );
  4790. var i,il, face;
  4791. var indices, k, j, jl, u;
  4792. // reset cache of vertices as it now will be changing.
  4793. this.__tmpVertices = undefined;
  4794. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4795. v = this.vertices[ i ];
  4796. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4797. if ( verticesMap[ key ] === undefined ) {
  4798. verticesMap[ key ] = i;
  4799. unique.push( this.vertices[ i ] );
  4800. changes[ i ] = unique.length - 1;
  4801. } else {
  4802. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4803. changes[ i ] = changes[ verticesMap[ key ] ];
  4804. }
  4805. };
  4806. // if faces are completely degenerate after merging vertices, we
  4807. // have to remove them from the geometry.
  4808. var faceIndicesToRemove = [];
  4809. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4810. face = this.faces[ i ];
  4811. if ( face instanceof THREE.Face3 ) {
  4812. face.a = changes[ face.a ];
  4813. face.b = changes[ face.b ];
  4814. face.c = changes[ face.c ];
  4815. indices = [ face.a, face.b, face.c ];
  4816. var dupIndex = -1;
  4817. // if any duplicate vertices are found in a Face3
  4818. // we have to remove the face as nothing can be saved
  4819. for ( var n = 0; n < 3; n ++ ) {
  4820. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4821. dupIndex = n;
  4822. faceIndicesToRemove.push( i );
  4823. break;
  4824. }
  4825. }
  4826. } else if ( face instanceof THREE.Face4 ) {
  4827. face.a = changes[ face.a ];
  4828. face.b = changes[ face.b ];
  4829. face.c = changes[ face.c ];
  4830. face.d = changes[ face.d ];
  4831. // check dups in (a, b, c, d) and convert to -> face3
  4832. indices = [ face.a, face.b, face.c, face.d ];
  4833. var dupIndex = -1;
  4834. for ( var n = 0; n < 4; n ++ ) {
  4835. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4836. // if more than one duplicated vertex is found
  4837. // we can't generate any valid Face3's, thus
  4838. // we need to remove this face complete.
  4839. if ( dupIndex >= 0 ) {
  4840. faceIndicesToRemove.push( i );
  4841. }
  4842. dupIndex = n;
  4843. }
  4844. }
  4845. if ( dupIndex >= 0 ) {
  4846. indices.splice( dupIndex, 1 );
  4847. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4848. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4849. u = this.faceVertexUvs[ j ][ i ];
  4850. if ( u ) {
  4851. u.splice( dupIndex, 1 );
  4852. }
  4853. }
  4854. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4855. newFace.vertexNormals = face.vertexNormals;
  4856. newFace.vertexNormals.splice( dupIndex, 1 );
  4857. }
  4858. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4859. newFace.vertexColors = face.vertexColors;
  4860. newFace.vertexColors.splice( dupIndex, 1 );
  4861. }
  4862. this.faces[ i ] = newFace;
  4863. }
  4864. }
  4865. }
  4866. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4867. this.faces.splice( i, 1 );
  4868. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4869. this.faceVertexUvs[ j ].splice( i, 1 );
  4870. }
  4871. }
  4872. // Use unique set of vertices
  4873. var diff = this.vertices.length - unique.length;
  4874. this.vertices = unique;
  4875. return diff;
  4876. },
  4877. clone: function () {
  4878. var geometry = new THREE.Geometry();
  4879. var vertices = this.vertices;
  4880. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4881. geometry.vertices.push( vertices[ i ].clone() );
  4882. }
  4883. var faces = this.faces;
  4884. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4885. geometry.faces.push( faces[ i ].clone() );
  4886. }
  4887. var uvs = this.faceVertexUvs[ 0 ];
  4888. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4889. var uv = uvs[ i ], uvCopy = [];
  4890. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4891. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4892. }
  4893. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4894. }
  4895. return geometry;
  4896. },
  4897. dispose: function () {
  4898. this.dispatchEvent( { type: 'dispose' } );
  4899. }
  4900. };
  4901. THREE.GeometryIdCount = 0;
  4902. /**
  4903. * @author alteredq / http://alteredqualia.com/
  4904. */
  4905. THREE.BufferGeometry = function () {
  4906. this.id = THREE.GeometryIdCount ++;
  4907. // attributes
  4908. this.attributes = {};
  4909. // attributes typed arrays are kept only if dynamic flag is set
  4910. this.dynamic = false;
  4911. // offsets for chunks when using indexed elements
  4912. this.offsets = [];
  4913. // boundings
  4914. this.boundingBox = null;
  4915. this.boundingSphere = null;
  4916. this.hasTangents = false;
  4917. // for compatibility
  4918. this.morphTargets = [];
  4919. };
  4920. THREE.BufferGeometry.prototype = {
  4921. constructor: THREE.BufferGeometry,
  4922. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4923. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4924. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4925. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4926. applyMatrix: function ( matrix ) {
  4927. var positionArray;
  4928. var normalArray;
  4929. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4930. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4931. if ( positionArray !== undefined ) {
  4932. matrix.multiplyVector3Array( positionArray );
  4933. this.verticesNeedUpdate = true;
  4934. }
  4935. if ( normalArray !== undefined ) {
  4936. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4937. normalMatrix.multiplyVector3Array( normalArray );
  4938. this.normalizeNormals();
  4939. this.normalsNeedUpdate = true;
  4940. }
  4941. },
  4942. computeBoundingBox: function () {
  4943. if ( this.boundingBox === null ) {
  4944. this.boundingBox = new THREE.Box3();
  4945. }
  4946. var positions = this.attributes[ "position" ].array;
  4947. if ( positions ) {
  4948. var bb = this.boundingBox;
  4949. var x, y, z;
  4950. if( positions.length >= 3 ) {
  4951. bb.min.x = bb.max.x = positions[ 0 ];
  4952. bb.min.y = bb.max.y = positions[ 1 ];
  4953. bb.min.z = bb.max.z = positions[ 2 ];
  4954. }
  4955. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4956. x = positions[ i ];
  4957. y = positions[ i + 1 ];
  4958. z = positions[ i + 2 ];
  4959. // bounding box
  4960. if ( x < bb.min.x ) {
  4961. bb.min.x = x;
  4962. } else if ( x > bb.max.x ) {
  4963. bb.max.x = x;
  4964. }
  4965. if ( y < bb.min.y ) {
  4966. bb.min.y = y;
  4967. } else if ( y > bb.max.y ) {
  4968. bb.max.y = y;
  4969. }
  4970. if ( z < bb.min.z ) {
  4971. bb.min.z = z;
  4972. } else if ( z > bb.max.z ) {
  4973. bb.max.z = z;
  4974. }
  4975. }
  4976. }
  4977. if ( positions === undefined || positions.length === 0 ) {
  4978. this.boundingBox.min.set( 0, 0, 0 );
  4979. this.boundingBox.max.set( 0, 0, 0 );
  4980. }
  4981. },
  4982. computeBoundingSphere: function () {
  4983. if ( this.boundingSphere === null ) {
  4984. this.boundingSphere = new THREE.Sphere();
  4985. }
  4986. var positions = this.attributes[ "position" ].array;
  4987. if ( positions ) {
  4988. var radiusSq, maxRadiusSq = 0;
  4989. var x, y, z;
  4990. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4991. x = positions[ i ];
  4992. y = positions[ i + 1 ];
  4993. z = positions[ i + 2 ];
  4994. radiusSq = x * x + y * y + z * z;
  4995. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4996. }
  4997. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4998. }
  4999. },
  5000. computeVertexNormals: function () {
  5001. if ( this.attributes[ "position" ] ) {
  5002. var i, il;
  5003. var j, jl;
  5004. var nVertexElements = this.attributes[ "position" ].array.length;
  5005. if ( this.attributes[ "normal" ] === undefined ) {
  5006. this.attributes[ "normal" ] = {
  5007. itemSize: 3,
  5008. array: new Float32Array( nVertexElements ),
  5009. numItems: nVertexElements
  5010. };
  5011. } else {
  5012. // reset existing normals to zero
  5013. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5014. this.attributes[ "normal" ].array[ i ] = 0;
  5015. }
  5016. }
  5017. var positions = this.attributes[ "position" ].array;
  5018. var normals = this.attributes[ "normal" ].array;
  5019. var vA, vB, vC, x, y, z,
  5020. pA = new THREE.Vector3(),
  5021. pB = new THREE.Vector3(),
  5022. pC = new THREE.Vector3(),
  5023. cb = new THREE.Vector3(),
  5024. ab = new THREE.Vector3();
  5025. // indexed elements
  5026. if ( this.attributes[ "index" ] ) {
  5027. var indices = this.attributes[ "index" ].array;
  5028. var offsets = this.offsets;
  5029. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5030. var start = offsets[ j ].start;
  5031. var count = offsets[ j ].count;
  5032. var index = offsets[ j ].index;
  5033. for ( i = start, il = start + count; i < il; i += 3 ) {
  5034. vA = index + indices[ i ];
  5035. vB = index + indices[ i + 1 ];
  5036. vC = index + indices[ i + 2 ];
  5037. x = positions[ vA * 3 ];
  5038. y = positions[ vA * 3 + 1 ];
  5039. z = positions[ vA * 3 + 2 ];
  5040. pA.set( x, y, z );
  5041. x = positions[ vB * 3 ];
  5042. y = positions[ vB * 3 + 1 ];
  5043. z = positions[ vB * 3 + 2 ];
  5044. pB.set( x, y, z );
  5045. x = positions[ vC * 3 ];
  5046. y = positions[ vC * 3 + 1 ];
  5047. z = positions[ vC * 3 + 2 ];
  5048. pC.set( x, y, z );
  5049. cb.subVectors( pC, pB );
  5050. ab.subVectors( pA, pB );
  5051. cb.cross( ab );
  5052. normals[ vA * 3 ] += cb.x;
  5053. normals[ vA * 3 + 1 ] += cb.y;
  5054. normals[ vA * 3 + 2 ] += cb.z;
  5055. normals[ vB * 3 ] += cb.x;
  5056. normals[ vB * 3 + 1 ] += cb.y;
  5057. normals[ vB * 3 + 2 ] += cb.z;
  5058. normals[ vC * 3 ] += cb.x;
  5059. normals[ vC * 3 + 1 ] += cb.y;
  5060. normals[ vC * 3 + 2 ] += cb.z;
  5061. }
  5062. }
  5063. // non-indexed elements (unconnected triangle soup)
  5064. } else {
  5065. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5066. x = positions[ i ];
  5067. y = positions[ i + 1 ];
  5068. z = positions[ i + 2 ];
  5069. pA.set( x, y, z );
  5070. x = positions[ i + 3 ];
  5071. y = positions[ i + 4 ];
  5072. z = positions[ i + 5 ];
  5073. pB.set( x, y, z );
  5074. x = positions[ i + 6 ];
  5075. y = positions[ i + 7 ];
  5076. z = positions[ i + 8 ];
  5077. pC.set( x, y, z );
  5078. cb.subVectors( pC, pB );
  5079. ab.subVectors( pA, pB );
  5080. cb.cross( ab );
  5081. normals[ i ] = cb.x;
  5082. normals[ i + 1 ] = cb.y;
  5083. normals[ i + 2 ] = cb.z;
  5084. normals[ i + 3 ] = cb.x;
  5085. normals[ i + 4 ] = cb.y;
  5086. normals[ i + 5 ] = cb.z;
  5087. normals[ i + 6 ] = cb.x;
  5088. normals[ i + 7 ] = cb.y;
  5089. normals[ i + 8 ] = cb.z;
  5090. }
  5091. }
  5092. this.normalizeNormals();
  5093. this.normalsNeedUpdate = true;
  5094. }
  5095. },
  5096. normalizeNormals: function () {
  5097. var normals = this.attributes[ "normal" ].array;
  5098. var x, y, z, n;
  5099. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5100. x = normals[ i ];
  5101. y = normals[ i + 1 ];
  5102. z = normals[ i + 2 ];
  5103. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5104. normals[ i ] *= n;
  5105. normals[ i + 1 ] *= n;
  5106. normals[ i + 2 ] *= n;
  5107. }
  5108. },
  5109. computeTangents: function () {
  5110. // based on http://www.terathon.com/code/tangent.html
  5111. // (per vertex tangents)
  5112. if ( this.attributes[ "index" ] === undefined ||
  5113. this.attributes[ "position" ] === undefined ||
  5114. this.attributes[ "normal" ] === undefined ||
  5115. this.attributes[ "uv" ] === undefined ) {
  5116. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5117. return;
  5118. }
  5119. var indices = this.attributes[ "index" ].array;
  5120. var positions = this.attributes[ "position" ].array;
  5121. var normals = this.attributes[ "normal" ].array;
  5122. var uvs = this.attributes[ "uv" ].array;
  5123. var nVertices = positions.length / 3;
  5124. if ( this.attributes[ "tangent" ] === undefined ) {
  5125. var nTangentElements = 4 * nVertices;
  5126. this.attributes[ "tangent" ] = {
  5127. itemSize: 4,
  5128. array: new Float32Array( nTangentElements ),
  5129. numItems: nTangentElements
  5130. };
  5131. }
  5132. var tangents = this.attributes[ "tangent" ].array;
  5133. var tan1 = [], tan2 = [];
  5134. for ( var k = 0; k < nVertices; k ++ ) {
  5135. tan1[ k ] = new THREE.Vector3();
  5136. tan2[ k ] = new THREE.Vector3();
  5137. }
  5138. var xA, yA, zA,
  5139. xB, yB, zB,
  5140. xC, yC, zC,
  5141. uA, vA,
  5142. uB, vB,
  5143. uC, vC,
  5144. x1, x2, y1, y2, z1, z2,
  5145. s1, s2, t1, t2, r;
  5146. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5147. function handleTriangle( a, b, c ) {
  5148. xA = positions[ a * 3 ];
  5149. yA = positions[ a * 3 + 1 ];
  5150. zA = positions[ a * 3 + 2 ];
  5151. xB = positions[ b * 3 ];
  5152. yB = positions[ b * 3 + 1 ];
  5153. zB = positions[ b * 3 + 2 ];
  5154. xC = positions[ c * 3 ];
  5155. yC = positions[ c * 3 + 1 ];
  5156. zC = positions[ c * 3 + 2 ];
  5157. uA = uvs[ a * 2 ];
  5158. vA = uvs[ a * 2 + 1 ];
  5159. uB = uvs[ b * 2 ];
  5160. vB = uvs[ b * 2 + 1 ];
  5161. uC = uvs[ c * 2 ];
  5162. vC = uvs[ c * 2 + 1 ];
  5163. x1 = xB - xA;
  5164. x2 = xC - xA;
  5165. y1 = yB - yA;
  5166. y2 = yC - yA;
  5167. z1 = zB - zA;
  5168. z2 = zC - zA;
  5169. s1 = uB - uA;
  5170. s2 = uC - uA;
  5171. t1 = vB - vA;
  5172. t2 = vC - vA;
  5173. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5174. sdir.set(
  5175. ( t2 * x1 - t1 * x2 ) * r,
  5176. ( t2 * y1 - t1 * y2 ) * r,
  5177. ( t2 * z1 - t1 * z2 ) * r
  5178. );
  5179. tdir.set(
  5180. ( s1 * x2 - s2 * x1 ) * r,
  5181. ( s1 * y2 - s2 * y1 ) * r,
  5182. ( s1 * z2 - s2 * z1 ) * r
  5183. );
  5184. tan1[ a ].add( sdir );
  5185. tan1[ b ].add( sdir );
  5186. tan1[ c ].add( sdir );
  5187. tan2[ a ].add( tdir );
  5188. tan2[ b ].add( tdir );
  5189. tan2[ c ].add( tdir );
  5190. }
  5191. var i, il;
  5192. var j, jl;
  5193. var iA, iB, iC;
  5194. var offsets = this.offsets;
  5195. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5196. var start = offsets[ j ].start;
  5197. var count = offsets[ j ].count;
  5198. var index = offsets[ j ].index;
  5199. for ( i = start, il = start + count; i < il; i += 3 ) {
  5200. iA = index + indices[ i ];
  5201. iB = index + indices[ i + 1 ];
  5202. iC = index + indices[ i + 2 ];
  5203. handleTriangle( iA, iB, iC );
  5204. }
  5205. }
  5206. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5207. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5208. var w, t, test;
  5209. function handleVertex( v ) {
  5210. n.x = normals[ v * 3 ];
  5211. n.y = normals[ v * 3 + 1 ];
  5212. n.z = normals[ v * 3 + 2 ];
  5213. n2.copy( n );
  5214. t = tan1[ v ];
  5215. // Gram-Schmidt orthogonalize
  5216. tmp.copy( t );
  5217. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5218. // Calculate handedness
  5219. tmp2.crossVectors( n2, t );
  5220. test = tmp2.dot( tan2[ v ] );
  5221. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5222. tangents[ v * 4 ] = tmp.x;
  5223. tangents[ v * 4 + 1 ] = tmp.y;
  5224. tangents[ v * 4 + 2 ] = tmp.z;
  5225. tangents[ v * 4 + 3 ] = w;
  5226. }
  5227. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5228. var start = offsets[ j ].start;
  5229. var count = offsets[ j ].count;
  5230. var index = offsets[ j ].index;
  5231. for ( i = start, il = start + count; i < il; i += 3 ) {
  5232. iA = index + indices[ i ];
  5233. iB = index + indices[ i + 1 ];
  5234. iC = index + indices[ i + 2 ];
  5235. handleVertex( iA );
  5236. handleVertex( iB );
  5237. handleVertex( iC );
  5238. }
  5239. }
  5240. this.hasTangents = true;
  5241. this.tangentsNeedUpdate = true;
  5242. },
  5243. dispose: function () {
  5244. this.dispatchEvent( { type: 'dispose' } );
  5245. }
  5246. };
  5247. /**
  5248. * @author mrdoob / http://mrdoob.com/
  5249. * @author mikael emtinger / http://gomo.se/
  5250. * @author WestLangley / http://github.com/WestLangley
  5251. */
  5252. THREE.Camera = function () {
  5253. THREE.Object3D.call( this );
  5254. this.matrixWorldInverse = new THREE.Matrix4();
  5255. this.projectionMatrix = new THREE.Matrix4();
  5256. this.projectionMatrixInverse = new THREE.Matrix4();
  5257. };
  5258. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5259. THREE.Camera.prototype.lookAt = function () {
  5260. // This routine does not support cameras with rotated and/or translated parent(s)
  5261. var m1 = new THREE.Matrix4();
  5262. return function ( vector ) {
  5263. m1.lookAt( this.position, vector, this.up );
  5264. if ( this.useQuaternion === true ) {
  5265. this.quaternion.setFromRotationMatrix( m1 );
  5266. } else {
  5267. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  5268. }
  5269. };
  5270. }();
  5271. /**
  5272. * @author alteredq / http://alteredqualia.com/
  5273. */
  5274. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5275. THREE.Camera.call( this );
  5276. this.left = left;
  5277. this.right = right;
  5278. this.top = top;
  5279. this.bottom = bottom;
  5280. this.near = ( near !== undefined ) ? near : 0.1;
  5281. this.far = ( far !== undefined ) ? far : 2000;
  5282. this.updateProjectionMatrix();
  5283. };
  5284. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5285. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5286. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5287. };
  5288. /**
  5289. * @author mrdoob / http://mrdoob.com/
  5290. * @author greggman / http://games.greggman.com/
  5291. * @author zz85 / http://www.lab4games.net/zz85/blog
  5292. */
  5293. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5294. THREE.Camera.call( this );
  5295. this.fov = fov !== undefined ? fov : 50;
  5296. this.aspect = aspect !== undefined ? aspect : 1;
  5297. this.near = near !== undefined ? near : 0.1;
  5298. this.far = far !== undefined ? far : 2000;
  5299. this.updateProjectionMatrix();
  5300. };
  5301. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5302. /**
  5303. * Uses Focal Length (in mm) to estimate and set FOV
  5304. * 35mm (fullframe) camera is used if frame size is not specified;
  5305. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5306. */
  5307. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5308. if ( frameHeight === undefined ) frameHeight = 24;
  5309. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5310. this.updateProjectionMatrix();
  5311. }
  5312. /**
  5313. * Sets an offset in a larger frustum. This is useful for multi-window or
  5314. * multi-monitor/multi-machine setups.
  5315. *
  5316. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5317. * the monitors are in grid like this
  5318. *
  5319. * +---+---+---+
  5320. * | A | B | C |
  5321. * +---+---+---+
  5322. * | D | E | F |
  5323. * +---+---+---+
  5324. *
  5325. * then for each monitor you would call it like this
  5326. *
  5327. * var w = 1920;
  5328. * var h = 1080;
  5329. * var fullWidth = w * 3;
  5330. * var fullHeight = h * 2;
  5331. *
  5332. * --A--
  5333. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5334. * --B--
  5335. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5336. * --C--
  5337. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5338. * --D--
  5339. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5340. * --E--
  5341. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5342. * --F--
  5343. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5344. *
  5345. * Note there is no reason monitors have to be the same size or in a grid.
  5346. */
  5347. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5348. this.fullWidth = fullWidth;
  5349. this.fullHeight = fullHeight;
  5350. this.x = x;
  5351. this.y = y;
  5352. this.width = width;
  5353. this.height = height;
  5354. this.updateProjectionMatrix();
  5355. };
  5356. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5357. if ( this.fullWidth ) {
  5358. var aspect = this.fullWidth / this.fullHeight;
  5359. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5360. var bottom = -top;
  5361. var left = aspect * bottom;
  5362. var right = aspect * top;
  5363. var width = Math.abs( right - left );
  5364. var height = Math.abs( top - bottom );
  5365. this.projectionMatrix.makeFrustum(
  5366. left + this.x * width / this.fullWidth,
  5367. left + ( this.x + this.width ) * width / this.fullWidth,
  5368. top - ( this.y + this.height ) * height / this.fullHeight,
  5369. top - this.y * height / this.fullHeight,
  5370. this.near,
  5371. this.far
  5372. );
  5373. } else {
  5374. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5375. }
  5376. };
  5377. /**
  5378. * @author mrdoob / http://mrdoob.com/
  5379. * @author alteredq / http://alteredqualia.com/
  5380. */
  5381. THREE.Light = function ( hex ) {
  5382. THREE.Object3D.call( this );
  5383. this.color = new THREE.Color( hex );
  5384. };
  5385. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5386. THREE.Light.prototype.clone = function ( light ) {
  5387. if ( light === undefined ) light = new THREE.Light();
  5388. THREE.Object3D.prototype.clone.call( this, light );
  5389. light.color.copy( this.color );
  5390. return light;
  5391. };
  5392. /**
  5393. * @author mrdoob / http://mrdoob.com/
  5394. */
  5395. THREE.AmbientLight = function ( hex ) {
  5396. THREE.Light.call( this, hex );
  5397. };
  5398. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5399. THREE.AmbientLight.prototype.clone = function () {
  5400. var light = new THREE.AmbientLight();
  5401. THREE.Light.prototype.clone.call( this, light );
  5402. return light;
  5403. };
  5404. /**
  5405. * @author MPanknin / http://www.redplant.de/
  5406. * @author alteredq / http://alteredqualia.com/
  5407. */
  5408. THREE.AreaLight = function ( hex, intensity ) {
  5409. THREE.Light.call( this, hex );
  5410. this.normal = new THREE.Vector3( 0, -1, 0 );
  5411. this.right = new THREE.Vector3( 1, 0, 0 );
  5412. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5413. this.width = 1.0;
  5414. this.height = 1.0;
  5415. this.constantAttenuation = 1.5;
  5416. this.linearAttenuation = 0.5;
  5417. this.quadraticAttenuation = 0.1;
  5418. };
  5419. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5420. /**
  5421. * @author mrdoob / http://mrdoob.com/
  5422. * @author alteredq / http://alteredqualia.com/
  5423. */
  5424. THREE.DirectionalLight = function ( hex, intensity ) {
  5425. THREE.Light.call( this, hex );
  5426. this.position.set( 0, 1, 0 );
  5427. this.target = new THREE.Object3D();
  5428. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5429. this.castShadow = false;
  5430. this.onlyShadow = false;
  5431. //
  5432. this.shadowCameraNear = 50;
  5433. this.shadowCameraFar = 5000;
  5434. this.shadowCameraLeft = -500;
  5435. this.shadowCameraRight = 500;
  5436. this.shadowCameraTop = 500;
  5437. this.shadowCameraBottom = -500;
  5438. this.shadowCameraVisible = false;
  5439. this.shadowBias = 0;
  5440. this.shadowDarkness = 0.5;
  5441. this.shadowMapWidth = 512;
  5442. this.shadowMapHeight = 512;
  5443. //
  5444. this.shadowCascade = false;
  5445. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5446. this.shadowCascadeCount = 2;
  5447. this.shadowCascadeBias = [ 0, 0, 0 ];
  5448. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5449. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5450. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5451. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5452. this.shadowCascadeArray = [];
  5453. //
  5454. this.shadowMap = null;
  5455. this.shadowMapSize = null;
  5456. this.shadowCamera = null;
  5457. this.shadowMatrix = null;
  5458. };
  5459. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5460. THREE.DirectionalLight.prototype.clone = function () {
  5461. var light = new THREE.DirectionalLight();
  5462. THREE.Light.prototype.clone.call( this, light );
  5463. light.target = this.target.clone();
  5464. light.intensity = this.intensity;
  5465. light.castShadow = this.castShadow;
  5466. light.onlyShadow = this.onlyShadow;
  5467. return light;
  5468. };
  5469. /**
  5470. * @author alteredq / http://alteredqualia.com/
  5471. */
  5472. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5473. THREE.Light.call( this, skyColorHex );
  5474. this.position.set( 0, 100, 0 );
  5475. this.groundColor = new THREE.Color( groundColorHex );
  5476. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5477. };
  5478. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5479. THREE.HemisphereLight.prototype.clone = function () {
  5480. var light = new THREE.PointLight();
  5481. THREE.Light.prototype.clone.call( this, light );
  5482. light.groundColor.copy( this.groundColor );
  5483. light.intensity = this.intensity;
  5484. return light;
  5485. };
  5486. /**
  5487. * @author mrdoob / http://mrdoob.com/
  5488. */
  5489. THREE.PointLight = function ( hex, intensity, distance ) {
  5490. THREE.Light.call( this, hex );
  5491. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5492. this.distance = ( distance !== undefined ) ? distance : 0;
  5493. };
  5494. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5495. THREE.PointLight.prototype.clone = function () {
  5496. var light = new THREE.PointLight();
  5497. THREE.Light.prototype.clone.call( this, light );
  5498. light.intensity = this.intensity;
  5499. light.distance = this.distance;
  5500. return light;
  5501. };
  5502. /**
  5503. * @author alteredq / http://alteredqualia.com/
  5504. */
  5505. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5506. THREE.Light.call( this, hex );
  5507. this.position.set( 0, 1, 0 );
  5508. this.target = new THREE.Object3D();
  5509. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5510. this.distance = ( distance !== undefined ) ? distance : 0;
  5511. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5512. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5513. this.castShadow = false;
  5514. this.onlyShadow = false;
  5515. //
  5516. this.shadowCameraNear = 50;
  5517. this.shadowCameraFar = 5000;
  5518. this.shadowCameraFov = 50;
  5519. this.shadowCameraVisible = false;
  5520. this.shadowBias = 0;
  5521. this.shadowDarkness = 0.5;
  5522. this.shadowMapWidth = 512;
  5523. this.shadowMapHeight = 512;
  5524. //
  5525. this.shadowMap = null;
  5526. this.shadowMapSize = null;
  5527. this.shadowCamera = null;
  5528. this.shadowMatrix = null;
  5529. };
  5530. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5531. THREE.SpotLight.prototype.clone = function () {
  5532. var light = new THREE.SpotLight();
  5533. THREE.Light.prototype.clone.call( this, light );
  5534. light.target = this.target.clone();
  5535. light.intensity = this.intensity;
  5536. light.distance = this.distance;
  5537. light.angle = this.angle;
  5538. light.exponent = this.exponent;
  5539. light.castShadow = this.castShadow;
  5540. light.onlyShadow = this.onlyShadow;
  5541. return light;
  5542. };
  5543. /**
  5544. * @author alteredq / http://alteredqualia.com/
  5545. */
  5546. THREE.Loader = function ( showStatus ) {
  5547. this.showStatus = showStatus;
  5548. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5549. this.onLoadStart = function () {};
  5550. this.onLoadProgress = function () {};
  5551. this.onLoadComplete = function () {};
  5552. };
  5553. THREE.Loader.prototype = {
  5554. constructor: THREE.Loader,
  5555. crossOrigin: 'anonymous',
  5556. addStatusElement: function () {
  5557. var e = document.createElement( "div" );
  5558. e.style.position = "absolute";
  5559. e.style.right = "0px";
  5560. e.style.top = "0px";
  5561. e.style.fontSize = "0.8em";
  5562. e.style.textAlign = "left";
  5563. e.style.background = "rgba(0,0,0,0.25)";
  5564. e.style.color = "#fff";
  5565. e.style.width = "120px";
  5566. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5567. e.style.zIndex = 1000;
  5568. e.innerHTML = "Loading ...";
  5569. return e;
  5570. },
  5571. updateProgress: function ( progress ) {
  5572. var message = "Loaded ";
  5573. if ( progress.total ) {
  5574. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5575. } else {
  5576. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5577. }
  5578. this.statusDomElement.innerHTML = message;
  5579. },
  5580. extractUrlBase: function ( url ) {
  5581. var parts = url.split( '/' );
  5582. parts.pop();
  5583. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5584. },
  5585. initMaterials: function ( materials, texturePath ) {
  5586. var array = [];
  5587. for ( var i = 0; i < materials.length; ++ i ) {
  5588. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5589. }
  5590. return array;
  5591. },
  5592. needsTangents: function ( materials ) {
  5593. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5594. var m = materials[ i ];
  5595. if ( m instanceof THREE.ShaderMaterial ) return true;
  5596. }
  5597. return false;
  5598. },
  5599. createMaterial: function ( m, texturePath ) {
  5600. var _this = this;
  5601. function is_pow2( n ) {
  5602. var l = Math.log( n ) / Math.LN2;
  5603. return Math.floor( l ) == l;
  5604. }
  5605. function nearest_pow2( n ) {
  5606. var l = Math.log( n ) / Math.LN2;
  5607. return Math.pow( 2, Math.round( l ) );
  5608. }
  5609. function load_image( where, url ) {
  5610. var image = new Image();
  5611. image.onload = function () {
  5612. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5613. var width = nearest_pow2( this.width );
  5614. var height = nearest_pow2( this.height );
  5615. where.image.width = width;
  5616. where.image.height = height;
  5617. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5618. } else {
  5619. where.image = this;
  5620. }
  5621. where.needsUpdate = true;
  5622. };
  5623. image.crossOrigin = _this.crossOrigin;
  5624. image.src = url;
  5625. }
  5626. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5627. var isCompressed = /\.dds$/i.test( sourceFile );
  5628. var fullPath = texturePath + "/" + sourceFile;
  5629. if ( isCompressed ) {
  5630. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5631. where[ name ] = texture;
  5632. } else {
  5633. var texture = document.createElement( 'canvas' );
  5634. where[ name ] = new THREE.Texture( texture );
  5635. }
  5636. where[ name ].sourceFile = sourceFile;
  5637. if( repeat ) {
  5638. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5639. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5640. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5641. }
  5642. if ( offset ) {
  5643. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5644. }
  5645. if ( wrap ) {
  5646. var wrapMap = {
  5647. "repeat": THREE.RepeatWrapping,
  5648. "mirror": THREE.MirroredRepeatWrapping
  5649. }
  5650. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5651. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5652. }
  5653. if ( anisotropy ) {
  5654. where[ name ].anisotropy = anisotropy;
  5655. }
  5656. if ( ! isCompressed ) {
  5657. load_image( where[ name ], fullPath );
  5658. }
  5659. }
  5660. function rgb2hex( rgb ) {
  5661. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5662. }
  5663. // defaults
  5664. var mtype = "MeshLambertMaterial";
  5665. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5666. // parameters from model file
  5667. if ( m.shading ) {
  5668. var shading = m.shading.toLowerCase();
  5669. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5670. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5671. }
  5672. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5673. mpars.blending = THREE[ m.blending ];
  5674. }
  5675. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5676. mpars.transparent = m.transparent;
  5677. }
  5678. if ( m.depthTest !== undefined ) {
  5679. mpars.depthTest = m.depthTest;
  5680. }
  5681. if ( m.depthWrite !== undefined ) {
  5682. mpars.depthWrite = m.depthWrite;
  5683. }
  5684. if ( m.visible !== undefined ) {
  5685. mpars.visible = m.visible;
  5686. }
  5687. if ( m.flipSided !== undefined ) {
  5688. mpars.side = THREE.BackSide;
  5689. }
  5690. if ( m.doubleSided !== undefined ) {
  5691. mpars.side = THREE.DoubleSide;
  5692. }
  5693. if ( m.wireframe !== undefined ) {
  5694. mpars.wireframe = m.wireframe;
  5695. }
  5696. if ( m.vertexColors !== undefined ) {
  5697. if ( m.vertexColors === "face" ) {
  5698. mpars.vertexColors = THREE.FaceColors;
  5699. } else if ( m.vertexColors ) {
  5700. mpars.vertexColors = THREE.VertexColors;
  5701. }
  5702. }
  5703. // colors
  5704. if ( m.colorDiffuse ) {
  5705. mpars.color = rgb2hex( m.colorDiffuse );
  5706. } else if ( m.DbgColor ) {
  5707. mpars.color = m.DbgColor;
  5708. }
  5709. if ( m.colorSpecular ) {
  5710. mpars.specular = rgb2hex( m.colorSpecular );
  5711. }
  5712. if ( m.colorAmbient ) {
  5713. mpars.ambient = rgb2hex( m.colorAmbient );
  5714. }
  5715. // modifiers
  5716. if ( m.transparency ) {
  5717. mpars.opacity = m.transparency;
  5718. }
  5719. if ( m.specularCoef ) {
  5720. mpars.shininess = m.specularCoef;
  5721. }
  5722. // textures
  5723. if ( m.mapDiffuse && texturePath ) {
  5724. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5725. }
  5726. if ( m.mapLight && texturePath ) {
  5727. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5728. }
  5729. if ( m.mapBump && texturePath ) {
  5730. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5731. }
  5732. if ( m.mapNormal && texturePath ) {
  5733. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5734. }
  5735. if ( m.mapSpecular && texturePath ) {
  5736. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5737. }
  5738. //
  5739. if ( m.mapBumpScale ) {
  5740. mpars.bumpScale = m.mapBumpScale;
  5741. }
  5742. // special case for normal mapped material
  5743. if ( m.mapNormal ) {
  5744. var shader = THREE.ShaderLib[ "normalmap" ];
  5745. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5746. uniforms[ "tNormal" ].value = mpars.normalMap;
  5747. if ( m.mapNormalFactor ) {
  5748. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5749. }
  5750. if ( mpars.map ) {
  5751. uniforms[ "tDiffuse" ].value = mpars.map;
  5752. uniforms[ "enableDiffuse" ].value = true;
  5753. }
  5754. if ( mpars.specularMap ) {
  5755. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5756. uniforms[ "enableSpecular" ].value = true;
  5757. }
  5758. if ( mpars.lightMap ) {
  5759. uniforms[ "tAO" ].value = mpars.lightMap;
  5760. uniforms[ "enableAO" ].value = true;
  5761. }
  5762. // for the moment don't handle displacement texture
  5763. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5764. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5765. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5766. uniforms[ "uShininess" ].value = mpars.shininess;
  5767. if ( mpars.opacity !== undefined ) {
  5768. uniforms[ "uOpacity" ].value = mpars.opacity;
  5769. }
  5770. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5771. var material = new THREE.ShaderMaterial( parameters );
  5772. if ( mpars.transparent ) {
  5773. material.transparent = true;
  5774. }
  5775. } else {
  5776. var material = new THREE[ mtype ]( mpars );
  5777. }
  5778. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5779. return material;
  5780. }
  5781. };
  5782. /**
  5783. * @author mrdoob / http://mrdoob.com/
  5784. */
  5785. THREE.ImageLoader = function () {
  5786. this.crossOrigin = null;
  5787. };
  5788. THREE.ImageLoader.prototype = {
  5789. constructor: THREE.ImageLoader,
  5790. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  5791. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  5792. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  5793. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  5794. load: function ( url, image ) {
  5795. var scope = this;
  5796. if ( image === undefined ) image = new Image();
  5797. image.addEventListener( 'load', function () {
  5798. scope.dispatchEvent( { type: 'load', content: image } );
  5799. }, false );
  5800. image.addEventListener( 'error', function () {
  5801. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5802. }, false );
  5803. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5804. image.src = url;
  5805. }
  5806. }
  5807. /**
  5808. * @author mrdoob / http://mrdoob.com/
  5809. * @author alteredq / http://alteredqualia.com/
  5810. */
  5811. THREE.JSONLoader = function ( showStatus ) {
  5812. THREE.Loader.call( this, showStatus );
  5813. this.withCredentials = false;
  5814. };
  5815. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5816. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5817. var scope = this;
  5818. // todo: unify load API to for easier SceneLoader use
  5819. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5820. this.onLoadStart();
  5821. this.loadAjaxJSON( this, url, callback, texturePath );
  5822. };
  5823. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5824. var xhr = new XMLHttpRequest();
  5825. var length = 0;
  5826. xhr.onreadystatechange = function () {
  5827. if ( xhr.readyState === xhr.DONE ) {
  5828. if ( xhr.status === 200 || xhr.status === 0 ) {
  5829. if ( xhr.responseText ) {
  5830. var json = JSON.parse( xhr.responseText );
  5831. var result = context.parse( json, texturePath );
  5832. callback( result.geometry, result.materials );
  5833. } else {
  5834. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5835. }
  5836. // in context of more complex asset initialization
  5837. // do not block on single failed file
  5838. // maybe should go even one more level up
  5839. context.onLoadComplete();
  5840. } else {
  5841. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5842. }
  5843. } else if ( xhr.readyState === xhr.LOADING ) {
  5844. if ( callbackProgress ) {
  5845. if ( length === 0 ) {
  5846. length = xhr.getResponseHeader( "Content-Length" );
  5847. }
  5848. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5849. }
  5850. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5851. if ( callbackProgress !== undefined ) {
  5852. length = xhr.getResponseHeader( "Content-Length" );
  5853. }
  5854. }
  5855. };
  5856. xhr.open( "GET", url, true );
  5857. xhr.withCredentials = this.withCredentials;
  5858. xhr.send( null );
  5859. };
  5860. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  5861. var scope = this,
  5862. geometry = new THREE.Geometry(),
  5863. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5864. parseModel( scale );
  5865. parseSkin();
  5866. parseMorphing( scale );
  5867. geometry.computeCentroids();
  5868. geometry.computeFaceNormals();
  5869. function parseModel( scale ) {
  5870. function isBitSet( value, position ) {
  5871. return value & ( 1 << position );
  5872. }
  5873. var i, j, fi,
  5874. offset, zLength, nVertices,
  5875. colorIndex, normalIndex, uvIndex, materialIndex,
  5876. type,
  5877. isQuad,
  5878. hasMaterial,
  5879. hasFaceUv, hasFaceVertexUv,
  5880. hasFaceNormal, hasFaceVertexNormal,
  5881. hasFaceColor, hasFaceVertexColor,
  5882. vertex, face, color, normal,
  5883. uvLayer, uvs, u, v,
  5884. faces = json.faces,
  5885. vertices = json.vertices,
  5886. normals = json.normals,
  5887. colors = json.colors,
  5888. nUvLayers = 0;
  5889. // disregard empty arrays
  5890. for ( i = 0; i < json.uvs.length; i++ ) {
  5891. if ( json.uvs[ i ].length ) nUvLayers ++;
  5892. }
  5893. for ( i = 0; i < nUvLayers; i++ ) {
  5894. geometry.faceUvs[ i ] = [];
  5895. geometry.faceVertexUvs[ i ] = [];
  5896. }
  5897. offset = 0;
  5898. zLength = vertices.length;
  5899. while ( offset < zLength ) {
  5900. vertex = new THREE.Vector3();
  5901. vertex.x = vertices[ offset ++ ] * scale;
  5902. vertex.y = vertices[ offset ++ ] * scale;
  5903. vertex.z = vertices[ offset ++ ] * scale;
  5904. geometry.vertices.push( vertex );
  5905. }
  5906. offset = 0;
  5907. zLength = faces.length;
  5908. while ( offset < zLength ) {
  5909. type = faces[ offset ++ ];
  5910. isQuad = isBitSet( type, 0 );
  5911. hasMaterial = isBitSet( type, 1 );
  5912. hasFaceUv = isBitSet( type, 2 );
  5913. hasFaceVertexUv = isBitSet( type, 3 );
  5914. hasFaceNormal = isBitSet( type, 4 );
  5915. hasFaceVertexNormal = isBitSet( type, 5 );
  5916. hasFaceColor = isBitSet( type, 6 );
  5917. hasFaceVertexColor = isBitSet( type, 7 );
  5918. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5919. if ( isQuad ) {
  5920. face = new THREE.Face4();
  5921. face.a = faces[ offset ++ ];
  5922. face.b = faces[ offset ++ ];
  5923. face.c = faces[ offset ++ ];
  5924. face.d = faces[ offset ++ ];
  5925. nVertices = 4;
  5926. } else {
  5927. face = new THREE.Face3();
  5928. face.a = faces[ offset ++ ];
  5929. face.b = faces[ offset ++ ];
  5930. face.c = faces[ offset ++ ];
  5931. nVertices = 3;
  5932. }
  5933. if ( hasMaterial ) {
  5934. materialIndex = faces[ offset ++ ];
  5935. face.materialIndex = materialIndex;
  5936. }
  5937. // to get face <=> uv index correspondence
  5938. fi = geometry.faces.length;
  5939. if ( hasFaceUv ) {
  5940. for ( i = 0; i < nUvLayers; i++ ) {
  5941. uvLayer = json.uvs[ i ];
  5942. uvIndex = faces[ offset ++ ];
  5943. u = uvLayer[ uvIndex * 2 ];
  5944. v = uvLayer[ uvIndex * 2 + 1 ];
  5945. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5946. }
  5947. }
  5948. if ( hasFaceVertexUv ) {
  5949. for ( i = 0; i < nUvLayers; i++ ) {
  5950. uvLayer = json.uvs[ i ];
  5951. uvs = [];
  5952. for ( j = 0; j < nVertices; j ++ ) {
  5953. uvIndex = faces[ offset ++ ];
  5954. u = uvLayer[ uvIndex * 2 ];
  5955. v = uvLayer[ uvIndex * 2 + 1 ];
  5956. uvs[ j ] = new THREE.Vector2( u, v );
  5957. }
  5958. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5959. }
  5960. }
  5961. if ( hasFaceNormal ) {
  5962. normalIndex = faces[ offset ++ ] * 3;
  5963. normal = new THREE.Vector3();
  5964. normal.x = normals[ normalIndex ++ ];
  5965. normal.y = normals[ normalIndex ++ ];
  5966. normal.z = normals[ normalIndex ];
  5967. face.normal = normal;
  5968. }
  5969. if ( hasFaceVertexNormal ) {
  5970. for ( i = 0; i < nVertices; i++ ) {
  5971. normalIndex = faces[ offset ++ ] * 3;
  5972. normal = new THREE.Vector3();
  5973. normal.x = normals[ normalIndex ++ ];
  5974. normal.y = normals[ normalIndex ++ ];
  5975. normal.z = normals[ normalIndex ];
  5976. face.vertexNormals.push( normal );
  5977. }
  5978. }
  5979. if ( hasFaceColor ) {
  5980. colorIndex = faces[ offset ++ ];
  5981. color = new THREE.Color( colors[ colorIndex ] );
  5982. face.color = color;
  5983. }
  5984. if ( hasFaceVertexColor ) {
  5985. for ( i = 0; i < nVertices; i++ ) {
  5986. colorIndex = faces[ offset ++ ];
  5987. color = new THREE.Color( colors[ colorIndex ] );
  5988. face.vertexColors.push( color );
  5989. }
  5990. }
  5991. geometry.faces.push( face );
  5992. }
  5993. };
  5994. function parseSkin() {
  5995. var i, l, x, y, z, w, a, b, c, d;
  5996. if ( json.skinWeights ) {
  5997. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5998. x = json.skinWeights[ i ];
  5999. y = json.skinWeights[ i + 1 ];
  6000. z = 0;
  6001. w = 0;
  6002. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6003. }
  6004. }
  6005. if ( json.skinIndices ) {
  6006. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6007. a = json.skinIndices[ i ];
  6008. b = json.skinIndices[ i + 1 ];
  6009. c = 0;
  6010. d = 0;
  6011. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6012. }
  6013. }
  6014. geometry.bones = json.bones;
  6015. geometry.animation = json.animation;
  6016. };
  6017. function parseMorphing( scale ) {
  6018. if ( json.morphTargets !== undefined ) {
  6019. var i, l, v, vl, dstVertices, srcVertices;
  6020. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6021. geometry.morphTargets[ i ] = {};
  6022. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6023. geometry.morphTargets[ i ].vertices = [];
  6024. dstVertices = geometry.morphTargets[ i ].vertices;
  6025. srcVertices = json.morphTargets [ i ].vertices;
  6026. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6027. var vertex = new THREE.Vector3();
  6028. vertex.x = srcVertices[ v ] * scale;
  6029. vertex.y = srcVertices[ v + 1 ] * scale;
  6030. vertex.z = srcVertices[ v + 2 ] * scale;
  6031. dstVertices.push( vertex );
  6032. }
  6033. }
  6034. }
  6035. if ( json.morphColors !== undefined ) {
  6036. var i, l, c, cl, dstColors, srcColors, color;
  6037. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6038. geometry.morphColors[ i ] = {};
  6039. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6040. geometry.morphColors[ i ].colors = [];
  6041. dstColors = geometry.morphColors[ i ].colors;
  6042. srcColors = json.morphColors [ i ].colors;
  6043. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6044. color = new THREE.Color( 0xffaa00 );
  6045. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6046. dstColors.push( color );
  6047. }
  6048. }
  6049. }
  6050. };
  6051. if ( json.materials === undefined ) {
  6052. return { geometry: geometry };
  6053. } else {
  6054. var materials = this.initMaterials( json.materials, texturePath );
  6055. if ( this.needsTangents( materials ) ) {
  6056. geometry.computeTangents();
  6057. }
  6058. return { geometry: geometry, materials: materials };
  6059. }
  6060. };
  6061. /**
  6062. * @author mrdoob / http://mrdoob.com/
  6063. */
  6064. THREE.LoadingMonitor = function () {
  6065. var scope = this;
  6066. var loaded = 0;
  6067. var total = 0;
  6068. var onLoad = function ( event ) {
  6069. loaded ++;
  6070. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  6071. if ( loaded === total ) {
  6072. scope.dispatchEvent( { type: 'load' } );
  6073. }
  6074. };
  6075. this.add = function ( loader ) {
  6076. total ++;
  6077. loader.addEventListener( 'load', onLoad, false );
  6078. };
  6079. };
  6080. THREE.LoadingMonitor.prototype = {
  6081. constructor: THREE.LoadingMonitor,
  6082. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6083. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6084. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6085. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent
  6086. };
  6087. /**
  6088. * @author mrdoob / http://mrdoob.com/
  6089. */
  6090. THREE.GeometryLoader = function () {};
  6091. THREE.GeometryLoader.prototype = {
  6092. constructor: THREE.GeometryLoader,
  6093. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6094. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6095. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6096. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  6097. load: function ( url ) {
  6098. var scope = this;
  6099. var request = new XMLHttpRequest();
  6100. request.addEventListener( 'load', function ( event ) {
  6101. var response = scope.parse( JSON.parse( event.target.responseText ) );
  6102. scope.dispatchEvent( { type: 'load', content: response } );
  6103. }, false );
  6104. request.addEventListener( 'progress', function ( event ) {
  6105. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  6106. }, false );
  6107. request.addEventListener( 'error', function () {
  6108. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6109. }, false );
  6110. request.open( 'GET', url, true );
  6111. request.send( null );
  6112. },
  6113. parse: function ( json ) {
  6114. }
  6115. };
  6116. /**
  6117. * @author mrdoob / http://mrdoob.com/
  6118. */
  6119. THREE.MaterialLoader = function () {};
  6120. THREE.MaterialLoader.prototype = {
  6121. constructor: THREE.MaterialLoader,
  6122. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6123. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6124. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6125. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  6126. load: function ( url ) {
  6127. var scope = this;
  6128. var request = new XMLHttpRequest();
  6129. request.addEventListener( 'load', function ( event ) {
  6130. var response = scope.parse( JSON.parse( event.target.responseText ) );
  6131. scope.dispatchEvent( { type: 'load', content: response } );
  6132. }, false );
  6133. request.addEventListener( 'progress', function ( event ) {
  6134. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  6135. }, false );
  6136. request.addEventListener( 'error', function () {
  6137. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6138. }, false );
  6139. request.open( 'GET', url, true );
  6140. request.send( null );
  6141. },
  6142. parse: function ( json ) {
  6143. var material;
  6144. switch ( json.type ) {
  6145. case 'MeshBasicMaterial':
  6146. material = new THREE.MeshBasicMaterial( {
  6147. color: json.color,
  6148. opacity: json.opacity,
  6149. transparent: json.transparent,
  6150. wireframe: json.wireframe
  6151. } );
  6152. break;
  6153. case 'MeshLambertMaterial':
  6154. material = new THREE.MeshLambertMaterial( {
  6155. color: json.color,
  6156. ambient: json.ambient,
  6157. emissive: json.emissive,
  6158. opacity: json.opacity,
  6159. transparent: json.transparent,
  6160. wireframe: json.wireframe
  6161. } );
  6162. break;
  6163. case 'MeshPhongMaterial':
  6164. material = new THREE.MeshPhongMaterial( {
  6165. color: json.color,
  6166. ambient: json.ambient,
  6167. emissive: json.emissive,
  6168. specular: json.specular,
  6169. shininess: json.shininess,
  6170. opacity: json.opacity,
  6171. transparent: json.transparent,
  6172. wireframe: json.wireframe
  6173. } );
  6174. break;
  6175. case 'MeshNormalMaterial':
  6176. material = new THREE.MeshNormalMaterial( {
  6177. opacity: json.opacity,
  6178. transparent: json.transparent,
  6179. wireframe: json.wireframe
  6180. } );
  6181. break;
  6182. case 'MeshDepthMaterial':
  6183. material = new THREE.MeshDepthMaterial( {
  6184. opacity: json.opacity,
  6185. transparent: json.transparent,
  6186. wireframe: json.wireframe
  6187. } );
  6188. break;
  6189. }
  6190. return material;
  6191. }
  6192. };
  6193. /**
  6194. * @author alteredq / http://alteredqualia.com/
  6195. */
  6196. THREE.SceneLoader = function () {
  6197. this.onLoadStart = function () {};
  6198. this.onLoadProgress = function() {};
  6199. this.onLoadComplete = function () {};
  6200. this.callbackSync = function () {};
  6201. this.callbackProgress = function () {};
  6202. this.geometryHandlerMap = {};
  6203. this.hierarchyHandlerMap = {};
  6204. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6205. };
  6206. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  6207. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  6208. var scope = this;
  6209. var xhr = new XMLHttpRequest();
  6210. xhr.onreadystatechange = function () {
  6211. if ( xhr.readyState === 4 ) {
  6212. if ( xhr.status === 200 || xhr.status === 0 ) {
  6213. var json = JSON.parse( xhr.responseText );
  6214. scope.parse( json, callbackFinished, url );
  6215. } else {
  6216. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6217. }
  6218. }
  6219. };
  6220. xhr.open( "GET", url, true );
  6221. xhr.send( null );
  6222. };
  6223. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  6224. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6225. };
  6226. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  6227. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  6228. };
  6229. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  6230. var scope = this;
  6231. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6232. var geometry, material, camera, fog,
  6233. texture, images, color,
  6234. light, hex, intensity,
  6235. counter_models, counter_textures,
  6236. total_models, total_textures,
  6237. result;
  6238. var target_array = [];
  6239. var data = json;
  6240. // async geometry loaders
  6241. for ( var typeID in this.geometryHandlerMap ) {
  6242. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  6243. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6244. }
  6245. // async hierachy loaders
  6246. for ( var typeID in this.hierarchyHandlerMap ) {
  6247. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  6248. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  6249. }
  6250. counter_models = 0;
  6251. counter_textures = 0;
  6252. result = {
  6253. scene: new THREE.Scene(),
  6254. geometries: {},
  6255. face_materials: {},
  6256. materials: {},
  6257. textures: {},
  6258. objects: {},
  6259. cameras: {},
  6260. lights: {},
  6261. fogs: {},
  6262. empties: {},
  6263. groups: {}
  6264. };
  6265. if ( data.transform ) {
  6266. var position = data.transform.position,
  6267. rotation = data.transform.rotation,
  6268. scale = data.transform.scale;
  6269. if ( position )
  6270. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  6271. if ( rotation )
  6272. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  6273. if ( scale )
  6274. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  6275. if ( position || rotation || scale ) {
  6276. result.scene.updateMatrix();
  6277. result.scene.updateMatrixWorld();
  6278. }
  6279. }
  6280. function get_url( source_url, url_type ) {
  6281. if ( url_type == "relativeToHTML" ) {
  6282. return source_url;
  6283. } else {
  6284. return urlBase + "/" + source_url;
  6285. }
  6286. };
  6287. // toplevel loader function, delegates to handle_children
  6288. function handle_objects() {
  6289. handle_children( result.scene, data.objects );
  6290. }
  6291. // handle all the children from the loaded json and attach them to given parent
  6292. function handle_children( parent, children ) {
  6293. var mat, dst, pos, rot, scl, quat;
  6294. for ( var objID in children ) {
  6295. // check by id if child has already been handled,
  6296. // if not, create new object
  6297. if ( result.objects[ objID ] === undefined ) {
  6298. var objJSON = children[ objID ];
  6299. var object = null;
  6300. // meshes
  6301. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6302. if ( objJSON.loading === undefined ) {
  6303. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  6304. "position": 1, "rotation": 1, "scale" : 1,
  6305. "visible": 1, "children": 1, "userData": 1,
  6306. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  6307. var loaderParameters = {};
  6308. for ( var parType in objJSON ) {
  6309. if ( ! ( parType in reservedTypes ) ) {
  6310. loaderParameters[ parType ] = objJSON[ parType ];
  6311. }
  6312. }
  6313. material = result.materials[ objJSON.material ];
  6314. objJSON.loading = true;
  6315. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6316. // ColladaLoader
  6317. if ( loader.options ) {
  6318. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6319. // UTF8Loader
  6320. // OBJLoader
  6321. } else {
  6322. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6323. }
  6324. }
  6325. } else if ( objJSON.geometry !== undefined ) {
  6326. geometry = result.geometries[ objJSON.geometry ];
  6327. // geometry already loaded
  6328. if ( geometry ) {
  6329. var needsTangents = false;
  6330. material = result.materials[ objJSON.material ];
  6331. needsTangents = material instanceof THREE.ShaderMaterial;
  6332. pos = objJSON.position;
  6333. rot = objJSON.rotation;
  6334. scl = objJSON.scale;
  6335. mat = objJSON.matrix;
  6336. quat = objJSON.quaternion;
  6337. // use materials from the model file
  6338. // if there is no material specified in the object
  6339. if ( ! objJSON.material ) {
  6340. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6341. }
  6342. // use materials from the model file
  6343. // if there is just empty face material
  6344. // (must create new material as each model has its own face material)
  6345. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6346. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6347. }
  6348. if ( material instanceof THREE.MeshFaceMaterial ) {
  6349. for ( var i = 0; i < material.materials.length; i ++ ) {
  6350. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6351. }
  6352. }
  6353. if ( needsTangents ) {
  6354. geometry.computeTangents();
  6355. }
  6356. if ( objJSON.skin ) {
  6357. object = new THREE.SkinnedMesh( geometry, material );
  6358. } else if ( objJSON.morph ) {
  6359. object = new THREE.MorphAnimMesh( geometry, material );
  6360. if ( objJSON.duration !== undefined ) {
  6361. object.duration = objJSON.duration;
  6362. }
  6363. if ( objJSON.time !== undefined ) {
  6364. object.time = objJSON.time;
  6365. }
  6366. if ( objJSON.mirroredLoop !== undefined ) {
  6367. object.mirroredLoop = objJSON.mirroredLoop;
  6368. }
  6369. if ( material.morphNormals ) {
  6370. geometry.computeMorphNormals();
  6371. }
  6372. } else {
  6373. object = new THREE.Mesh( geometry, material );
  6374. }
  6375. object.name = objID;
  6376. if ( mat ) {
  6377. object.matrixAutoUpdate = false;
  6378. object.matrix.set(
  6379. mat[0], mat[1], mat[2], mat[3],
  6380. mat[4], mat[5], mat[6], mat[7],
  6381. mat[8], mat[9], mat[10], mat[11],
  6382. mat[12], mat[13], mat[14], mat[15]
  6383. );
  6384. } else {
  6385. object.position.set( pos[0], pos[1], pos[2] );
  6386. if ( quat ) {
  6387. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6388. object.useQuaternion = true;
  6389. } else {
  6390. object.rotation.set( rot[0], rot[1], rot[2] );
  6391. }
  6392. object.scale.set( scl[0], scl[1], scl[2] );
  6393. }
  6394. object.visible = objJSON.visible;
  6395. object.castShadow = objJSON.castShadow;
  6396. object.receiveShadow = objJSON.receiveShadow;
  6397. parent.add( object );
  6398. result.objects[ objID ] = object;
  6399. }
  6400. // lights
  6401. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6402. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6403. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6404. if ( objJSON.type === "DirectionalLight" ) {
  6405. pos = objJSON.direction;
  6406. light = new THREE.DirectionalLight( hex, intensity );
  6407. light.position.set( pos[0], pos[1], pos[2] );
  6408. if ( objJSON.target ) {
  6409. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6410. // kill existing default target
  6411. // otherwise it gets added to scene when parent gets added
  6412. light.target = null;
  6413. }
  6414. } else if ( objJSON.type === "PointLight" ) {
  6415. pos = objJSON.position;
  6416. dst = objJSON.distance;
  6417. light = new THREE.PointLight( hex, intensity, dst );
  6418. light.position.set( pos[0], pos[1], pos[2] );
  6419. } else if ( objJSON.type === "AmbientLight" ) {
  6420. light = new THREE.AmbientLight( hex );
  6421. }
  6422. parent.add( light );
  6423. light.name = objID;
  6424. result.lights[ objID ] = light;
  6425. result.objects[ objID ] = light;
  6426. // cameras
  6427. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6428. pos = objJSON.position;
  6429. rot = objJSON.rotation;
  6430. quat = objJSON.quaternion;
  6431. if ( objJSON.type === "PerspectiveCamera" ) {
  6432. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6433. } else if ( objJSON.type === "OrthographicCamera" ) {
  6434. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6435. }
  6436. camera.name = objID;
  6437. camera.position.set( pos[0], pos[1], pos[2] );
  6438. if ( quat !== undefined ) {
  6439. camera.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6440. camera.useQuaternion = true;
  6441. } else if ( rot !== undefined ) {
  6442. camera.rotation.set( rot[0], rot[1], rot[2] );
  6443. }
  6444. parent.add( camera );
  6445. result.cameras[ objID ] = camera;
  6446. result.objects[ objID ] = camera;
  6447. // pure Object3D
  6448. } else {
  6449. pos = objJSON.position;
  6450. rot = objJSON.rotation;
  6451. scl = objJSON.scale;
  6452. quat = objJSON.quaternion;
  6453. object = new THREE.Object3D();
  6454. object.name = objID;
  6455. object.position.set( pos[0], pos[1], pos[2] );
  6456. if ( quat ) {
  6457. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6458. object.useQuaternion = true;
  6459. } else {
  6460. object.rotation.set( rot[0], rot[1], rot[2] );
  6461. }
  6462. object.scale.set( scl[0], scl[1], scl[2] );
  6463. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6464. parent.add( object );
  6465. result.objects[ objID ] = object;
  6466. result.empties[ objID ] = object;
  6467. }
  6468. if ( object ) {
  6469. if ( objJSON.userData !== undefined ) {
  6470. for ( var key in objJSON.userData ) {
  6471. var value = objJSON.userData[ key ];
  6472. object.userData[ key ] = value;
  6473. }
  6474. }
  6475. if ( objJSON.groups !== undefined ) {
  6476. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6477. var groupID = objJSON.groups[ i ];
  6478. if ( result.groups[ groupID ] === undefined ) {
  6479. result.groups[ groupID ] = [];
  6480. }
  6481. result.groups[ groupID ].push( objID );
  6482. }
  6483. }
  6484. if ( objJSON.children !== undefined ) {
  6485. handle_children( object, objJSON.children );
  6486. }
  6487. }
  6488. }
  6489. }
  6490. };
  6491. function handle_mesh( geo, mat, id ) {
  6492. result.geometries[ id ] = geo;
  6493. result.face_materials[ id ] = mat;
  6494. handle_objects();
  6495. };
  6496. function handle_hierarchy( node, id, parent, material, obj ) {
  6497. var p = obj.position;
  6498. var r = obj.rotation;
  6499. var q = obj.quaternion;
  6500. var s = obj.scale;
  6501. node.position.set( p[0], p[1], p[2] );
  6502. if ( q ) {
  6503. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6504. node.useQuaternion = true;
  6505. } else {
  6506. node.rotation.set( r[0], r[1], r[2] );
  6507. }
  6508. node.scale.set( s[0], s[1], s[2] );
  6509. // override children materials
  6510. // if object material was specified in JSON explicitly
  6511. if ( material ) {
  6512. node.traverse( function ( child ) {
  6513. child.material = material;
  6514. } );
  6515. }
  6516. // override children visibility
  6517. // with root node visibility as specified in JSON
  6518. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6519. node.traverse( function ( child ) {
  6520. child.visible = visible;
  6521. } );
  6522. parent.add( node );
  6523. node.name = id;
  6524. result.objects[ id ] = node;
  6525. handle_objects();
  6526. };
  6527. function create_callback_geometry( id ) {
  6528. return function ( geo, mat ) {
  6529. geo.name = id;
  6530. handle_mesh( geo, mat, id );
  6531. counter_models -= 1;
  6532. scope.onLoadComplete();
  6533. async_callback_gate();
  6534. }
  6535. };
  6536. function create_callback_hierachy( id, parent, material, obj ) {
  6537. return function ( event ) {
  6538. var result;
  6539. // loaders which use EventDispatcher
  6540. if ( event.content ) {
  6541. result = event.content;
  6542. // ColladaLoader
  6543. } else if ( event.dae ) {
  6544. result = event.scene;
  6545. // UTF8Loader
  6546. } else {
  6547. result = event;
  6548. }
  6549. handle_hierarchy( result, id, parent, material, obj );
  6550. counter_models -= 1;
  6551. scope.onLoadComplete();
  6552. async_callback_gate();
  6553. }
  6554. };
  6555. function create_callback_embed( id ) {
  6556. return function ( geo, mat ) {
  6557. geo.name = id;
  6558. result.geometries[ id ] = geo;
  6559. result.face_materials[ id ] = mat;
  6560. }
  6561. };
  6562. function async_callback_gate() {
  6563. var progress = {
  6564. totalModels : total_models,
  6565. totalTextures : total_textures,
  6566. loadedModels : total_models - counter_models,
  6567. loadedTextures : total_textures - counter_textures
  6568. };
  6569. scope.callbackProgress( progress, result );
  6570. scope.onLoadProgress();
  6571. if ( counter_models === 0 && counter_textures === 0 ) {
  6572. finalize();
  6573. callbackFinished( result );
  6574. }
  6575. };
  6576. function finalize() {
  6577. // take care of targets which could be asynchronously loaded objects
  6578. for ( var i = 0; i < target_array.length; i ++ ) {
  6579. var ta = target_array[ i ];
  6580. var target = result.objects[ ta.targetName ];
  6581. if ( target ) {
  6582. ta.object.target = target;
  6583. } else {
  6584. // if there was error and target of specified name doesn't exist in the scene file
  6585. // create instead dummy target
  6586. // (target must be added to scene explicitly as parent is already added)
  6587. ta.object.target = new THREE.Object3D();
  6588. result.scene.add( ta.object.target );
  6589. }
  6590. ta.object.target.userData.targetInverse = ta.object;
  6591. }
  6592. };
  6593. var callbackTexture = function ( count ) {
  6594. counter_textures -= count;
  6595. async_callback_gate();
  6596. scope.onLoadComplete();
  6597. };
  6598. // must use this instead of just directly calling callbackTexture
  6599. // because of closure in the calling context loop
  6600. var generateTextureCallback = function ( count ) {
  6601. return function () {
  6602. callbackTexture( count );
  6603. };
  6604. };
  6605. // first go synchronous elements
  6606. // fogs
  6607. var fogID, fogJSON;
  6608. for ( fogID in data.fogs ) {
  6609. fogJSON = data.fogs[ fogID ];
  6610. if ( fogJSON.type === "linear" ) {
  6611. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6612. } else if ( fogJSON.type === "exp2" ) {
  6613. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6614. }
  6615. color = fogJSON.color;
  6616. fog.color.setRGB( color[0], color[1], color[2] );
  6617. result.fogs[ fogID ] = fog;
  6618. }
  6619. // now come potentially asynchronous elements
  6620. // geometries
  6621. // count how many geometries will be loaded asynchronously
  6622. var geoID, geoJSON;
  6623. for ( geoID in data.geometries ) {
  6624. geoJSON = data.geometries[ geoID ];
  6625. if ( geoJSON.type in this.geometryHandlerMap ) {
  6626. counter_models += 1;
  6627. scope.onLoadStart();
  6628. }
  6629. }
  6630. // count how many hierarchies will be loaded asynchronously
  6631. var objID, objJSON;
  6632. for ( objID in data.objects ) {
  6633. objJSON = data.objects[ objID ];
  6634. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6635. counter_models += 1;
  6636. scope.onLoadStart();
  6637. }
  6638. }
  6639. total_models = counter_models;
  6640. for ( geoID in data.geometries ) {
  6641. geoJSON = data.geometries[ geoID ];
  6642. if ( geoJSON.type === "cube" ) {
  6643. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6644. geometry.name = geoID;
  6645. result.geometries[ geoID ] = geometry;
  6646. } else if ( geoJSON.type === "plane" ) {
  6647. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6648. geometry.name = geoID;
  6649. result.geometries[ geoID ] = geometry;
  6650. } else if ( geoJSON.type === "sphere" ) {
  6651. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6652. geometry.name = geoID;
  6653. result.geometries[ geoID ] = geometry;
  6654. } else if ( geoJSON.type === "cylinder" ) {
  6655. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6656. geometry.name = geoID;
  6657. result.geometries[ geoID ] = geometry;
  6658. } else if ( geoJSON.type === "torus" ) {
  6659. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6660. geometry.name = geoID;
  6661. result.geometries[ geoID ] = geometry;
  6662. } else if ( geoJSON.type === "icosahedron" ) {
  6663. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6664. geometry.name = geoID;
  6665. result.geometries[ geoID ] = geometry;
  6666. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6667. var loaderParameters = {};
  6668. for ( var parType in geoJSON ) {
  6669. if ( parType !== "type" && parType !== "url" ) {
  6670. loaderParameters[ parType ] = geoJSON[ parType ];
  6671. }
  6672. }
  6673. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6674. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6675. } else if ( geoJSON.type === "embedded" ) {
  6676. var modelJson = data.embeds[ geoJSON.id ],
  6677. texture_path = "";
  6678. // pass metadata along to jsonLoader so it knows the format version
  6679. modelJson.metadata = data.metadata;
  6680. if ( modelJson ) {
  6681. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6682. var model = jsonLoader.parse( modelJson, texture_path );
  6683. create_callback_embed( geoID )( model.geometry, model.materials );
  6684. }
  6685. }
  6686. }
  6687. // textures
  6688. // count how many textures will be loaded asynchronously
  6689. var textureID, textureJSON;
  6690. for ( textureID in data.textures ) {
  6691. textureJSON = data.textures[ textureID ];
  6692. if ( textureJSON.url instanceof Array ) {
  6693. counter_textures += textureJSON.url.length;
  6694. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6695. scope.onLoadStart();
  6696. }
  6697. } else {
  6698. counter_textures += 1;
  6699. scope.onLoadStart();
  6700. }
  6701. }
  6702. total_textures = counter_textures;
  6703. for ( textureID in data.textures ) {
  6704. textureJSON = data.textures[ textureID ];
  6705. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6706. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6707. }
  6708. if ( textureJSON.url instanceof Array ) {
  6709. var count = textureJSON.url.length;
  6710. var url_array = [];
  6711. for( var i = 0; i < count; i ++ ) {
  6712. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6713. }
  6714. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  6715. if ( isCompressed ) {
  6716. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6717. } else {
  6718. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6719. }
  6720. } else {
  6721. var isCompressed = /\.dds$/i.test( textureJSON.url );
  6722. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6723. var textureCallback = generateTextureCallback( 1 );
  6724. if ( isCompressed ) {
  6725. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6726. } else {
  6727. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6728. }
  6729. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6730. texture.minFilter = THREE[ textureJSON.minFilter ];
  6731. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6732. texture.magFilter = THREE[ textureJSON.magFilter ];
  6733. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6734. if ( textureJSON.repeat ) {
  6735. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6736. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6737. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6738. }
  6739. if ( textureJSON.offset ) {
  6740. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6741. }
  6742. // handle wrap after repeat so that default repeat can be overriden
  6743. if ( textureJSON.wrap ) {
  6744. var wrapMap = {
  6745. "repeat" : THREE.RepeatWrapping,
  6746. "mirror" : THREE.MirroredRepeatWrapping
  6747. }
  6748. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6749. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6750. }
  6751. }
  6752. result.textures[ textureID ] = texture;
  6753. }
  6754. // materials
  6755. var matID, matJSON;
  6756. var parID;
  6757. for ( matID in data.materials ) {
  6758. matJSON = data.materials[ matID ];
  6759. for ( parID in matJSON.parameters ) {
  6760. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6761. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6762. } else if ( parID === "shading" ) {
  6763. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6764. } else if ( parID === "side" ) {
  6765. if ( matJSON.parameters[ parID ] == "double" ) {
  6766. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6767. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6768. matJSON.parameters[ parID ] = THREE.BackSide;
  6769. } else {
  6770. matJSON.parameters[ parID ] = THREE.FrontSide;
  6771. }
  6772. } else if ( parID === "blending" ) {
  6773. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6774. } else if ( parID === "combine" ) {
  6775. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6776. } else if ( parID === "vertexColors" ) {
  6777. if ( matJSON.parameters[ parID ] == "face" ) {
  6778. matJSON.parameters[ parID ] = THREE.FaceColors;
  6779. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6780. } else if ( matJSON.parameters[ parID ] ) {
  6781. matJSON.parameters[ parID ] = THREE.VertexColors;
  6782. }
  6783. } else if ( parID === "wrapRGB" ) {
  6784. var v3 = matJSON.parameters[ parID ];
  6785. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6786. }
  6787. }
  6788. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6789. matJSON.parameters.transparent = true;
  6790. }
  6791. if ( matJSON.parameters.normalMap ) {
  6792. var shader = THREE.ShaderLib[ "normalmap" ];
  6793. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6794. var diffuse = matJSON.parameters.color;
  6795. var specular = matJSON.parameters.specular;
  6796. var ambient = matJSON.parameters.ambient;
  6797. var shininess = matJSON.parameters.shininess;
  6798. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6799. if ( matJSON.parameters.normalScale ) {
  6800. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6801. }
  6802. if ( matJSON.parameters.map ) {
  6803. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6804. uniforms[ "enableDiffuse" ].value = true;
  6805. }
  6806. if ( matJSON.parameters.envMap ) {
  6807. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6808. uniforms[ "enableReflection" ].value = true;
  6809. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6810. }
  6811. if ( matJSON.parameters.lightMap ) {
  6812. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6813. uniforms[ "enableAO" ].value = true;
  6814. }
  6815. if ( matJSON.parameters.specularMap ) {
  6816. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6817. uniforms[ "enableSpecular" ].value = true;
  6818. }
  6819. if ( matJSON.parameters.displacementMap ) {
  6820. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6821. uniforms[ "enableDisplacement" ].value = true;
  6822. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6823. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6824. }
  6825. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6826. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6827. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6828. uniforms[ "uShininess" ].value = shininess;
  6829. if ( matJSON.parameters.opacity ) {
  6830. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6831. }
  6832. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6833. material = new THREE.ShaderMaterial( parameters );
  6834. } else {
  6835. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6836. }
  6837. material.name = matID;
  6838. result.materials[ matID ] = material;
  6839. }
  6840. // second pass through all materials to initialize MeshFaceMaterials
  6841. // that could be referring to other materials out of order
  6842. for ( matID in data.materials ) {
  6843. matJSON = data.materials[ matID ];
  6844. if ( matJSON.parameters.materials ) {
  6845. var materialArray = [];
  6846. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6847. var label = matJSON.parameters.materials[ i ];
  6848. materialArray.push( result.materials[ label ] );
  6849. }
  6850. result.materials[ matID ].materials = materialArray;
  6851. }
  6852. }
  6853. // objects ( synchronous init of procedural primitives )
  6854. handle_objects();
  6855. // defaults
  6856. if ( result.cameras && data.defaults.camera ) {
  6857. result.currentCamera = result.cameras[ data.defaults.camera ];
  6858. }
  6859. if ( result.fogs && data.defaults.fog ) {
  6860. result.scene.fog = result.fogs[ data.defaults.fog ];
  6861. }
  6862. // synchronous callback
  6863. scope.callbackSync( result );
  6864. // just in case there are no async elements
  6865. async_callback_gate();
  6866. };
  6867. /**
  6868. * @author mrdoob / http://mrdoob.com/
  6869. */
  6870. THREE.TextureLoader = function () {
  6871. this.crossOrigin = null;
  6872. };
  6873. THREE.TextureLoader.prototype = {
  6874. constructor: THREE.TextureLoader,
  6875. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6876. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6877. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6878. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  6879. load: function ( url ) {
  6880. var scope = this;
  6881. var image = new Image();
  6882. image.addEventListener( 'load', function () {
  6883. var texture = new THREE.Texture( image );
  6884. texture.needsUpdate = true;
  6885. scope.dispatchEvent( { type: 'load', content: texture } );
  6886. }, false );
  6887. image.addEventListener( 'error', function () {
  6888. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6889. }, false );
  6890. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6891. image.src = url;
  6892. }
  6893. };
  6894. /**
  6895. * @author mrdoob / http://mrdoob.com/
  6896. * @author alteredq / http://alteredqualia.com/
  6897. */
  6898. THREE.Material = function () {
  6899. this.id = THREE.MaterialIdCount ++;
  6900. this.name = '';
  6901. this.side = THREE.FrontSide;
  6902. this.opacity = 1;
  6903. this.transparent = false;
  6904. this.blending = THREE.NormalBlending;
  6905. this.blendSrc = THREE.SrcAlphaFactor;
  6906. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6907. this.blendEquation = THREE.AddEquation;
  6908. this.depthTest = true;
  6909. this.depthWrite = true;
  6910. this.polygonOffset = false;
  6911. this.polygonOffsetFactor = 0;
  6912. this.polygonOffsetUnits = 0;
  6913. this.alphaTest = 0;
  6914. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6915. this.visible = true;
  6916. this.needsUpdate = true;
  6917. };
  6918. THREE.Material.prototype = {
  6919. constructor: THREE.Material,
  6920. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  6921. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  6922. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  6923. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  6924. setValues: function ( values ) {
  6925. if ( values === undefined ) return;
  6926. for ( var key in values ) {
  6927. var newValue = values[ key ];
  6928. if ( newValue === undefined ) {
  6929. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6930. continue;
  6931. }
  6932. if ( key in this ) {
  6933. var currentValue = this[ key ];
  6934. if ( currentValue instanceof THREE.Color ) {
  6935. currentValue.set( newValue );
  6936. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6937. currentValue.copy( newValue );
  6938. } else {
  6939. this[ key ] = newValue;
  6940. }
  6941. }
  6942. }
  6943. },
  6944. clone: function ( material ) {
  6945. if ( material === undefined ) material = new THREE.Material();
  6946. material.name = this.name;
  6947. material.side = this.side;
  6948. material.opacity = this.opacity;
  6949. material.transparent = this.transparent;
  6950. material.blending = this.blending;
  6951. material.blendSrc = this.blendSrc;
  6952. material.blendDst = this.blendDst;
  6953. material.blendEquation = this.blendEquation;
  6954. material.depthTest = this.depthTest;
  6955. material.depthWrite = this.depthWrite;
  6956. material.polygonOffset = this.polygonOffset;
  6957. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6958. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6959. material.alphaTest = this.alphaTest;
  6960. material.overdraw = this.overdraw;
  6961. material.visible = this.visible;
  6962. return material;
  6963. },
  6964. dispose: function () {
  6965. this.dispatchEvent( { type: 'dispose' } );
  6966. }
  6967. };
  6968. THREE.MaterialIdCount = 0;
  6969. /**
  6970. * @author mrdoob / http://mrdoob.com/
  6971. * @author alteredq / http://alteredqualia.com/
  6972. *
  6973. * parameters = {
  6974. * color: <hex>,
  6975. * opacity: <float>,
  6976. *
  6977. * blending: THREE.NormalBlending,
  6978. * depthTest: <bool>,
  6979. * depthWrite: <bool>,
  6980. *
  6981. * linewidth: <float>,
  6982. * linecap: "round",
  6983. * linejoin: "round",
  6984. *
  6985. * vertexColors: <bool>
  6986. *
  6987. * fog: <bool>
  6988. * }
  6989. */
  6990. THREE.LineBasicMaterial = function ( parameters ) {
  6991. THREE.Material.call( this );
  6992. this.color = new THREE.Color( 0xffffff );
  6993. this.linewidth = 1;
  6994. this.linecap = 'round';
  6995. this.linejoin = 'round';
  6996. this.vertexColors = false;
  6997. this.fog = true;
  6998. this.setValues( parameters );
  6999. };
  7000. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7001. THREE.LineBasicMaterial.prototype.clone = function () {
  7002. var material = new THREE.LineBasicMaterial();
  7003. THREE.Material.prototype.clone.call( this, material );
  7004. material.color.copy( this.color );
  7005. material.linewidth = this.linewidth;
  7006. material.linecap = this.linecap;
  7007. material.linejoin = this.linejoin;
  7008. material.vertexColors = this.vertexColors;
  7009. material.fog = this.fog;
  7010. return material;
  7011. };
  7012. /**
  7013. * @author alteredq / http://alteredqualia.com/
  7014. *
  7015. * parameters = {
  7016. * color: <hex>,
  7017. * opacity: <float>,
  7018. *
  7019. * blending: THREE.NormalBlending,
  7020. * depthTest: <bool>,
  7021. * depthWrite: <bool>,
  7022. *
  7023. * linewidth: <float>,
  7024. *
  7025. * scale: <float>,
  7026. * dashSize: <float>,
  7027. * gapSize: <float>,
  7028. *
  7029. * vertexColors: <bool>
  7030. *
  7031. * fog: <bool>
  7032. * }
  7033. */
  7034. THREE.LineDashedMaterial = function ( parameters ) {
  7035. THREE.Material.call( this );
  7036. this.color = new THREE.Color( 0xffffff );
  7037. this.linewidth = 1;
  7038. this.scale = 1;
  7039. this.dashSize = 3;
  7040. this.gapSize = 1;
  7041. this.vertexColors = false;
  7042. this.fog = true;
  7043. this.setValues( parameters );
  7044. };
  7045. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7046. THREE.LineDashedMaterial.prototype.clone = function () {
  7047. var material = new THREE.LineDashedMaterial();
  7048. THREE.Material.prototype.clone.call( this, material );
  7049. material.color.copy( this.color );
  7050. material.linewidth = this.linewidth;
  7051. material.scale = this.scale;
  7052. material.dashSize = this.dashSize;
  7053. material.gapSize = this.gapSize;
  7054. material.vertexColors = this.vertexColors;
  7055. material.fog = this.fog;
  7056. return material;
  7057. };
  7058. /**
  7059. * @author mrdoob / http://mrdoob.com/
  7060. * @author alteredq / http://alteredqualia.com/
  7061. *
  7062. * parameters = {
  7063. * color: <hex>,
  7064. * opacity: <float>,
  7065. * map: new THREE.Texture( <Image> ),
  7066. *
  7067. * lightMap: new THREE.Texture( <Image> ),
  7068. *
  7069. * specularMap: new THREE.Texture( <Image> ),
  7070. *
  7071. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7072. * combine: THREE.Multiply,
  7073. * reflectivity: <float>,
  7074. * refractionRatio: <float>,
  7075. *
  7076. * shading: THREE.SmoothShading,
  7077. * blending: THREE.NormalBlending,
  7078. * depthTest: <bool>,
  7079. * depthWrite: <bool>,
  7080. *
  7081. * wireframe: <boolean>,
  7082. * wireframeLinewidth: <float>,
  7083. *
  7084. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7085. *
  7086. * skinning: <bool>,
  7087. * morphTargets: <bool>,
  7088. *
  7089. * fog: <bool>
  7090. * }
  7091. */
  7092. THREE.MeshBasicMaterial = function ( parameters ) {
  7093. THREE.Material.call( this );
  7094. this.color = new THREE.Color( 0xffffff ); // emissive
  7095. this.map = null;
  7096. this.lightMap = null;
  7097. this.specularMap = null;
  7098. this.envMap = null;
  7099. this.combine = THREE.MultiplyOperation;
  7100. this.reflectivity = 1;
  7101. this.refractionRatio = 0.98;
  7102. this.fog = true;
  7103. this.shading = THREE.SmoothShading;
  7104. this.wireframe = false;
  7105. this.wireframeLinewidth = 1;
  7106. this.wireframeLinecap = 'round';
  7107. this.wireframeLinejoin = 'round';
  7108. this.vertexColors = THREE.NoColors;
  7109. this.skinning = false;
  7110. this.morphTargets = false;
  7111. this.setValues( parameters );
  7112. };
  7113. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7114. THREE.MeshBasicMaterial.prototype.clone = function () {
  7115. var material = new THREE.MeshBasicMaterial();
  7116. THREE.Material.prototype.clone.call( this, material );
  7117. material.color.copy( this.color );
  7118. material.map = this.map;
  7119. material.lightMap = this.lightMap;
  7120. material.specularMap = this.specularMap;
  7121. material.envMap = this.envMap;
  7122. material.combine = this.combine;
  7123. material.reflectivity = this.reflectivity;
  7124. material.refractionRatio = this.refractionRatio;
  7125. material.fog = this.fog;
  7126. material.shading = this.shading;
  7127. material.wireframe = this.wireframe;
  7128. material.wireframeLinewidth = this.wireframeLinewidth;
  7129. material.wireframeLinecap = this.wireframeLinecap;
  7130. material.wireframeLinejoin = this.wireframeLinejoin;
  7131. material.vertexColors = this.vertexColors;
  7132. material.skinning = this.skinning;
  7133. material.morphTargets = this.morphTargets;
  7134. return material;
  7135. };
  7136. /**
  7137. * @author mrdoob / http://mrdoob.com/
  7138. * @author alteredq / http://alteredqualia.com/
  7139. *
  7140. * parameters = {
  7141. * color: <hex>,
  7142. * ambient: <hex>,
  7143. * emissive: <hex>,
  7144. * opacity: <float>,
  7145. *
  7146. * map: new THREE.Texture( <Image> ),
  7147. *
  7148. * lightMap: new THREE.Texture( <Image> ),
  7149. *
  7150. * specularMap: new THREE.Texture( <Image> ),
  7151. *
  7152. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7153. * combine: THREE.Multiply,
  7154. * reflectivity: <float>,
  7155. * refractionRatio: <float>,
  7156. *
  7157. * shading: THREE.SmoothShading,
  7158. * blending: THREE.NormalBlending,
  7159. * depthTest: <bool>,
  7160. * depthWrite: <bool>,
  7161. *
  7162. * wireframe: <boolean>,
  7163. * wireframeLinewidth: <float>,
  7164. *
  7165. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7166. *
  7167. * skinning: <bool>,
  7168. * morphTargets: <bool>,
  7169. * morphNormals: <bool>,
  7170. *
  7171. * fog: <bool>
  7172. * }
  7173. */
  7174. THREE.MeshLambertMaterial = function ( parameters ) {
  7175. THREE.Material.call( this );
  7176. this.color = new THREE.Color( 0xffffff ); // diffuse
  7177. this.ambient = new THREE.Color( 0xffffff );
  7178. this.emissive = new THREE.Color( 0x000000 );
  7179. this.wrapAround = false;
  7180. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7181. this.map = null;
  7182. this.lightMap = null;
  7183. this.specularMap = null;
  7184. this.envMap = null;
  7185. this.combine = THREE.MultiplyOperation;
  7186. this.reflectivity = 1;
  7187. this.refractionRatio = 0.98;
  7188. this.fog = true;
  7189. this.shading = THREE.SmoothShading;
  7190. this.wireframe = false;
  7191. this.wireframeLinewidth = 1;
  7192. this.wireframeLinecap = 'round';
  7193. this.wireframeLinejoin = 'round';
  7194. this.vertexColors = THREE.NoColors;
  7195. this.skinning = false;
  7196. this.morphTargets = false;
  7197. this.morphNormals = false;
  7198. this.setValues( parameters );
  7199. };
  7200. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7201. THREE.MeshLambertMaterial.prototype.clone = function () {
  7202. var material = new THREE.MeshLambertMaterial();
  7203. THREE.Material.prototype.clone.call( this, material );
  7204. material.color.copy( this.color );
  7205. material.ambient.copy( this.ambient );
  7206. material.emissive.copy( this.emissive );
  7207. material.wrapAround = this.wrapAround;
  7208. material.wrapRGB.copy( this.wrapRGB );
  7209. material.map = this.map;
  7210. material.lightMap = this.lightMap;
  7211. material.specularMap = this.specularMap;
  7212. material.envMap = this.envMap;
  7213. material.combine = this.combine;
  7214. material.reflectivity = this.reflectivity;
  7215. material.refractionRatio = this.refractionRatio;
  7216. material.fog = this.fog;
  7217. material.shading = this.shading;
  7218. material.wireframe = this.wireframe;
  7219. material.wireframeLinewidth = this.wireframeLinewidth;
  7220. material.wireframeLinecap = this.wireframeLinecap;
  7221. material.wireframeLinejoin = this.wireframeLinejoin;
  7222. material.vertexColors = this.vertexColors;
  7223. material.skinning = this.skinning;
  7224. material.morphTargets = this.morphTargets;
  7225. material.morphNormals = this.morphNormals;
  7226. return material;
  7227. };
  7228. /**
  7229. * @author mrdoob / http://mrdoob.com/
  7230. * @author alteredq / http://alteredqualia.com/
  7231. *
  7232. * parameters = {
  7233. * color: <hex>,
  7234. * ambient: <hex>,
  7235. * emissive: <hex>,
  7236. * specular: <hex>,
  7237. * shininess: <float>,
  7238. * opacity: <float>,
  7239. *
  7240. * map: new THREE.Texture( <Image> ),
  7241. *
  7242. * lightMap: new THREE.Texture( <Image> ),
  7243. *
  7244. * bumpMap: new THREE.Texture( <Image> ),
  7245. * bumpScale: <float>,
  7246. *
  7247. * normalMap: new THREE.Texture( <Image> ),
  7248. * normalScale: <Vector2>,
  7249. *
  7250. * specularMap: new THREE.Texture( <Image> ),
  7251. *
  7252. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7253. * combine: THREE.Multiply,
  7254. * reflectivity: <float>,
  7255. * refractionRatio: <float>,
  7256. *
  7257. * shading: THREE.SmoothShading,
  7258. * blending: THREE.NormalBlending,
  7259. * depthTest: <bool>,
  7260. * depthWrite: <bool>,
  7261. *
  7262. * wireframe: <boolean>,
  7263. * wireframeLinewidth: <float>,
  7264. *
  7265. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7266. *
  7267. * skinning: <bool>,
  7268. * morphTargets: <bool>,
  7269. * morphNormals: <bool>,
  7270. *
  7271. * fog: <bool>
  7272. * }
  7273. */
  7274. THREE.MeshPhongMaterial = function ( parameters ) {
  7275. THREE.Material.call( this );
  7276. this.color = new THREE.Color( 0xffffff ); // diffuse
  7277. this.ambient = new THREE.Color( 0xffffff );
  7278. this.emissive = new THREE.Color( 0x000000 );
  7279. this.specular = new THREE.Color( 0x111111 );
  7280. this.shininess = 30;
  7281. this.metal = false;
  7282. this.perPixel = true;
  7283. this.wrapAround = false;
  7284. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7285. this.map = null;
  7286. this.lightMap = null;
  7287. this.bumpMap = null;
  7288. this.bumpScale = 1;
  7289. this.normalMap = null;
  7290. this.normalScale = new THREE.Vector2( 1, 1 );
  7291. this.specularMap = null;
  7292. this.envMap = null;
  7293. this.combine = THREE.MultiplyOperation;
  7294. this.reflectivity = 1;
  7295. this.refractionRatio = 0.98;
  7296. this.fog = true;
  7297. this.shading = THREE.SmoothShading;
  7298. this.wireframe = false;
  7299. this.wireframeLinewidth = 1;
  7300. this.wireframeLinecap = 'round';
  7301. this.wireframeLinejoin = 'round';
  7302. this.vertexColors = THREE.NoColors;
  7303. this.skinning = false;
  7304. this.morphTargets = false;
  7305. this.morphNormals = false;
  7306. this.setValues( parameters );
  7307. };
  7308. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7309. THREE.MeshPhongMaterial.prototype.clone = function () {
  7310. var material = new THREE.MeshPhongMaterial();
  7311. THREE.Material.prototype.clone.call( this, material );
  7312. material.color.copy( this.color );
  7313. material.ambient.copy( this.ambient );
  7314. material.emissive.copy( this.emissive );
  7315. material.specular.copy( this.specular );
  7316. material.shininess = this.shininess;
  7317. material.metal = this.metal;
  7318. material.perPixel = this.perPixel;
  7319. material.wrapAround = this.wrapAround;
  7320. material.wrapRGB.copy( this.wrapRGB );
  7321. material.map = this.map;
  7322. material.lightMap = this.lightMap;
  7323. material.bumpMap = this.bumpMap;
  7324. material.bumpScale = this.bumpScale;
  7325. material.normalMap = this.normalMap;
  7326. material.normalScale.copy( this.normalScale );
  7327. material.specularMap = this.specularMap;
  7328. material.envMap = this.envMap;
  7329. material.combine = this.combine;
  7330. material.reflectivity = this.reflectivity;
  7331. material.refractionRatio = this.refractionRatio;
  7332. material.fog = this.fog;
  7333. material.shading = this.shading;
  7334. material.wireframe = this.wireframe;
  7335. material.wireframeLinewidth = this.wireframeLinewidth;
  7336. material.wireframeLinecap = this.wireframeLinecap;
  7337. material.wireframeLinejoin = this.wireframeLinejoin;
  7338. material.vertexColors = this.vertexColors;
  7339. material.skinning = this.skinning;
  7340. material.morphTargets = this.morphTargets;
  7341. material.morphNormals = this.morphNormals;
  7342. return material;
  7343. };
  7344. /**
  7345. * @author mrdoob / http://mrdoob.com/
  7346. * @author alteredq / http://alteredqualia.com/
  7347. *
  7348. * parameters = {
  7349. * opacity: <float>,
  7350. *
  7351. * blending: THREE.NormalBlending,
  7352. * depthTest: <bool>,
  7353. * depthWrite: <bool>,
  7354. *
  7355. * wireframe: <boolean>,
  7356. * wireframeLinewidth: <float>
  7357. * }
  7358. */
  7359. THREE.MeshDepthMaterial = function ( parameters ) {
  7360. THREE.Material.call( this );
  7361. this.wireframe = false;
  7362. this.wireframeLinewidth = 1;
  7363. this.setValues( parameters );
  7364. };
  7365. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7366. THREE.MeshDepthMaterial.prototype.clone = function () {
  7367. var material = new THREE.MeshDepthMaterial();
  7368. THREE.Material.prototype.clone.call( this, material );
  7369. material.wireframe = this.wireframe;
  7370. material.wireframeLinewidth = this.wireframeLinewidth;
  7371. return material;
  7372. };
  7373. /**
  7374. * @author mrdoob / http://mrdoob.com/
  7375. *
  7376. * parameters = {
  7377. * opacity: <float>,
  7378. *
  7379. * shading: THREE.FlatShading,
  7380. * blending: THREE.NormalBlending,
  7381. * depthTest: <bool>,
  7382. * depthWrite: <bool>,
  7383. *
  7384. * wireframe: <boolean>,
  7385. * wireframeLinewidth: <float>
  7386. * }
  7387. */
  7388. THREE.MeshNormalMaterial = function ( parameters ) {
  7389. THREE.Material.call( this, parameters );
  7390. this.shading = THREE.FlatShading;
  7391. this.wireframe = false;
  7392. this.wireframeLinewidth = 1;
  7393. this.morphTargets = false;
  7394. this.setValues( parameters );
  7395. };
  7396. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7397. THREE.MeshNormalMaterial.prototype.clone = function () {
  7398. var material = new THREE.MeshNormalMaterial();
  7399. THREE.Material.prototype.clone.call( this, material );
  7400. material.shading = this.shading;
  7401. material.wireframe = this.wireframe;
  7402. material.wireframeLinewidth = this.wireframeLinewidth;
  7403. return material;
  7404. };
  7405. /**
  7406. * @author mrdoob / http://mrdoob.com/
  7407. */
  7408. THREE.MeshFaceMaterial = function ( materials ) {
  7409. this.materials = materials instanceof Array ? materials : [];
  7410. };
  7411. THREE.MeshFaceMaterial.prototype.clone = function () {
  7412. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7413. };
  7414. /**
  7415. * @author mrdoob / http://mrdoob.com/
  7416. * @author alteredq / http://alteredqualia.com/
  7417. *
  7418. * parameters = {
  7419. * color: <hex>,
  7420. * opacity: <float>,
  7421. * map: new THREE.Texture( <Image> ),
  7422. *
  7423. * size: <float>,
  7424. *
  7425. * blending: THREE.NormalBlending,
  7426. * depthTest: <bool>,
  7427. * depthWrite: <bool>,
  7428. *
  7429. * vertexColors: <bool>,
  7430. *
  7431. * fog: <bool>
  7432. * }
  7433. */
  7434. THREE.ParticleBasicMaterial = function ( parameters ) {
  7435. THREE.Material.call( this );
  7436. this.color = new THREE.Color( 0xffffff );
  7437. this.map = null;
  7438. this.size = 1;
  7439. this.sizeAttenuation = true;
  7440. this.vertexColors = false;
  7441. this.fog = true;
  7442. this.setValues( parameters );
  7443. };
  7444. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7445. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7446. var material = new THREE.ParticleBasicMaterial();
  7447. THREE.Material.prototype.clone.call( this, material );
  7448. material.color.copy( this.color );
  7449. material.map = this.map;
  7450. material.size = this.size;
  7451. material.sizeAttenuation = this.sizeAttenuation;
  7452. material.vertexColors = this.vertexColors;
  7453. material.fog = this.fog;
  7454. return material;
  7455. };
  7456. /**
  7457. * @author mrdoob / http://mrdoob.com/
  7458. *
  7459. * parameters = {
  7460. * color: <hex>,
  7461. * program: <function>,
  7462. * opacity: <float>,
  7463. * blending: THREE.NormalBlending
  7464. * }
  7465. */
  7466. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7467. THREE.Material.call( this );
  7468. this.color = new THREE.Color( 0xffffff );
  7469. this.program = function ( context, color ) {};
  7470. this.setValues( parameters );
  7471. };
  7472. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7473. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7474. var material = new THREE.ParticleCanvasMaterial();
  7475. THREE.Material.prototype.clone.call( this, material );
  7476. material.color.copy( this.color );
  7477. material.program = this.program;
  7478. return material;
  7479. };
  7480. /**
  7481. * @author alteredq / http://alteredqualia.com/
  7482. *
  7483. * parameters = {
  7484. * fragmentShader: <string>,
  7485. * vertexShader: <string>,
  7486. *
  7487. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7488. *
  7489. * defines: { "label" : "value" },
  7490. *
  7491. * shading: THREE.SmoothShading,
  7492. * blending: THREE.NormalBlending,
  7493. * depthTest: <bool>,
  7494. * depthWrite: <bool>,
  7495. *
  7496. * wireframe: <boolean>,
  7497. * wireframeLinewidth: <float>,
  7498. *
  7499. * lights: <bool>,
  7500. *
  7501. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7502. *
  7503. * skinning: <bool>,
  7504. * morphTargets: <bool>,
  7505. * morphNormals: <bool>,
  7506. *
  7507. * fog: <bool>
  7508. * }
  7509. */
  7510. THREE.ShaderMaterial = function ( parameters ) {
  7511. THREE.Material.call( this );
  7512. this.fragmentShader = "void main() {}";
  7513. this.vertexShader = "void main() {}";
  7514. this.uniforms = {};
  7515. this.defines = {};
  7516. this.attributes = null;
  7517. this.shading = THREE.SmoothShading;
  7518. this.linewidth = 1;
  7519. this.wireframe = false;
  7520. this.wireframeLinewidth = 1;
  7521. this.fog = false; // set to use scene fog
  7522. this.lights = false; // set to use scene lights
  7523. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7524. this.skinning = false; // set to use skinning attribute streams
  7525. this.morphTargets = false; // set to use morph targets
  7526. this.morphNormals = false; // set to use morph normals
  7527. this.setValues( parameters );
  7528. };
  7529. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7530. THREE.ShaderMaterial.prototype.clone = function () {
  7531. var material = new THREE.ShaderMaterial();
  7532. THREE.Material.prototype.clone.call( this, material );
  7533. material.fragmentShader = this.fragmentShader;
  7534. material.vertexShader = this.vertexShader;
  7535. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7536. material.attributes = this.attributes;
  7537. material.defines = this.defines;
  7538. material.shading = this.shading;
  7539. material.wireframe = this.wireframe;
  7540. material.wireframeLinewidth = this.wireframeLinewidth;
  7541. material.fog = this.fog;
  7542. material.lights = this.lights;
  7543. material.vertexColors = this.vertexColors;
  7544. material.skinning = this.skinning;
  7545. material.morphTargets = this.morphTargets;
  7546. material.morphNormals = this.morphNormals;
  7547. return material;
  7548. };
  7549. /**
  7550. * @author alteredq / http://alteredqualia.com/
  7551. *
  7552. * parameters = {
  7553. * color: <hex>,
  7554. * opacity: <float>,
  7555. * map: new THREE.Texture( <Image> ),
  7556. *
  7557. * blending: THREE.NormalBlending,
  7558. * depthTest: <bool>,
  7559. * depthWrite: <bool>,
  7560. *
  7561. * useScreenCoordinates: <bool>,
  7562. * sizeAttenuation: <bool>,
  7563. * scaleByViewport: <bool>,
  7564. * alignment: THREE.SpriteAlignment.center,
  7565. *
  7566. * uvOffset: new THREE.Vector2(),
  7567. * uvScale: new THREE.Vector2(),
  7568. *
  7569. * fog: <bool>
  7570. * }
  7571. */
  7572. THREE.SpriteMaterial = function ( parameters ) {
  7573. THREE.Material.call( this );
  7574. // defaults
  7575. this.color = new THREE.Color( 0xffffff );
  7576. this.map = new THREE.Texture();
  7577. this.useScreenCoordinates = true;
  7578. this.depthTest = !this.useScreenCoordinates;
  7579. this.sizeAttenuation = !this.useScreenCoordinates;
  7580. this.scaleByViewport = !this.sizeAttenuation;
  7581. this.alignment = THREE.SpriteAlignment.center.clone();
  7582. this.fog = false;
  7583. this.uvOffset = new THREE.Vector2( 0, 0 );
  7584. this.uvScale = new THREE.Vector2( 1, 1 );
  7585. // set parameters
  7586. this.setValues( parameters );
  7587. // override coupled defaults if not specified explicitly by parameters
  7588. parameters = parameters || {};
  7589. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7590. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7591. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7592. };
  7593. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7594. THREE.SpriteMaterial.prototype.clone = function () {
  7595. var material = new THREE.SpriteMaterial();
  7596. THREE.Material.prototype.clone.call( this, material );
  7597. material.color.copy( this.color );
  7598. material.map = this.map;
  7599. material.useScreenCoordinates = this.useScreenCoordinates;
  7600. material.sizeAttenuation = this.sizeAttenuation;
  7601. material.scaleByViewport = this.scaleByViewport;
  7602. material.alignment.copy( this.alignment );
  7603. material.uvOffset.copy( this.uvOffset );
  7604. material.uvScale.copy( this.uvScale );
  7605. material.fog = this.fog;
  7606. return material;
  7607. };
  7608. // Alignment enums
  7609. THREE.SpriteAlignment = {};
  7610. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7611. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7612. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7613. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7614. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7615. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7616. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7617. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7618. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7619. /**
  7620. * @author mrdoob / http://mrdoob.com/
  7621. * @author alteredq / http://alteredqualia.com/
  7622. * @author szimek / https://github.com/szimek/
  7623. */
  7624. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7625. this.id = THREE.TextureIdCount ++;
  7626. this.name = '';
  7627. this.image = image;
  7628. this.mipmaps = [];
  7629. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7630. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7631. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7632. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7633. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7634. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7635. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7636. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7637. this.offset = new THREE.Vector2( 0, 0 );
  7638. this.repeat = new THREE.Vector2( 1, 1 );
  7639. this.generateMipmaps = true;
  7640. this.premultiplyAlpha = false;
  7641. this.flipY = true;
  7642. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7643. this.needsUpdate = false;
  7644. this.onUpdate = null;
  7645. };
  7646. THREE.Texture.prototype = {
  7647. constructor: THREE.Texture,
  7648. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  7649. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  7650. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  7651. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  7652. clone: function ( texture ) {
  7653. if ( texture === undefined ) texture = new THREE.Texture();
  7654. texture.image = this.image;
  7655. texture.mipmaps = this.mipmaps.slice(0);
  7656. texture.mapping = this.mapping;
  7657. texture.wrapS = this.wrapS;
  7658. texture.wrapT = this.wrapT;
  7659. texture.magFilter = this.magFilter;
  7660. texture.minFilter = this.minFilter;
  7661. texture.anisotropy = this.anisotropy;
  7662. texture.format = this.format;
  7663. texture.type = this.type;
  7664. texture.offset.copy( this.offset );
  7665. texture.repeat.copy( this.repeat );
  7666. texture.generateMipmaps = this.generateMipmaps;
  7667. texture.premultiplyAlpha = this.premultiplyAlpha;
  7668. texture.flipY = this.flipY;
  7669. texture.unpackAlignment = this.unpackAlignment;
  7670. return texture;
  7671. },
  7672. dispose: function () {
  7673. this.dispatchEvent( { type: 'dispose' } );
  7674. }
  7675. };
  7676. THREE.TextureIdCount = 0;
  7677. /**
  7678. * @author alteredq / http://alteredqualia.com/
  7679. */
  7680. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7681. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7682. this.image = { width: width, height: height };
  7683. this.mipmaps = mipmaps;
  7684. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7685. };
  7686. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7687. THREE.CompressedTexture.prototype.clone = function () {
  7688. var texture = new THREE.CompressedTexture();
  7689. THREE.Texture.prototype.clone.call( this, texture );
  7690. return texture;
  7691. };
  7692. /**
  7693. * @author alteredq / http://alteredqualia.com/
  7694. */
  7695. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7696. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7697. this.image = { data: data, width: width, height: height };
  7698. };
  7699. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7700. THREE.DataTexture.prototype.clone = function () {
  7701. var texture = new THREE.DataTexture();
  7702. THREE.Texture.prototype.clone.call( this, texture );
  7703. return texture;
  7704. };
  7705. /**
  7706. * @author mrdoob / http://mrdoob.com/
  7707. */
  7708. THREE.Particle = function ( material ) {
  7709. THREE.Object3D.call( this );
  7710. this.material = material;
  7711. };
  7712. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7713. THREE.Particle.prototype.clone = function ( object ) {
  7714. if ( object === undefined ) object = new THREE.Particle( this.material );
  7715. THREE.Object3D.prototype.clone.call( this, object );
  7716. return object;
  7717. };
  7718. /**
  7719. * @author alteredq / http://alteredqualia.com/
  7720. */
  7721. THREE.ParticleSystem = function ( geometry, material ) {
  7722. THREE.Object3D.call( this );
  7723. this.geometry = geometry;
  7724. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7725. this.sortParticles = false;
  7726. if ( this.geometry ) {
  7727. // calc bound radius
  7728. if( this.geometry.boundingSphere === null ) {
  7729. this.geometry.computeBoundingSphere();
  7730. }
  7731. }
  7732. this.frustumCulled = false;
  7733. };
  7734. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7735. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7736. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7737. object.sortParticles = this.sortParticles;
  7738. THREE.Object3D.prototype.clone.call( this, object );
  7739. return object;
  7740. };
  7741. /**
  7742. * @author mrdoob / http://mrdoob.com/
  7743. */
  7744. THREE.Line = function ( geometry, material, type ) {
  7745. THREE.Object3D.call( this );
  7746. this.geometry = geometry;
  7747. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7748. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7749. if ( this.geometry ) {
  7750. if ( ! this.geometry.boundingSphere ) {
  7751. this.geometry.computeBoundingSphere();
  7752. }
  7753. }
  7754. };
  7755. THREE.LineStrip = 0;
  7756. THREE.LinePieces = 1;
  7757. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7758. THREE.Line.prototype.clone = function ( object ) {
  7759. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7760. THREE.Object3D.prototype.clone.call( this, object );
  7761. return object;
  7762. };
  7763. /**
  7764. * @author mrdoob / http://mrdoob.com/
  7765. * @author alteredq / http://alteredqualia.com/
  7766. * @author mikael emtinger / http://gomo.se/
  7767. * @author jonobr1 / http://jonobr1.com/
  7768. */
  7769. THREE.Mesh = function ( geometry, material ) {
  7770. THREE.Object3D.call( this );
  7771. this.geometry = null;
  7772. this.material = null;
  7773. this.setGeometry( geometry );
  7774. this.setMaterial( material );
  7775. };
  7776. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7777. THREE.Mesh.prototype.setGeometry = function ( geometry ) {
  7778. if ( geometry !== undefined ) {
  7779. this.geometry = geometry;
  7780. if ( this.geometry.boundingSphere === null ) {
  7781. this.geometry.computeBoundingSphere();
  7782. }
  7783. this.updateMorphTargets();
  7784. }
  7785. };
  7786. THREE.Mesh.prototype.setMaterial = function ( material ) {
  7787. if ( material !== undefined ) {
  7788. this.material = material;
  7789. } else {
  7790. this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7791. }
  7792. };
  7793. THREE.Mesh.prototype.updateMorphTargets = function () {
  7794. if ( this.geometry.morphTargets.length > 0 ) {
  7795. this.morphTargetBase = -1;
  7796. this.morphTargetForcedOrder = [];
  7797. this.morphTargetInfluences = [];
  7798. this.morphTargetDictionary = {};
  7799. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7800. this.morphTargetInfluences.push( 0 );
  7801. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7802. }
  7803. }
  7804. };
  7805. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7806. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7807. return this.morphTargetDictionary[ name ];
  7808. }
  7809. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7810. return 0;
  7811. };
  7812. THREE.Mesh.prototype.clone = function ( object ) {
  7813. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7814. THREE.Object3D.prototype.clone.call( this, object );
  7815. return object;
  7816. };
  7817. /**
  7818. * @author mikael emtinger / http://gomo.se/
  7819. * @author alteredq / http://alteredqualia.com/
  7820. */
  7821. THREE.Bone = function( belongsToSkin ) {
  7822. THREE.Object3D.call( this );
  7823. this.skin = belongsToSkin;
  7824. this.skinMatrix = new THREE.Matrix4();
  7825. };
  7826. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7827. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7828. // update local
  7829. if ( this.matrixAutoUpdate ) {
  7830. forceUpdate |= this.updateMatrix();
  7831. }
  7832. // update skin matrix
  7833. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7834. if( parentSkinMatrix ) {
  7835. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7836. } else {
  7837. this.skinMatrix.copy( this.matrix );
  7838. }
  7839. this.matrixWorldNeedsUpdate = false;
  7840. forceUpdate = true;
  7841. }
  7842. // update children
  7843. var child, i, l = this.children.length;
  7844. for ( i = 0; i < l; i ++ ) {
  7845. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7846. }
  7847. };
  7848. /**
  7849. * @author mikael emtinger / http://gomo.se/
  7850. * @author alteredq / http://alteredqualia.com/
  7851. */
  7852. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7853. THREE.Mesh.call( this, geometry, material );
  7854. //
  7855. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7856. // init bones
  7857. this.identityMatrix = new THREE.Matrix4();
  7858. this.bones = [];
  7859. this.boneMatrices = [];
  7860. var b, bone, gbone, p, q, s;
  7861. if ( this.geometry && this.geometry.bones !== undefined ) {
  7862. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7863. gbone = this.geometry.bones[ b ];
  7864. p = gbone.pos;
  7865. q = gbone.rotq;
  7866. s = gbone.scl;
  7867. bone = this.addBone();
  7868. bone.name = gbone.name;
  7869. bone.position.set( p[0], p[1], p[2] );
  7870. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7871. bone.useQuaternion = true;
  7872. if ( s !== undefined ) {
  7873. bone.scale.set( s[0], s[1], s[2] );
  7874. } else {
  7875. bone.scale.set( 1, 1, 1 );
  7876. }
  7877. }
  7878. for ( b = 0; b < this.bones.length; b ++ ) {
  7879. gbone = this.geometry.bones[ b ];
  7880. bone = this.bones[ b ];
  7881. if ( gbone.parent === -1 ) {
  7882. this.add( bone );
  7883. } else {
  7884. this.bones[ gbone.parent ].add( bone );
  7885. }
  7886. }
  7887. //
  7888. var nBones = this.bones.length;
  7889. if ( this.useVertexTexture ) {
  7890. // layout (1 matrix = 4 pixels)
  7891. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7892. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7893. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7894. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7895. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7896. var size;
  7897. if ( nBones > 256 )
  7898. size = 64;
  7899. else if ( nBones > 64 )
  7900. size = 32;
  7901. else if ( nBones > 16 )
  7902. size = 16;
  7903. else
  7904. size = 8;
  7905. this.boneTextureWidth = size;
  7906. this.boneTextureHeight = size;
  7907. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7908. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7909. this.boneTexture.minFilter = THREE.NearestFilter;
  7910. this.boneTexture.magFilter = THREE.NearestFilter;
  7911. this.boneTexture.generateMipmaps = false;
  7912. this.boneTexture.flipY = false;
  7913. } else {
  7914. this.boneMatrices = new Float32Array( 16 * nBones );
  7915. }
  7916. this.pose();
  7917. }
  7918. };
  7919. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7920. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7921. if ( bone === undefined ) {
  7922. bone = new THREE.Bone( this );
  7923. }
  7924. this.bones.push( bone );
  7925. return bone;
  7926. };
  7927. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7928. this.matrixAutoUpdate && this.updateMatrix();
  7929. // update matrixWorld
  7930. if ( this.matrixWorldNeedsUpdate || force ) {
  7931. if ( this.parent ) {
  7932. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7933. } else {
  7934. this.matrixWorld.copy( this.matrix );
  7935. }
  7936. this.matrixWorldNeedsUpdate = false;
  7937. force = true;
  7938. }
  7939. // update children
  7940. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7941. var child = this.children[ i ];
  7942. if ( child instanceof THREE.Bone ) {
  7943. child.update( this.identityMatrix, false );
  7944. } else {
  7945. child.updateMatrixWorld( true );
  7946. }
  7947. }
  7948. // make a snapshot of the bones' rest position
  7949. if ( this.boneInverses == undefined ) {
  7950. this.boneInverses = [];
  7951. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7952. var inverse = new THREE.Matrix4();
  7953. inverse.getInverse( this.bones[ b ].skinMatrix );
  7954. this.boneInverses.push( inverse );
  7955. }
  7956. }
  7957. // flatten bone matrices to array
  7958. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7959. // compute the offset between the current and the original transform;
  7960. //TODO: we could get rid of this multiplication step if the skinMatrix
  7961. // was already representing the offset; however, this requires some
  7962. // major changes to the animation system
  7963. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7964. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7965. }
  7966. if ( this.useVertexTexture ) {
  7967. this.boneTexture.needsUpdate = true;
  7968. }
  7969. };
  7970. THREE.SkinnedMesh.prototype.pose = function () {
  7971. this.updateMatrixWorld( true );
  7972. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7973. // normalize weights
  7974. var sw = this.geometry.skinWeights[ i ];
  7975. var scale = 1.0 / sw.lengthManhattan();
  7976. if ( scale !== Infinity ) {
  7977. sw.multiplyScalar( scale );
  7978. } else {
  7979. sw.set( 1 ); // this will be normalized by the shader anyway
  7980. }
  7981. }
  7982. };
  7983. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7984. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7985. THREE.Mesh.prototype.clone.call( this, object );
  7986. return object;
  7987. };
  7988. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7989. /**
  7990. * @author alteredq / http://alteredqualia.com/
  7991. */
  7992. THREE.MorphAnimMesh = function ( geometry, material ) {
  7993. THREE.Mesh.call( this, geometry, material );
  7994. // API
  7995. this.duration = 1000; // milliseconds
  7996. this.mirroredLoop = false;
  7997. this.time = 0;
  7998. // internals
  7999. this.lastKeyframe = 0;
  8000. this.currentKeyframe = 0;
  8001. this.direction = 1;
  8002. this.directionBackwards = false;
  8003. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8004. };
  8005. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8006. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8007. this.startKeyframe = start;
  8008. this.endKeyframe = end;
  8009. this.length = this.endKeyframe - this.startKeyframe + 1;
  8010. };
  8011. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8012. this.direction = 1;
  8013. this.directionBackwards = false;
  8014. };
  8015. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8016. this.direction = -1;
  8017. this.directionBackwards = true;
  8018. };
  8019. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8020. var geometry = this.geometry;
  8021. if ( ! geometry.animations ) geometry.animations = {};
  8022. var firstAnimation, animations = geometry.animations;
  8023. var pattern = /([a-z]+)(\d+)/;
  8024. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8025. var morph = geometry.morphTargets[ i ];
  8026. var parts = morph.name.match( pattern );
  8027. if ( parts && parts.length > 1 ) {
  8028. var label = parts[ 1 ];
  8029. var num = parts[ 2 ];
  8030. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8031. var animation = animations[ label ];
  8032. if ( i < animation.start ) animation.start = i;
  8033. if ( i > animation.end ) animation.end = i;
  8034. if ( ! firstAnimation ) firstAnimation = label;
  8035. }
  8036. }
  8037. geometry.firstAnimation = firstAnimation;
  8038. };
  8039. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8040. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8041. this.geometry.animations[ label ] = { start: start, end: end };
  8042. };
  8043. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8044. var animation = this.geometry.animations[ label ];
  8045. if ( animation ) {
  8046. this.setFrameRange( animation.start, animation.end );
  8047. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8048. this.time = 0;
  8049. } else {
  8050. console.warn( "animation[" + label + "] undefined" );
  8051. }
  8052. };
  8053. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8054. var frameTime = this.duration / this.length;
  8055. this.time += this.direction * delta;
  8056. if ( this.mirroredLoop ) {
  8057. if ( this.time > this.duration || this.time < 0 ) {
  8058. this.direction *= -1;
  8059. if ( this.time > this.duration ) {
  8060. this.time = this.duration;
  8061. this.directionBackwards = true;
  8062. }
  8063. if ( this.time < 0 ) {
  8064. this.time = 0;
  8065. this.directionBackwards = false;
  8066. }
  8067. }
  8068. } else {
  8069. this.time = this.time % this.duration;
  8070. if ( this.time < 0 ) this.time += this.duration;
  8071. }
  8072. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8073. if ( keyframe !== this.currentKeyframe ) {
  8074. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8075. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8076. this.morphTargetInfluences[ keyframe ] = 0;
  8077. this.lastKeyframe = this.currentKeyframe;
  8078. this.currentKeyframe = keyframe;
  8079. }
  8080. var mix = ( this.time % frameTime ) / frameTime;
  8081. if ( this.directionBackwards ) {
  8082. mix = 1 - mix;
  8083. }
  8084. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8085. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8086. };
  8087. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8088. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8089. object.duration = this.duration;
  8090. object.mirroredLoop = this.mirroredLoop;
  8091. object.time = this.time;
  8092. object.lastKeyframe = this.lastKeyframe;
  8093. object.currentKeyframe = this.currentKeyframe;
  8094. object.direction = this.direction;
  8095. object.directionBackwards = this.directionBackwards;
  8096. THREE.Mesh.prototype.clone.call( this, object );
  8097. return object;
  8098. };
  8099. /**
  8100. * @author alteredq / http://alteredqualia.com/
  8101. */
  8102. THREE.Ribbon = function ( geometry, material ) {
  8103. THREE.Object3D.call( this );
  8104. this.geometry = geometry;
  8105. this.material = material;
  8106. };
  8107. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8108. THREE.Ribbon.prototype.clone = function ( object ) {
  8109. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8110. THREE.Object3D.prototype.clone.call( this, object );
  8111. return object;
  8112. };
  8113. /**
  8114. * @author mikael emtinger / http://gomo.se/
  8115. * @author alteredq / http://alteredqualia.com/
  8116. * @author mrdoob / http://mrdoob.com/
  8117. */
  8118. THREE.LOD = function () {
  8119. THREE.Object3D.call( this );
  8120. this.objects = [];
  8121. };
  8122. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8123. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8124. if ( distance === undefined ) distance = 0;
  8125. distance = Math.abs( distance );
  8126. for ( var l = 0; l < this.objects.length; l ++ ) {
  8127. if ( distance < this.objects[ l ].distance ) {
  8128. break;
  8129. }
  8130. }
  8131. this.objects.splice( l, 0, { distance: distance, object: object } );
  8132. this.add( object );
  8133. };
  8134. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8135. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8136. if ( distance < this.objects[ i ].distance ) {
  8137. break;
  8138. }
  8139. }
  8140. return this.objects[ i - 1 ].object;
  8141. };
  8142. THREE.LOD.prototype.update = function () {
  8143. var v1 = new THREE.Vector3();
  8144. var v2 = new THREE.Vector3();
  8145. return function ( camera ) {
  8146. if ( this.objects.length > 1 ) {
  8147. v1.getPositionFromMatrix( camera.matrixWorld );
  8148. v2.getPositionFromMatrix( this.matrixWorld );
  8149. var distance = v1.distanceTo( v2 );
  8150. this.objects[ 0 ].object.visible = true;
  8151. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8152. if ( distance >= this.objects[ i ].distance ) {
  8153. this.objects[ i - 1 ].object.visible = false;
  8154. this.objects[ i ].object.visible = true;
  8155. } else {
  8156. break;
  8157. }
  8158. }
  8159. for( ; i < l; i ++ ) {
  8160. this.objects[ i ].object.visible = false;
  8161. }
  8162. }
  8163. };
  8164. }();
  8165. THREE.LOD.prototype.clone = function () {
  8166. // TODO
  8167. };
  8168. /**
  8169. * @author mikael emtinger / http://gomo.se/
  8170. * @author alteredq / http://alteredqualia.com/
  8171. */
  8172. THREE.Sprite = function ( material ) {
  8173. THREE.Object3D.call( this );
  8174. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8175. this.rotation3d = this.rotation;
  8176. this.rotation = 0;
  8177. };
  8178. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8179. /*
  8180. * Custom update matrix
  8181. */
  8182. THREE.Sprite.prototype.updateMatrix = function () {
  8183. this.rotation3d.set( 0, 0, this.rotation );
  8184. this.quaternion.setFromEuler( this.rotation3d, this.eulerOrder );
  8185. this.matrix.makeFromPositionQuaternionScale( this.position, this.quaternion, this.scale );
  8186. this.matrixWorldNeedsUpdate = true;
  8187. };
  8188. THREE.Sprite.prototype.clone = function ( object ) {
  8189. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8190. THREE.Object3D.prototype.clone.call( this, object );
  8191. return object;
  8192. };
  8193. /**
  8194. * @author mrdoob / http://mrdoob.com/
  8195. */
  8196. THREE.Scene = function () {
  8197. THREE.Object3D.call( this );
  8198. this.fog = null;
  8199. this.overrideMaterial = null;
  8200. this.autoUpdate = true; // checked by the renderer
  8201. this.matrixAutoUpdate = false;
  8202. this.__objects = [];
  8203. this.__lights = [];
  8204. this.__objectsAdded = [];
  8205. this.__objectsRemoved = [];
  8206. };
  8207. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8208. THREE.Scene.prototype.__addObject = function ( object ) {
  8209. if ( object instanceof THREE.Light ) {
  8210. if ( this.__lights.indexOf( object ) === - 1 ) {
  8211. this.__lights.push( object );
  8212. }
  8213. if ( object.target && object.target.parent === undefined ) {
  8214. this.add( object.target );
  8215. }
  8216. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8217. if ( this.__objects.indexOf( object ) === - 1 ) {
  8218. this.__objects.push( object );
  8219. this.__objectsAdded.push( object );
  8220. // check if previously removed
  8221. var i = this.__objectsRemoved.indexOf( object );
  8222. if ( i !== -1 ) {
  8223. this.__objectsRemoved.splice( i, 1 );
  8224. }
  8225. }
  8226. }
  8227. for ( var c = 0; c < object.children.length; c ++ ) {
  8228. this.__addObject( object.children[ c ] );
  8229. }
  8230. };
  8231. THREE.Scene.prototype.__removeObject = function ( object ) {
  8232. if ( object instanceof THREE.Light ) {
  8233. var i = this.__lights.indexOf( object );
  8234. if ( i !== -1 ) {
  8235. this.__lights.splice( i, 1 );
  8236. }
  8237. } else if ( !( object instanceof THREE.Camera ) ) {
  8238. var i = this.__objects.indexOf( object );
  8239. if( i !== -1 ) {
  8240. this.__objects.splice( i, 1 );
  8241. this.__objectsRemoved.push( object );
  8242. // check if previously added
  8243. var ai = this.__objectsAdded.indexOf( object );
  8244. if ( ai !== -1 ) {
  8245. this.__objectsAdded.splice( ai, 1 );
  8246. }
  8247. }
  8248. }
  8249. for ( var c = 0; c < object.children.length; c ++ ) {
  8250. this.__removeObject( object.children[ c ] );
  8251. }
  8252. };
  8253. /**
  8254. * @author mrdoob / http://mrdoob.com/
  8255. * @author alteredq / http://alteredqualia.com/
  8256. */
  8257. THREE.Fog = function ( hex, near, far ) {
  8258. this.name = '';
  8259. this.color = new THREE.Color( hex );
  8260. this.near = ( near !== undefined ) ? near : 1;
  8261. this.far = ( far !== undefined ) ? far : 1000;
  8262. };
  8263. THREE.Fog.prototype.clone = function () {
  8264. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8265. };
  8266. /**
  8267. * @author mrdoob / http://mrdoob.com/
  8268. * @author alteredq / http://alteredqualia.com/
  8269. */
  8270. THREE.FogExp2 = function ( hex, density ) {
  8271. this.name = '';
  8272. this.color = new THREE.Color( hex );
  8273. this.density = ( density !== undefined ) ? density : 0.00025;
  8274. };
  8275. THREE.FogExp2.prototype.clone = function () {
  8276. return new THREE.FogExp2( this.color.getHex(), this.density );
  8277. };
  8278. /**
  8279. * @author mrdoob / http://mrdoob.com/
  8280. */
  8281. THREE.CanvasRenderer = function ( parameters ) {
  8282. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8283. var smoothstep = THREE.Math.smoothstep;
  8284. parameters = parameters || {};
  8285. var _this = this,
  8286. _renderData, _elements, _lights,
  8287. _projector = new THREE.Projector(),
  8288. _canvas = parameters.canvas !== undefined
  8289. ? parameters.canvas
  8290. : document.createElement( 'canvas' ),
  8291. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8292. _context = _canvas.getContext( '2d' ),
  8293. _clearColor = new THREE.Color( 0x000000 ),
  8294. _clearAlpha = 0,
  8295. _contextGlobalAlpha = 1,
  8296. _contextGlobalCompositeOperation = 0,
  8297. _contextStrokeStyle = null,
  8298. _contextFillStyle = null,
  8299. _contextLineWidth = null,
  8300. _contextLineCap = null,
  8301. _contextLineJoin = null,
  8302. _contextDashSize = null,
  8303. _contextGapSize = 0,
  8304. _v1, _v2, _v3, _v4,
  8305. _v5 = new THREE.RenderableVertex(),
  8306. _v6 = new THREE.RenderableVertex(),
  8307. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8308. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8309. _color = new THREE.Color(),
  8310. _color1 = new THREE.Color(),
  8311. _color2 = new THREE.Color(),
  8312. _color3 = new THREE.Color(),
  8313. _color4 = new THREE.Color(),
  8314. _diffuseColor = new THREE.Color(),
  8315. _emissiveColor = new THREE.Color(),
  8316. _lightColor = new THREE.Color(),
  8317. _patterns = {}, _imagedatas = {},
  8318. _near, _far,
  8319. _image, _uvs,
  8320. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8321. _clipBox = new THREE.Box2(),
  8322. _clearBox = new THREE.Box2(),
  8323. _elemBox = new THREE.Box2(),
  8324. _ambientLight = new THREE.Color(),
  8325. _directionalLights = new THREE.Color(),
  8326. _pointLights = new THREE.Color(),
  8327. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8328. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8329. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8330. _pixelMap = document.createElement( 'canvas' );
  8331. _pixelMap.width = _pixelMap.height = 2;
  8332. _pixelMapContext = _pixelMap.getContext( '2d' );
  8333. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8334. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8335. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8336. _pixelMapData = _pixelMapImage.data;
  8337. _gradientMap = document.createElement( 'canvas' );
  8338. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8339. _gradientMapContext = _gradientMap.getContext( '2d' );
  8340. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8341. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8342. _gradientMapQuality --; // Fix UVs
  8343. // dash+gap fallbacks for Firefox and everything else
  8344. if ( _context.setLineDash === undefined ) {
  8345. if ( _context.mozDash !== undefined ) {
  8346. _context.setLineDash = function ( values ) {
  8347. _context.mozDash = values[ 0 ] !== null ? values : null;
  8348. }
  8349. } else {
  8350. _context.setLineDash = function () {}
  8351. }
  8352. }
  8353. this.domElement = _canvas;
  8354. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8355. ? parameters.devicePixelRatio
  8356. : window.devicePixelRatio !== undefined
  8357. ? window.devicePixelRatio
  8358. : 1;
  8359. this.autoClear = true;
  8360. this.sortObjects = true;
  8361. this.sortElements = true;
  8362. this.info = {
  8363. render: {
  8364. vertices: 0,
  8365. faces: 0
  8366. }
  8367. }
  8368. // WebGLRenderer compatibility
  8369. this.supportsVertexTextures = function () {};
  8370. this.setFaceCulling = function () {};
  8371. this.setSize = function ( width, height, updateStyle ) {
  8372. _canvasWidth = width * this.devicePixelRatio;
  8373. _canvasHeight = height * this.devicePixelRatio;
  8374. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8375. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8376. _canvas.width = _canvasWidth;
  8377. _canvas.height = _canvasHeight;
  8378. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  8379. _canvas.style.width = width + 'px';
  8380. _canvas.style.height = height + 'px';
  8381. }
  8382. _clipBox.set(
  8383. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8384. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8385. );
  8386. _clearBox.set(
  8387. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8388. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8389. );
  8390. _contextGlobalAlpha = 1;
  8391. _contextGlobalCompositeOperation = 0;
  8392. _contextStrokeStyle = null;
  8393. _contextFillStyle = null;
  8394. _contextLineWidth = null;
  8395. _contextLineCap = null;
  8396. _contextLineJoin = null;
  8397. };
  8398. this.setClearColor = function ( color, alpha ) {
  8399. _clearColor.set( color );
  8400. _clearAlpha = alpha !== undefined ? alpha : 1;
  8401. _clearBox.set(
  8402. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8403. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8404. );
  8405. };
  8406. this.setClearColorHex = function ( hex, alpha ) {
  8407. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  8408. this.setClearColor( hex, alpha );
  8409. };
  8410. this.getMaxAnisotropy = function () {
  8411. return 0;
  8412. };
  8413. this.clear = function () {
  8414. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8415. if ( _clearBox.empty() === false ) {
  8416. _clearBox.intersect( _clipBox );
  8417. _clearBox.expandByScalar( 2 );
  8418. if ( _clearAlpha < 1 ) {
  8419. _context.clearRect(
  8420. _clearBox.min.x | 0,
  8421. _clearBox.min.y | 0,
  8422. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8423. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8424. );
  8425. }
  8426. if ( _clearAlpha > 0 ) {
  8427. setBlending( THREE.NormalBlending );
  8428. setOpacity( 1 );
  8429. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  8430. _context.fillRect(
  8431. _clearBox.min.x | 0,
  8432. _clearBox.min.y | 0,
  8433. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8434. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8435. );
  8436. }
  8437. _clearBox.makeEmpty();
  8438. }
  8439. };
  8440. this.render = function ( scene, camera ) {
  8441. if ( camera instanceof THREE.Camera === false ) {
  8442. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8443. return;
  8444. }
  8445. if ( this.autoClear === true ) this.clear();
  8446. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8447. _this.info.render.vertices = 0;
  8448. _this.info.render.faces = 0;
  8449. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8450. _elements = _renderData.elements;
  8451. _lights = _renderData.lights;
  8452. /* DEBUG
  8453. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8454. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8455. */
  8456. calculateLights();
  8457. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8458. var element = _elements[ e ];
  8459. var material = element.material;
  8460. if ( material === undefined || material.visible === false ) continue;
  8461. _elemBox.makeEmpty();
  8462. if ( element instanceof THREE.RenderableParticle ) {
  8463. _v1 = element;
  8464. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8465. renderParticle( _v1, element, material );
  8466. } else if ( element instanceof THREE.RenderableLine ) {
  8467. _v1 = element.v1; _v2 = element.v2;
  8468. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8469. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8470. _elemBox.setFromPoints( [
  8471. _v1.positionScreen,
  8472. _v2.positionScreen
  8473. ] );
  8474. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8475. renderLine( _v1, _v2, element, material );
  8476. }
  8477. } else if ( element instanceof THREE.RenderableFace3 ) {
  8478. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8479. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8480. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8481. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8482. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8483. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8484. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8485. if ( material.overdraw === true ) {
  8486. expand( _v1.positionScreen, _v2.positionScreen );
  8487. expand( _v2.positionScreen, _v3.positionScreen );
  8488. expand( _v3.positionScreen, _v1.positionScreen );
  8489. }
  8490. _elemBox.setFromPoints( [
  8491. _v1.positionScreen,
  8492. _v2.positionScreen,
  8493. _v3.positionScreen
  8494. ] );
  8495. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8496. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8497. }
  8498. } else if ( element instanceof THREE.RenderableFace4 ) {
  8499. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8500. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8501. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8502. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8503. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8504. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8505. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8506. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8507. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8508. _v5.positionScreen.copy( _v2.positionScreen );
  8509. _v6.positionScreen.copy( _v4.positionScreen );
  8510. if ( material.overdraw === true ) {
  8511. expand( _v1.positionScreen, _v2.positionScreen );
  8512. expand( _v2.positionScreen, _v4.positionScreen );
  8513. expand( _v4.positionScreen, _v1.positionScreen );
  8514. expand( _v3.positionScreen, _v5.positionScreen );
  8515. expand( _v3.positionScreen, _v6.positionScreen );
  8516. }
  8517. _elemBox.setFromPoints( [
  8518. _v1.positionScreen,
  8519. _v2.positionScreen,
  8520. _v3.positionScreen,
  8521. _v4.positionScreen
  8522. ] );
  8523. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8524. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material );
  8525. }
  8526. }
  8527. /* DEBUG
  8528. setLineWidth( 1 );
  8529. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8530. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8531. */
  8532. _clearBox.union( _elemBox );
  8533. }
  8534. /* DEBUG
  8535. setLineWidth( 1 );
  8536. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  8537. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8538. */
  8539. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8540. //
  8541. function calculateLights() {
  8542. _ambientLight.setRGB( 0, 0, 0 );
  8543. _directionalLights.setRGB( 0, 0, 0 );
  8544. _pointLights.setRGB( 0, 0, 0 );
  8545. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8546. var light = _lights[ l ];
  8547. var lightColor = light.color;
  8548. if ( light instanceof THREE.AmbientLight ) {
  8549. _ambientLight.add( lightColor );
  8550. } else if ( light instanceof THREE.DirectionalLight ) {
  8551. // for particles
  8552. _directionalLights.add( lightColor );
  8553. } else if ( light instanceof THREE.PointLight ) {
  8554. // for particles
  8555. _pointLights.add( lightColor );
  8556. }
  8557. }
  8558. }
  8559. function calculateLight( position, normal, color ) {
  8560. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8561. var light = _lights[ l ];
  8562. _lightColor.copy( light.color );
  8563. if ( light instanceof THREE.DirectionalLight ) {
  8564. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  8565. var amount = normal.dot( lightPosition );
  8566. if ( amount <= 0 ) continue;
  8567. amount *= light.intensity;
  8568. color.add( _lightColor.multiplyScalar( amount ) );
  8569. } else if ( light instanceof THREE.PointLight ) {
  8570. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  8571. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8572. if ( amount <= 0 ) continue;
  8573. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8574. if ( amount == 0 ) continue;
  8575. amount *= light.intensity;
  8576. color.add( _lightColor.multiplyScalar( amount ) );
  8577. }
  8578. }
  8579. }
  8580. function renderParticle( v1, element, material ) {
  8581. setOpacity( material.opacity );
  8582. setBlending( material.blending );
  8583. var width, height, scaleX, scaleY,
  8584. bitmap, bitmapWidth, bitmapHeight;
  8585. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8586. if ( material.map === null ) {
  8587. scaleX = element.object.scale.x;
  8588. scaleY = element.object.scale.y;
  8589. // TODO: Be able to disable this
  8590. scaleX *= element.scale.x * _canvasWidthHalf;
  8591. scaleY *= element.scale.y * _canvasHeightHalf;
  8592. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8593. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8594. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8595. _elemBox.makeEmpty();
  8596. return;
  8597. }
  8598. setFillStyle( material.color.getStyle() );
  8599. _context.save();
  8600. _context.translate( v1.x, v1.y );
  8601. _context.rotate( - element.rotation );
  8602. _context.scale( scaleX, scaleY );
  8603. _context.fillRect( -1, -1, 2, 2 );
  8604. _context.restore();
  8605. } else {
  8606. bitmap = material.map.image;
  8607. bitmapWidth = bitmap.width >> 1;
  8608. bitmapHeight = bitmap.height >> 1;
  8609. scaleX = element.scale.x * _canvasWidthHalf;
  8610. scaleY = element.scale.y * _canvasHeightHalf;
  8611. width = scaleX * bitmapWidth;
  8612. height = scaleY * bitmapHeight;
  8613. // TODO: Rotations break this...
  8614. _elemBox.min.set( v1.x - width, v1.y - height );
  8615. _elemBox.max.set( v1.x + width, v1.y + height );
  8616. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8617. _elemBox.makeEmpty();
  8618. return;
  8619. }
  8620. _context.save();
  8621. _context.translate( v1.x, v1.y );
  8622. _context.rotate( - element.rotation );
  8623. _context.scale( scaleX, - scaleY );
  8624. _context.translate( - bitmapWidth, - bitmapHeight );
  8625. _context.drawImage( bitmap, 0, 0 );
  8626. _context.restore();
  8627. }
  8628. /* DEBUG
  8629. setStrokeStyle( 'rgb(255,255,0)' );
  8630. _context.beginPath();
  8631. _context.moveTo( v1.x - 10, v1.y );
  8632. _context.lineTo( v1.x + 10, v1.y );
  8633. _context.moveTo( v1.x, v1.y - 10 );
  8634. _context.lineTo( v1.x, v1.y + 10 );
  8635. _context.stroke();
  8636. */
  8637. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8638. width = element.scale.x * _canvasWidthHalf;
  8639. height = element.scale.y * _canvasHeightHalf;
  8640. _elemBox.min.set( v1.x - width, v1.y - height );
  8641. _elemBox.max.set( v1.x + width, v1.y + height );
  8642. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8643. _elemBox.makeEmpty();
  8644. return;
  8645. }
  8646. setStrokeStyle( material.color.getStyle() );
  8647. setFillStyle( material.color.getStyle() );
  8648. _context.save();
  8649. _context.translate( v1.x, v1.y );
  8650. _context.rotate( - element.rotation );
  8651. _context.scale( width, height );
  8652. material.program( _context );
  8653. _context.restore();
  8654. }
  8655. }
  8656. function renderLine( v1, v2, element, material ) {
  8657. setOpacity( material.opacity );
  8658. setBlending( material.blending );
  8659. _context.beginPath();
  8660. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8661. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8662. if ( material instanceof THREE.LineBasicMaterial ) {
  8663. setLineWidth( material.linewidth );
  8664. setLineCap( material.linecap );
  8665. setLineJoin( material.linejoin );
  8666. if ( material.vertexColors !== THREE.VertexColors ) {
  8667. setStrokeStyle( material.color.getStyle() );
  8668. } else {
  8669. var colorStyle1 = element.vertexColors[0].getStyle();
  8670. var colorStyle2 = element.vertexColors[1].getStyle();
  8671. if ( colorStyle1 === colorStyle2 ) {
  8672. setStrokeStyle( colorStyle1 );
  8673. } else {
  8674. try {
  8675. var grad = _context.createLinearGradient(
  8676. v1.positionScreen.x,
  8677. v1.positionScreen.y,
  8678. v2.positionScreen.x,
  8679. v2.positionScreen.y
  8680. );
  8681. grad.addColorStop( 0, colorStyle1 );
  8682. grad.addColorStop( 1, colorStyle2 );
  8683. } catch ( exception ) {
  8684. grad = colorStyle1;
  8685. }
  8686. setStrokeStyle( grad );
  8687. }
  8688. }
  8689. _context.stroke();
  8690. _elemBox.expandByScalar( material.linewidth * 2 );
  8691. } else if ( material instanceof THREE.LineDashedMaterial ) {
  8692. setLineWidth( material.linewidth );
  8693. setLineCap( material.linecap );
  8694. setLineJoin( material.linejoin );
  8695. setStrokeStyle( material.color.getStyle() );
  8696. setDashAndGap( material.dashSize, material.gapSize );
  8697. _context.stroke();
  8698. _elemBox.expandByScalar( material.linewidth * 2 );
  8699. setDashAndGap( null, null );
  8700. }
  8701. }
  8702. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  8703. _this.info.render.vertices += 3;
  8704. _this.info.render.faces ++;
  8705. setOpacity( material.opacity );
  8706. setBlending( material.blending );
  8707. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8708. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8709. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8710. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8711. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  8712. _diffuseColor.copy( material.color );
  8713. _emissiveColor.copy( material.emissive );
  8714. if ( material.vertexColors === THREE.FaceColors ) {
  8715. _diffuseColor.multiply( element.color );
  8716. }
  8717. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8718. _color1.copy( _ambientLight );
  8719. _color2.copy( _ambientLight );
  8720. _color3.copy( _ambientLight );
  8721. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8722. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8723. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8724. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8725. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8726. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8727. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8728. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8729. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8730. } else {
  8731. _color.copy( _ambientLight );
  8732. calculateLight( element.centroidModel, element.normalModel, _color );
  8733. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8734. material.wireframe === true
  8735. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8736. : fillPath( _color );
  8737. }
  8738. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8739. if ( material.map !== null ) {
  8740. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8741. _uvs = element.uvs[ 0 ];
  8742. 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 );
  8743. }
  8744. } else if ( material.envMap !== null ) {
  8745. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8746. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8747. _uv1x = 0.5 * _vector3.x + 0.5;
  8748. _uv1y = 0.5 * _vector3.y + 0.5;
  8749. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8750. _uv2x = 0.5 * _vector3.x + 0.5;
  8751. _uv2y = 0.5 * _vector3.y + 0.5;
  8752. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8753. _uv3x = 0.5 * _vector3.x + 0.5;
  8754. _uv3y = 0.5 * _vector3.y + 0.5;
  8755. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8756. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8757. }*/
  8758. } else {
  8759. _color.copy( material.color );
  8760. if ( material.vertexColors === THREE.FaceColors ) {
  8761. _color.multiply( element.color );
  8762. }
  8763. material.wireframe === true
  8764. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8765. : fillPath( _color );
  8766. }
  8767. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8768. _near = camera.near;
  8769. _far = camera.far;
  8770. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8771. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8772. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8773. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8774. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8775. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8776. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8777. var normal;
  8778. if ( material.shading == THREE.FlatShading ) {
  8779. normal = element.normalModelView;
  8780. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8781. material.wireframe === true
  8782. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8783. : fillPath( _color );
  8784. } else if ( material.shading == THREE.SmoothShading ) {
  8785. normal = element.vertexNormalsModelView[ uv1 ];
  8786. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8787. normal = element.vertexNormalsModelView[ uv2 ];
  8788. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8789. normal = element.vertexNormalsModelView[ uv3 ];
  8790. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8791. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8792. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8793. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8794. }
  8795. }
  8796. }
  8797. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  8798. _this.info.render.vertices += 4;
  8799. _this.info.render.faces ++;
  8800. setOpacity( material.opacity );
  8801. setBlending( material.blending );
  8802. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8803. // Let renderFace3() handle this
  8804. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  8805. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  8806. return;
  8807. }
  8808. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8809. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8810. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8811. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8812. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8813. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8814. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8815. _diffuseColor.copy( material.color );
  8816. _emissiveColor.copy( material.emissive );
  8817. if ( material.vertexColors === THREE.FaceColors ) {
  8818. _diffuseColor.multiply( element.color );
  8819. }
  8820. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8821. _color1.copy( _ambientLight );
  8822. _color2.copy( _ambientLight );
  8823. _color3.copy( _ambientLight );
  8824. _color4.copy( _ambientLight );
  8825. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8826. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8827. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8828. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8829. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8830. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8831. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8832. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8833. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8834. // TODO: UVs are incorrect, v4->v3?
  8835. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8836. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8837. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8838. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8839. } else {
  8840. _color.copy( _ambientLight );
  8841. calculateLight( element.centroidModel, element.normalModel, _color );
  8842. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8843. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8844. material.wireframe === true
  8845. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8846. : fillPath( _color );
  8847. }
  8848. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8849. _color.copy( material.color );
  8850. if ( material.vertexColors === THREE.FaceColors ) {
  8851. _color.multiply( element.color );
  8852. }
  8853. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8854. material.wireframe === true
  8855. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8856. : fillPath( _color );
  8857. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8858. var normal;
  8859. if ( material.shading == THREE.FlatShading ) {
  8860. normal = element.normalModelView;
  8861. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8862. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8863. material.wireframe === true
  8864. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8865. : fillPath( _color );
  8866. } else if ( material.shading == THREE.SmoothShading ) {
  8867. normal = element.vertexNormalsModelView[ 0 ];
  8868. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8869. normal = element.vertexNormalsModelView[ 1 ];
  8870. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8871. normal = element.vertexNormalsModelView[ 3 ];
  8872. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8873. normal = element.vertexNormalsModelView[ 2 ];
  8874. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8875. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8876. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8877. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8878. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8879. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8880. }
  8881. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8882. _near = camera.near;
  8883. _far = camera.far;
  8884. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8885. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8886. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  8887. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8888. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8889. // TODO: UVs are incorrect, v4->v3?
  8890. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8891. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8892. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8893. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8894. }
  8895. }
  8896. //
  8897. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8898. _context.beginPath();
  8899. _context.moveTo( x0, y0 );
  8900. _context.lineTo( x1, y1 );
  8901. _context.lineTo( x2, y2 );
  8902. _context.closePath();
  8903. }
  8904. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8905. _context.beginPath();
  8906. _context.moveTo( x0, y0 );
  8907. _context.lineTo( x1, y1 );
  8908. _context.lineTo( x2, y2 );
  8909. _context.lineTo( x3, y3 );
  8910. _context.closePath();
  8911. }
  8912. function strokePath( color, linewidth, linecap, linejoin ) {
  8913. setLineWidth( linewidth );
  8914. setLineCap( linecap );
  8915. setLineJoin( linejoin );
  8916. setStrokeStyle( color.getStyle() );
  8917. _context.stroke();
  8918. _elemBox.expandByScalar( linewidth * 2 );
  8919. }
  8920. function fillPath( color ) {
  8921. setFillStyle( color.getStyle() );
  8922. _context.fill();
  8923. }
  8924. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8925. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8926. if ( texture.needsUpdate === true ) {
  8927. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8928. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8929. _patterns[ texture.id ] = _context.createPattern(
  8930. texture.image, repeatX === true && repeatY === true
  8931. ? 'repeat'
  8932. : repeatX === true && repeatY === false
  8933. ? 'repeat-x'
  8934. : repeatX === false && repeatY === true
  8935. ? 'repeat-y'
  8936. : 'no-repeat'
  8937. );
  8938. texture.needsUpdate = false;
  8939. }
  8940. _patterns[ texture.id ] === undefined
  8941. ? setFillStyle( 'rgba(0,0,0,1)' )
  8942. : setFillStyle( _patterns[ texture.id ] );
  8943. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8944. var a, b, c, d, e, f, det, idet,
  8945. offsetX = texture.offset.x / texture.repeat.x,
  8946. offsetY = texture.offset.y / texture.repeat.y,
  8947. width = texture.image.width * texture.repeat.x,
  8948. height = texture.image.height * texture.repeat.y;
  8949. u0 = ( u0 + offsetX ) * width;
  8950. v0 = ( 1.0 - v0 + offsetY ) * height;
  8951. u1 = ( u1 + offsetX ) * width;
  8952. v1 = ( 1.0 - v1 + offsetY ) * height;
  8953. u2 = ( u2 + offsetX ) * width;
  8954. v2 = ( 1.0 - v2 + offsetY ) * height;
  8955. x1 -= x0; y1 -= y0;
  8956. x2 -= x0; y2 -= y0;
  8957. u1 -= u0; v1 -= v0;
  8958. u2 -= u0; v2 -= v0;
  8959. det = u1 * v2 - u2 * v1;
  8960. if ( det === 0 ) {
  8961. if ( _imagedatas[ texture.id ] === undefined ) {
  8962. var canvas = document.createElement( 'canvas' )
  8963. canvas.width = texture.image.width;
  8964. canvas.height = texture.image.height;
  8965. var context = canvas.getContext( '2d' );
  8966. context.drawImage( texture.image, 0, 0 );
  8967. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8968. }
  8969. var data = _imagedatas[ texture.id ];
  8970. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8971. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8972. fillPath( _color );
  8973. return;
  8974. }
  8975. idet = 1 / det;
  8976. a = ( v2 * x1 - v1 * x2 ) * idet;
  8977. b = ( v2 * y1 - v1 * y2 ) * idet;
  8978. c = ( u1 * x2 - u2 * x1 ) * idet;
  8979. d = ( u1 * y2 - u2 * y1 ) * idet;
  8980. e = x0 - a * u0 - c * v0;
  8981. f = y0 - b * u0 - d * v0;
  8982. _context.save();
  8983. _context.transform( a, b, c, d, e, f );
  8984. _context.fill();
  8985. _context.restore();
  8986. }
  8987. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8988. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8989. var a, b, c, d, e, f, det, idet,
  8990. width = image.width - 1,
  8991. height = image.height - 1;
  8992. u0 *= width; v0 *= height;
  8993. u1 *= width; v1 *= height;
  8994. u2 *= width; v2 *= height;
  8995. x1 -= x0; y1 -= y0;
  8996. x2 -= x0; y2 -= y0;
  8997. u1 -= u0; v1 -= v0;
  8998. u2 -= u0; v2 -= v0;
  8999. det = u1 * v2 - u2 * v1;
  9000. idet = 1 / det;
  9001. a = ( v2 * x1 - v1 * x2 ) * idet;
  9002. b = ( v2 * y1 - v1 * y2 ) * idet;
  9003. c = ( u1 * x2 - u2 * x1 ) * idet;
  9004. d = ( u1 * y2 - u2 * y1 ) * idet;
  9005. e = x0 - a * u0 - c * v0;
  9006. f = y0 - b * u0 - d * v0;
  9007. _context.save();
  9008. _context.transform( a, b, c, d, e, f );
  9009. _context.clip();
  9010. _context.drawImage( image, 0, 0 );
  9011. _context.restore();
  9012. }
  9013. function getGradientTexture( color1, color2, color3, color4 ) {
  9014. // http://mrdoob.com/blog/post/710
  9015. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9016. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9017. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9018. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9019. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9020. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9021. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9022. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9023. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9024. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9025. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9026. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9027. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9028. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9029. return _gradientMap;
  9030. }
  9031. // Hide anti-alias gaps
  9032. function expand( v1, v2 ) {
  9033. var x = v2.x - v1.x, y = v2.y - v1.y,
  9034. det = x * x + y * y, idet;
  9035. if ( det === 0 ) return;
  9036. idet = 1 / Math.sqrt( det );
  9037. x *= idet; y *= idet;
  9038. v2.x += x; v2.y += y;
  9039. v1.x -= x; v1.y -= y;
  9040. }
  9041. };
  9042. // Context cached methods.
  9043. function setOpacity( value ) {
  9044. if ( _contextGlobalAlpha !== value ) {
  9045. _context.globalAlpha = value;
  9046. _contextGlobalAlpha = value;
  9047. }
  9048. }
  9049. function setBlending( value ) {
  9050. if ( _contextGlobalCompositeOperation !== value ) {
  9051. if ( value === THREE.NormalBlending ) {
  9052. _context.globalCompositeOperation = 'source-over';
  9053. } else if ( value === THREE.AdditiveBlending ) {
  9054. _context.globalCompositeOperation = 'lighter';
  9055. } else if ( value === THREE.SubtractiveBlending ) {
  9056. _context.globalCompositeOperation = 'darker';
  9057. }
  9058. _contextGlobalCompositeOperation = value;
  9059. }
  9060. }
  9061. function setLineWidth( value ) {
  9062. if ( _contextLineWidth !== value ) {
  9063. _context.lineWidth = value;
  9064. _contextLineWidth = value;
  9065. }
  9066. }
  9067. function setLineCap( value ) {
  9068. // "butt", "round", "square"
  9069. if ( _contextLineCap !== value ) {
  9070. _context.lineCap = value;
  9071. _contextLineCap = value;
  9072. }
  9073. }
  9074. function setLineJoin( value ) {
  9075. // "round", "bevel", "miter"
  9076. if ( _contextLineJoin !== value ) {
  9077. _context.lineJoin = value;
  9078. _contextLineJoin = value;
  9079. }
  9080. }
  9081. function setStrokeStyle( value ) {
  9082. if ( _contextStrokeStyle !== value ) {
  9083. _context.strokeStyle = value;
  9084. _contextStrokeStyle = value;
  9085. }
  9086. }
  9087. function setFillStyle( value ) {
  9088. if ( _contextFillStyle !== value ) {
  9089. _context.fillStyle = value;
  9090. _contextFillStyle = value;
  9091. }
  9092. }
  9093. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9094. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9095. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9096. _contextDashSize = dashSizeValue;
  9097. _contextGapSize = gapSizeValue;
  9098. }
  9099. }
  9100. };
  9101. /**
  9102. * @author alteredq / http://alteredqualia.com/
  9103. * @author mrdoob / http://mrdoob.com/
  9104. * @author mikael emtinger / http://gomo.se/
  9105. */
  9106. THREE.ShaderChunk = {
  9107. // FOG
  9108. fog_pars_fragment: [
  9109. "#ifdef USE_FOG",
  9110. "uniform vec3 fogColor;",
  9111. "#ifdef FOG_EXP2",
  9112. "uniform float fogDensity;",
  9113. "#else",
  9114. "uniform float fogNear;",
  9115. "uniform float fogFar;",
  9116. "#endif",
  9117. "#endif"
  9118. ].join("\n"),
  9119. fog_fragment: [
  9120. "#ifdef USE_FOG",
  9121. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9122. "#ifdef FOG_EXP2",
  9123. "const float LOG2 = 1.442695;",
  9124. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9125. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9126. "#else",
  9127. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9128. "#endif",
  9129. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9130. "#endif"
  9131. ].join("\n"),
  9132. // ENVIRONMENT MAP
  9133. envmap_pars_fragment: [
  9134. "#ifdef USE_ENVMAP",
  9135. "uniform float reflectivity;",
  9136. "uniform samplerCube envMap;",
  9137. "uniform float flipEnvMap;",
  9138. "uniform int combine;",
  9139. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9140. "uniform bool useRefract;",
  9141. "uniform float refractionRatio;",
  9142. "#else",
  9143. "varying vec3 vReflect;",
  9144. "#endif",
  9145. "#endif"
  9146. ].join("\n"),
  9147. envmap_fragment: [
  9148. "#ifdef USE_ENVMAP",
  9149. "vec3 reflectVec;",
  9150. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9151. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9152. "if ( useRefract ) {",
  9153. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9154. "} else { ",
  9155. "reflectVec = reflect( cameraToVertex, normal );",
  9156. "}",
  9157. "#else",
  9158. "reflectVec = vReflect;",
  9159. "#endif",
  9160. "#ifdef DOUBLE_SIDED",
  9161. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9162. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9163. "#else",
  9164. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9165. "#endif",
  9166. "#ifdef GAMMA_INPUT",
  9167. "cubeColor.xyz *= cubeColor.xyz;",
  9168. "#endif",
  9169. "if ( combine == 1 ) {",
  9170. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9171. "} else if ( combine == 2 ) {",
  9172. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9173. "} else {",
  9174. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9175. "}",
  9176. "#endif"
  9177. ].join("\n"),
  9178. envmap_pars_vertex: [
  9179. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9180. "varying vec3 vReflect;",
  9181. "uniform float refractionRatio;",
  9182. "uniform bool useRefract;",
  9183. "#endif"
  9184. ].join("\n"),
  9185. worldpos_vertex : [
  9186. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9187. "#ifdef USE_SKINNING",
  9188. "vec4 worldPosition = modelMatrix * skinned;",
  9189. "#endif",
  9190. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9191. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9192. "#endif",
  9193. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9194. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9195. "#endif",
  9196. "#endif"
  9197. ].join("\n"),
  9198. envmap_vertex : [
  9199. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9200. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9201. "worldNormal = normalize( worldNormal );",
  9202. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9203. "if ( useRefract ) {",
  9204. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9205. "} else {",
  9206. "vReflect = reflect( cameraToVertex, worldNormal );",
  9207. "}",
  9208. "#endif"
  9209. ].join("\n"),
  9210. // COLOR MAP (particles)
  9211. map_particle_pars_fragment: [
  9212. "#ifdef USE_MAP",
  9213. "uniform sampler2D map;",
  9214. "#endif"
  9215. ].join("\n"),
  9216. map_particle_fragment: [
  9217. "#ifdef USE_MAP",
  9218. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9219. "#endif"
  9220. ].join("\n"),
  9221. // COLOR MAP (triangles)
  9222. map_pars_vertex: [
  9223. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9224. "varying vec2 vUv;",
  9225. "uniform vec4 offsetRepeat;",
  9226. "#endif"
  9227. ].join("\n"),
  9228. map_pars_fragment: [
  9229. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9230. "varying vec2 vUv;",
  9231. "#endif",
  9232. "#ifdef USE_MAP",
  9233. "uniform sampler2D map;",
  9234. "#endif"
  9235. ].join("\n"),
  9236. map_vertex: [
  9237. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9238. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9239. "#endif"
  9240. ].join("\n"),
  9241. map_fragment: [
  9242. "#ifdef USE_MAP",
  9243. "vec4 texelColor = texture2D( map, vUv );",
  9244. "#ifdef GAMMA_INPUT",
  9245. "texelColor.xyz *= texelColor.xyz;",
  9246. "#endif",
  9247. "gl_FragColor = gl_FragColor * texelColor;",
  9248. "#endif"
  9249. ].join("\n"),
  9250. // LIGHT MAP
  9251. lightmap_pars_fragment: [
  9252. "#ifdef USE_LIGHTMAP",
  9253. "varying vec2 vUv2;",
  9254. "uniform sampler2D lightMap;",
  9255. "#endif"
  9256. ].join("\n"),
  9257. lightmap_pars_vertex: [
  9258. "#ifdef USE_LIGHTMAP",
  9259. "varying vec2 vUv2;",
  9260. "#endif"
  9261. ].join("\n"),
  9262. lightmap_fragment: [
  9263. "#ifdef USE_LIGHTMAP",
  9264. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9265. "#endif"
  9266. ].join("\n"),
  9267. lightmap_vertex: [
  9268. "#ifdef USE_LIGHTMAP",
  9269. "vUv2 = uv2;",
  9270. "#endif"
  9271. ].join("\n"),
  9272. // BUMP MAP
  9273. bumpmap_pars_fragment: [
  9274. "#ifdef USE_BUMPMAP",
  9275. "uniform sampler2D bumpMap;",
  9276. "uniform float bumpScale;",
  9277. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9278. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9279. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9280. "vec2 dHdxy_fwd() {",
  9281. "vec2 dSTdx = dFdx( vUv );",
  9282. "vec2 dSTdy = dFdy( vUv );",
  9283. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9284. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9285. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9286. "return vec2( dBx, dBy );",
  9287. "}",
  9288. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9289. "vec3 vSigmaX = dFdx( surf_pos );",
  9290. "vec3 vSigmaY = dFdy( surf_pos );",
  9291. "vec3 vN = surf_norm;", // normalized
  9292. "vec3 R1 = cross( vSigmaY, vN );",
  9293. "vec3 R2 = cross( vN, vSigmaX );",
  9294. "float fDet = dot( vSigmaX, R1 );",
  9295. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9296. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9297. "}",
  9298. "#endif"
  9299. ].join("\n"),
  9300. // NORMAL MAP
  9301. normalmap_pars_fragment: [
  9302. "#ifdef USE_NORMALMAP",
  9303. "uniform sampler2D normalMap;",
  9304. "uniform vec2 normalScale;",
  9305. // Per-Pixel Tangent Space Normal Mapping
  9306. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9307. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9308. "vec3 q0 = dFdx( eye_pos.xyz );",
  9309. "vec3 q1 = dFdy( eye_pos.xyz );",
  9310. "vec2 st0 = dFdx( vUv.st );",
  9311. "vec2 st1 = dFdy( vUv.st );",
  9312. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9313. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9314. "vec3 N = normalize( surf_norm );",
  9315. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9316. "mapN.xy = normalScale * mapN.xy;",
  9317. "mat3 tsn = mat3( S, T, N );",
  9318. "return normalize( tsn * mapN );",
  9319. "}",
  9320. "#endif"
  9321. ].join("\n"),
  9322. // SPECULAR MAP
  9323. specularmap_pars_fragment: [
  9324. "#ifdef USE_SPECULARMAP",
  9325. "uniform sampler2D specularMap;",
  9326. "#endif"
  9327. ].join("\n"),
  9328. specularmap_fragment: [
  9329. "float specularStrength;",
  9330. "#ifdef USE_SPECULARMAP",
  9331. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9332. "specularStrength = texelSpecular.r;",
  9333. "#else",
  9334. "specularStrength = 1.0;",
  9335. "#endif"
  9336. ].join("\n"),
  9337. // LIGHTS LAMBERT
  9338. lights_lambert_pars_vertex: [
  9339. "uniform vec3 ambient;",
  9340. "uniform vec3 diffuse;",
  9341. "uniform vec3 emissive;",
  9342. "uniform vec3 ambientLightColor;",
  9343. "#if MAX_DIR_LIGHTS > 0",
  9344. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9345. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9346. "#endif",
  9347. "#if MAX_HEMI_LIGHTS > 0",
  9348. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9349. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9350. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9351. "#endif",
  9352. "#if MAX_POINT_LIGHTS > 0",
  9353. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9354. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9355. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9356. "#endif",
  9357. "#if MAX_SPOT_LIGHTS > 0",
  9358. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9359. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9360. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9361. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9362. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9363. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9364. "#endif",
  9365. "#ifdef WRAP_AROUND",
  9366. "uniform vec3 wrapRGB;",
  9367. "#endif"
  9368. ].join("\n"),
  9369. lights_lambert_vertex: [
  9370. "vLightFront = vec3( 0.0 );",
  9371. "#ifdef DOUBLE_SIDED",
  9372. "vLightBack = vec3( 0.0 );",
  9373. "#endif",
  9374. "transformedNormal = normalize( transformedNormal );",
  9375. "#if MAX_DIR_LIGHTS > 0",
  9376. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9377. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9378. "vec3 dirVector = normalize( lDirection.xyz );",
  9379. "float dotProduct = dot( transformedNormal, dirVector );",
  9380. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9381. "#ifdef DOUBLE_SIDED",
  9382. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9383. "#ifdef WRAP_AROUND",
  9384. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9385. "#endif",
  9386. "#endif",
  9387. "#ifdef WRAP_AROUND",
  9388. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9389. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9390. "#ifdef DOUBLE_SIDED",
  9391. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9392. "#endif",
  9393. "#endif",
  9394. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9395. "#ifdef DOUBLE_SIDED",
  9396. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9397. "#endif",
  9398. "}",
  9399. "#endif",
  9400. "#if MAX_POINT_LIGHTS > 0",
  9401. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9402. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9403. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9404. "float lDistance = 1.0;",
  9405. "if ( pointLightDistance[ i ] > 0.0 )",
  9406. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9407. "lVector = normalize( lVector );",
  9408. "float dotProduct = dot( transformedNormal, lVector );",
  9409. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9410. "#ifdef DOUBLE_SIDED",
  9411. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9412. "#ifdef WRAP_AROUND",
  9413. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9414. "#endif",
  9415. "#endif",
  9416. "#ifdef WRAP_AROUND",
  9417. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9418. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9419. "#ifdef DOUBLE_SIDED",
  9420. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9421. "#endif",
  9422. "#endif",
  9423. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9424. "#ifdef DOUBLE_SIDED",
  9425. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9426. "#endif",
  9427. "}",
  9428. "#endif",
  9429. "#if MAX_SPOT_LIGHTS > 0",
  9430. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9431. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9432. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9433. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9434. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9435. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9436. "float lDistance = 1.0;",
  9437. "if ( spotLightDistance[ i ] > 0.0 )",
  9438. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9439. "lVector = normalize( lVector );",
  9440. "float dotProduct = dot( transformedNormal, lVector );",
  9441. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9442. "#ifdef DOUBLE_SIDED",
  9443. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9444. "#ifdef WRAP_AROUND",
  9445. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9446. "#endif",
  9447. "#endif",
  9448. "#ifdef WRAP_AROUND",
  9449. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9450. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9451. "#ifdef DOUBLE_SIDED",
  9452. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9453. "#endif",
  9454. "#endif",
  9455. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9456. "#ifdef DOUBLE_SIDED",
  9457. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9458. "#endif",
  9459. "}",
  9460. "}",
  9461. "#endif",
  9462. "#if MAX_HEMI_LIGHTS > 0",
  9463. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9464. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9465. "vec3 lVector = normalize( lDirection.xyz );",
  9466. "float dotProduct = dot( transformedNormal, lVector );",
  9467. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9468. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9469. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9470. "#ifdef DOUBLE_SIDED",
  9471. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9472. "#endif",
  9473. "}",
  9474. "#endif",
  9475. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9476. "#ifdef DOUBLE_SIDED",
  9477. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9478. "#endif"
  9479. ].join("\n"),
  9480. // LIGHTS PHONG
  9481. lights_phong_pars_vertex: [
  9482. "#ifndef PHONG_PER_PIXEL",
  9483. "#if MAX_POINT_LIGHTS > 0",
  9484. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9485. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9486. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9487. "#endif",
  9488. "#if MAX_SPOT_LIGHTS > 0",
  9489. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9490. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9491. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9492. "#endif",
  9493. "#endif",
  9494. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9495. "varying vec3 vWorldPosition;",
  9496. "#endif"
  9497. ].join("\n"),
  9498. lights_phong_vertex: [
  9499. "#ifndef PHONG_PER_PIXEL",
  9500. "#if MAX_POINT_LIGHTS > 0",
  9501. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9502. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9503. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9504. "float lDistance = 1.0;",
  9505. "if ( pointLightDistance[ i ] > 0.0 )",
  9506. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9507. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9508. "}",
  9509. "#endif",
  9510. "#if MAX_SPOT_LIGHTS > 0",
  9511. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9512. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9513. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9514. "float lDistance = 1.0;",
  9515. "if ( spotLightDistance[ i ] > 0.0 )",
  9516. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9517. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9518. "}",
  9519. "#endif",
  9520. "#endif",
  9521. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9522. "vWorldPosition = worldPosition.xyz;",
  9523. "#endif"
  9524. ].join("\n"),
  9525. lights_phong_pars_fragment: [
  9526. "uniform vec3 ambientLightColor;",
  9527. "#if MAX_DIR_LIGHTS > 0",
  9528. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9529. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9530. "#endif",
  9531. "#if MAX_HEMI_LIGHTS > 0",
  9532. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9533. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9534. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9535. "#endif",
  9536. "#if MAX_POINT_LIGHTS > 0",
  9537. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9538. "#ifdef PHONG_PER_PIXEL",
  9539. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9540. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9541. "#else",
  9542. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9543. "#endif",
  9544. "#endif",
  9545. "#if MAX_SPOT_LIGHTS > 0",
  9546. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9547. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9548. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9549. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9550. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9551. "#ifdef PHONG_PER_PIXEL",
  9552. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9553. "#else",
  9554. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9555. "#endif",
  9556. "#endif",
  9557. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9558. "varying vec3 vWorldPosition;",
  9559. "#endif",
  9560. "#ifdef WRAP_AROUND",
  9561. "uniform vec3 wrapRGB;",
  9562. "#endif",
  9563. "varying vec3 vViewPosition;",
  9564. "varying vec3 vNormal;"
  9565. ].join("\n"),
  9566. lights_phong_fragment: [
  9567. "vec3 normal = normalize( vNormal );",
  9568. "vec3 viewPosition = normalize( vViewPosition );",
  9569. "#ifdef DOUBLE_SIDED",
  9570. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9571. "#endif",
  9572. "#ifdef USE_NORMALMAP",
  9573. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  9574. "#elif defined( USE_BUMPMAP )",
  9575. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9576. "#endif",
  9577. "#if MAX_POINT_LIGHTS > 0",
  9578. "vec3 pointDiffuse = vec3( 0.0 );",
  9579. "vec3 pointSpecular = vec3( 0.0 );",
  9580. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9581. "#ifdef PHONG_PER_PIXEL",
  9582. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9583. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9584. "float lDistance = 1.0;",
  9585. "if ( pointLightDistance[ i ] > 0.0 )",
  9586. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9587. "lVector = normalize( lVector );",
  9588. "#else",
  9589. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9590. "float lDistance = vPointLight[ i ].w;",
  9591. "#endif",
  9592. // diffuse
  9593. "float dotProduct = dot( normal, lVector );",
  9594. "#ifdef WRAP_AROUND",
  9595. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9596. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9597. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9598. "#else",
  9599. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9600. "#endif",
  9601. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9602. // specular
  9603. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9604. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9605. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9606. "#ifdef PHYSICALLY_BASED_SHADING",
  9607. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9608. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9609. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9610. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9611. "#else",
  9612. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9613. "#endif",
  9614. "}",
  9615. "#endif",
  9616. "#if MAX_SPOT_LIGHTS > 0",
  9617. "vec3 spotDiffuse = vec3( 0.0 );",
  9618. "vec3 spotSpecular = vec3( 0.0 );",
  9619. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9620. "#ifdef PHONG_PER_PIXEL",
  9621. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9622. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9623. "float lDistance = 1.0;",
  9624. "if ( spotLightDistance[ i ] > 0.0 )",
  9625. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9626. "lVector = normalize( lVector );",
  9627. "#else",
  9628. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9629. "float lDistance = vSpotLight[ i ].w;",
  9630. "#endif",
  9631. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9632. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9633. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9634. // diffuse
  9635. "float dotProduct = dot( normal, lVector );",
  9636. "#ifdef WRAP_AROUND",
  9637. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9638. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9639. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9640. "#else",
  9641. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9642. "#endif",
  9643. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9644. // specular
  9645. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9646. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9647. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9648. "#ifdef PHYSICALLY_BASED_SHADING",
  9649. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9650. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9651. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9652. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9653. "#else",
  9654. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9655. "#endif",
  9656. "}",
  9657. "}",
  9658. "#endif",
  9659. "#if MAX_DIR_LIGHTS > 0",
  9660. "vec3 dirDiffuse = vec3( 0.0 );",
  9661. "vec3 dirSpecular = vec3( 0.0 );" ,
  9662. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9663. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9664. "vec3 dirVector = normalize( lDirection.xyz );",
  9665. // diffuse
  9666. "float dotProduct = dot( normal, dirVector );",
  9667. "#ifdef WRAP_AROUND",
  9668. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9669. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9670. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9671. "#else",
  9672. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9673. "#endif",
  9674. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9675. // specular
  9676. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9677. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9678. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9679. "#ifdef PHYSICALLY_BASED_SHADING",
  9680. /*
  9681. // fresnel term from skin shader
  9682. "const float F0 = 0.128;",
  9683. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9684. "float exponential = pow( base, 5.0 );",
  9685. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9686. */
  9687. /*
  9688. // fresnel term from fresnel shader
  9689. "const float mFresnelBias = 0.08;",
  9690. "const float mFresnelScale = 0.3;",
  9691. "const float mFresnelPower = 5.0;",
  9692. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9693. */
  9694. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9695. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9696. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9697. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9698. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9699. "#else",
  9700. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9701. "#endif",
  9702. "}",
  9703. "#endif",
  9704. "#if MAX_HEMI_LIGHTS > 0",
  9705. "vec3 hemiDiffuse = vec3( 0.0 );",
  9706. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9707. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9708. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9709. "vec3 lVector = normalize( lDirection.xyz );",
  9710. // diffuse
  9711. "float dotProduct = dot( normal, lVector );",
  9712. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9713. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9714. "hemiDiffuse += diffuse * hemiColor;",
  9715. // specular (sky light)
  9716. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9717. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9718. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9719. // specular (ground light)
  9720. "vec3 lVectorGround = -lVector;",
  9721. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9722. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9723. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9724. "#ifdef PHYSICALLY_BASED_SHADING",
  9725. "float dotProductGround = dot( normal, lVectorGround );",
  9726. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9727. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9728. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9729. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9730. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9731. "#else",
  9732. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9733. "#endif",
  9734. "}",
  9735. "#endif",
  9736. "vec3 totalDiffuse = vec3( 0.0 );",
  9737. "vec3 totalSpecular = vec3( 0.0 );",
  9738. "#if MAX_DIR_LIGHTS > 0",
  9739. "totalDiffuse += dirDiffuse;",
  9740. "totalSpecular += dirSpecular;",
  9741. "#endif",
  9742. "#if MAX_HEMI_LIGHTS > 0",
  9743. "totalDiffuse += hemiDiffuse;",
  9744. "totalSpecular += hemiSpecular;",
  9745. "#endif",
  9746. "#if MAX_POINT_LIGHTS > 0",
  9747. "totalDiffuse += pointDiffuse;",
  9748. "totalSpecular += pointSpecular;",
  9749. "#endif",
  9750. "#if MAX_SPOT_LIGHTS > 0",
  9751. "totalDiffuse += spotDiffuse;",
  9752. "totalSpecular += spotSpecular;",
  9753. "#endif",
  9754. "#ifdef METAL",
  9755. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9756. "#else",
  9757. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9758. "#endif"
  9759. ].join("\n"),
  9760. // VERTEX COLORS
  9761. color_pars_fragment: [
  9762. "#ifdef USE_COLOR",
  9763. "varying vec3 vColor;",
  9764. "#endif"
  9765. ].join("\n"),
  9766. color_fragment: [
  9767. "#ifdef USE_COLOR",
  9768. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9769. "#endif"
  9770. ].join("\n"),
  9771. color_pars_vertex: [
  9772. "#ifdef USE_COLOR",
  9773. "varying vec3 vColor;",
  9774. "#endif"
  9775. ].join("\n"),
  9776. color_vertex: [
  9777. "#ifdef USE_COLOR",
  9778. "#ifdef GAMMA_INPUT",
  9779. "vColor = color * color;",
  9780. "#else",
  9781. "vColor = color;",
  9782. "#endif",
  9783. "#endif"
  9784. ].join("\n"),
  9785. // SKINNING
  9786. skinning_pars_vertex: [
  9787. "#ifdef USE_SKINNING",
  9788. "#ifdef BONE_TEXTURE",
  9789. "uniform sampler2D boneTexture;",
  9790. "mat4 getBoneMatrix( const in float i ) {",
  9791. "float j = i * 4.0;",
  9792. "float x = mod( j, N_BONE_PIXEL_X );",
  9793. "float y = floor( j / N_BONE_PIXEL_X );",
  9794. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9795. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9796. "y = dy * ( y + 0.5 );",
  9797. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9798. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9799. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9800. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9801. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9802. "return bone;",
  9803. "}",
  9804. "#else",
  9805. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9806. "mat4 getBoneMatrix( const in float i ) {",
  9807. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9808. "return bone;",
  9809. "}",
  9810. "#endif",
  9811. "#endif"
  9812. ].join("\n"),
  9813. skinbase_vertex: [
  9814. "#ifdef USE_SKINNING",
  9815. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9816. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9817. "#endif"
  9818. ].join("\n"),
  9819. skinning_vertex: [
  9820. "#ifdef USE_SKINNING",
  9821. "#ifdef USE_MORPHTARGETS",
  9822. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9823. "#else",
  9824. "vec4 skinVertex = vec4( position, 1.0 );",
  9825. "#endif",
  9826. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9827. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9828. "#endif"
  9829. ].join("\n"),
  9830. // MORPHING
  9831. morphtarget_pars_vertex: [
  9832. "#ifdef USE_MORPHTARGETS",
  9833. "#ifndef USE_MORPHNORMALS",
  9834. "uniform float morphTargetInfluences[ 8 ];",
  9835. "#else",
  9836. "uniform float morphTargetInfluences[ 4 ];",
  9837. "#endif",
  9838. "#endif"
  9839. ].join("\n"),
  9840. morphtarget_vertex: [
  9841. "#ifdef USE_MORPHTARGETS",
  9842. "vec3 morphed = vec3( 0.0 );",
  9843. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9844. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9845. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9846. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9847. "#ifndef USE_MORPHNORMALS",
  9848. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9849. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9850. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9851. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9852. "#endif",
  9853. "morphed += position;",
  9854. "#endif"
  9855. ].join("\n"),
  9856. default_vertex : [
  9857. "vec4 mvPosition;",
  9858. "#ifdef USE_SKINNING",
  9859. "mvPosition = modelViewMatrix * skinned;",
  9860. "#endif",
  9861. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9862. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9863. "#endif",
  9864. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9865. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9866. "#endif",
  9867. "gl_Position = projectionMatrix * mvPosition;"
  9868. ].join("\n"),
  9869. morphnormal_vertex: [
  9870. "#ifdef USE_MORPHNORMALS",
  9871. "vec3 morphedNormal = vec3( 0.0 );",
  9872. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9873. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9874. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9875. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9876. "morphedNormal += normal;",
  9877. "#endif"
  9878. ].join("\n"),
  9879. skinnormal_vertex: [
  9880. "#ifdef USE_SKINNING",
  9881. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9882. "skinMatrix += skinWeight.y * boneMatY;",
  9883. "#ifdef USE_MORPHNORMALS",
  9884. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9885. "#else",
  9886. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9887. "#endif",
  9888. "#endif"
  9889. ].join("\n"),
  9890. defaultnormal_vertex: [
  9891. "vec3 objectNormal;",
  9892. "#ifdef USE_SKINNING",
  9893. "objectNormal = skinnedNormal.xyz;",
  9894. "#endif",
  9895. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9896. "objectNormal = morphedNormal;",
  9897. "#endif",
  9898. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9899. "objectNormal = normal;",
  9900. "#endif",
  9901. "#ifdef FLIP_SIDED",
  9902. "objectNormal = -objectNormal;",
  9903. "#endif",
  9904. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9905. ].join("\n"),
  9906. // SHADOW MAP
  9907. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9908. // http://spidergl.org/example.php?id=6
  9909. // http://fabiensanglard.net/shadowmapping
  9910. shadowmap_pars_fragment: [
  9911. "#ifdef USE_SHADOWMAP",
  9912. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9913. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9914. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9915. "uniform float shadowBias[ MAX_SHADOWS ];",
  9916. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9917. "float unpackDepth( const in vec4 rgba_depth ) {",
  9918. "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 );",
  9919. "float depth = dot( rgba_depth, bit_shift );",
  9920. "return depth;",
  9921. "}",
  9922. "#endif"
  9923. ].join("\n"),
  9924. shadowmap_fragment: [
  9925. "#ifdef USE_SHADOWMAP",
  9926. "#ifdef SHADOWMAP_DEBUG",
  9927. "vec3 frustumColors[3];",
  9928. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9929. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9930. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9931. "#endif",
  9932. "#ifdef SHADOWMAP_CASCADE",
  9933. "int inFrustumCount = 0;",
  9934. "#endif",
  9935. "float fDepth;",
  9936. "vec3 shadowColor = vec3( 1.0 );",
  9937. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9938. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9939. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9940. // "if ( all( something, something ) )" using this instead
  9941. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9942. "bool inFrustum = all( inFrustumVec );",
  9943. // don't shadow pixels outside of light frustum
  9944. // use just first frustum (for cascades)
  9945. // don't shadow pixels behind far plane of light frustum
  9946. "#ifdef SHADOWMAP_CASCADE",
  9947. "inFrustumCount += int( inFrustum );",
  9948. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9949. "#else",
  9950. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9951. "#endif",
  9952. "bool frustumTest = all( frustumTestVec );",
  9953. "if ( frustumTest ) {",
  9954. "shadowCoord.z += shadowBias[ i ];",
  9955. "#if defined( SHADOWMAP_TYPE_PCF )",
  9956. // Percentage-close filtering
  9957. // (9 pixel kernel)
  9958. // http://fabiensanglard.net/shadowmappingPCF/
  9959. "float shadow = 0.0;",
  9960. /*
  9961. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9962. // must enroll loop manually
  9963. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9964. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9965. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9966. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9967. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9968. "float fDepth = unpackDepth( rgbaDepth );",
  9969. "if ( fDepth < shadowCoord.z )",
  9970. "shadow += 1.0;",
  9971. "}",
  9972. "shadow /= 9.0;",
  9973. */
  9974. "const float shadowDelta = 1.0 / 9.0;",
  9975. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9976. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9977. "float dx0 = -1.25 * xPixelOffset;",
  9978. "float dy0 = -1.25 * yPixelOffset;",
  9979. "float dx1 = 1.25 * xPixelOffset;",
  9980. "float dy1 = 1.25 * yPixelOffset;",
  9981. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9982. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9983. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9984. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9985. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9986. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9987. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9988. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9989. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9990. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9991. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9992. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9993. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9994. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9995. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9996. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9997. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9998. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9999. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10000. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10001. // Percentage-close filtering
  10002. // (9 pixel kernel)
  10003. // http://fabiensanglard.net/shadowmappingPCF/
  10004. "float shadow = 0.0;",
  10005. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10006. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10007. "float dx0 = -1.0 * xPixelOffset;",
  10008. "float dy0 = -1.0 * yPixelOffset;",
  10009. "float dx1 = 1.0 * xPixelOffset;",
  10010. "float dy1 = 1.0 * yPixelOffset;",
  10011. "mat3 shadowKernel;",
  10012. "mat3 depthKernel;",
  10013. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10014. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10015. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10016. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10017. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10018. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10019. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10020. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10021. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10022. "vec3 shadowZ = vec3( shadowCoord.z );",
  10023. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10024. "shadowKernel[0] *= vec3(0.25);",
  10025. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10026. "shadowKernel[1] *= vec3(0.25);",
  10027. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10028. "shadowKernel[2] *= vec3(0.25);",
  10029. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10030. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10031. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10032. "vec4 shadowValues;",
  10033. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10034. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10035. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10036. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10037. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10038. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10039. "#else",
  10040. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10041. "float fDepth = unpackDepth( rgbaDepth );",
  10042. "if ( fDepth < shadowCoord.z )",
  10043. // spot with multiple shadows is darker
  10044. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10045. // spot with multiple shadows has the same color as single shadow spot
  10046. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10047. "#endif",
  10048. "}",
  10049. "#ifdef SHADOWMAP_DEBUG",
  10050. "#ifdef SHADOWMAP_CASCADE",
  10051. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10052. "#else",
  10053. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10054. "#endif",
  10055. "#endif",
  10056. "}",
  10057. "#ifdef GAMMA_OUTPUT",
  10058. "shadowColor *= shadowColor;",
  10059. "#endif",
  10060. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10061. "#endif"
  10062. ].join("\n"),
  10063. shadowmap_pars_vertex: [
  10064. "#ifdef USE_SHADOWMAP",
  10065. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10066. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10067. "#endif"
  10068. ].join("\n"),
  10069. shadowmap_vertex: [
  10070. "#ifdef USE_SHADOWMAP",
  10071. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10072. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10073. "}",
  10074. "#endif"
  10075. ].join("\n"),
  10076. // ALPHATEST
  10077. alphatest_fragment: [
  10078. "#ifdef ALPHATEST",
  10079. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10080. "#endif"
  10081. ].join("\n"),
  10082. // LINEAR SPACE
  10083. linear_to_gamma_fragment: [
  10084. "#ifdef GAMMA_OUTPUT",
  10085. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10086. "#endif"
  10087. ].join("\n")
  10088. };
  10089. THREE.UniformsUtils = {
  10090. merge: function ( uniforms ) {
  10091. var u, p, tmp, merged = {};
  10092. for ( u = 0; u < uniforms.length; u ++ ) {
  10093. tmp = this.clone( uniforms[ u ] );
  10094. for ( p in tmp ) {
  10095. merged[ p ] = tmp[ p ];
  10096. }
  10097. }
  10098. return merged;
  10099. },
  10100. clone: function ( uniforms_src ) {
  10101. var u, p, parameter, parameter_src, uniforms_dst = {};
  10102. for ( u in uniforms_src ) {
  10103. uniforms_dst[ u ] = {};
  10104. for ( p in uniforms_src[ u ] ) {
  10105. parameter_src = uniforms_src[ u ][ p ];
  10106. if ( parameter_src instanceof THREE.Color ||
  10107. parameter_src instanceof THREE.Vector2 ||
  10108. parameter_src instanceof THREE.Vector3 ||
  10109. parameter_src instanceof THREE.Vector4 ||
  10110. parameter_src instanceof THREE.Matrix4 ||
  10111. parameter_src instanceof THREE.Texture ) {
  10112. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10113. } else if ( parameter_src instanceof Array ) {
  10114. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10115. } else {
  10116. uniforms_dst[ u ][ p ] = parameter_src;
  10117. }
  10118. }
  10119. }
  10120. return uniforms_dst;
  10121. }
  10122. };
  10123. THREE.UniformsLib = {
  10124. common: {
  10125. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10126. "opacity" : { type: "f", value: 1.0 },
  10127. "map" : { type: "t", value: null },
  10128. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10129. "lightMap" : { type: "t", value: null },
  10130. "specularMap" : { type: "t", value: null },
  10131. "envMap" : { type: "t", value: null },
  10132. "flipEnvMap" : { type: "f", value: -1 },
  10133. "useRefract" : { type: "i", value: 0 },
  10134. "reflectivity" : { type: "f", value: 1.0 },
  10135. "refractionRatio" : { type: "f", value: 0.98 },
  10136. "combine" : { type: "i", value: 0 },
  10137. "morphTargetInfluences" : { type: "f", value: 0 }
  10138. },
  10139. bump: {
  10140. "bumpMap" : { type: "t", value: null },
  10141. "bumpScale" : { type: "f", value: 1 }
  10142. },
  10143. normalmap: {
  10144. "normalMap" : { type: "t", value: null },
  10145. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10146. },
  10147. fog : {
  10148. "fogDensity" : { type: "f", value: 0.00025 },
  10149. "fogNear" : { type: "f", value: 1 },
  10150. "fogFar" : { type: "f", value: 2000 },
  10151. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10152. },
  10153. lights: {
  10154. "ambientLightColor" : { type: "fv", value: [] },
  10155. "directionalLightDirection" : { type: "fv", value: [] },
  10156. "directionalLightColor" : { type: "fv", value: [] },
  10157. "hemisphereLightDirection" : { type: "fv", value: [] },
  10158. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10159. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10160. "pointLightColor" : { type: "fv", value: [] },
  10161. "pointLightPosition" : { type: "fv", value: [] },
  10162. "pointLightDistance" : { type: "fv1", value: [] },
  10163. "spotLightColor" : { type: "fv", value: [] },
  10164. "spotLightPosition" : { type: "fv", value: [] },
  10165. "spotLightDirection" : { type: "fv", value: [] },
  10166. "spotLightDistance" : { type: "fv1", value: [] },
  10167. "spotLightAngleCos" : { type: "fv1", value: [] },
  10168. "spotLightExponent" : { type: "fv1", value: [] }
  10169. },
  10170. particle: {
  10171. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10172. "opacity" : { type: "f", value: 1.0 },
  10173. "size" : { type: "f", value: 1.0 },
  10174. "scale" : { type: "f", value: 1.0 },
  10175. "map" : { type: "t", value: null },
  10176. "fogDensity" : { type: "f", value: 0.00025 },
  10177. "fogNear" : { type: "f", value: 1 },
  10178. "fogFar" : { type: "f", value: 2000 },
  10179. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10180. },
  10181. shadowmap: {
  10182. "shadowMap": { type: "tv", value: [] },
  10183. "shadowMapSize": { type: "v2v", value: [] },
  10184. "shadowBias" : { type: "fv1", value: [] },
  10185. "shadowDarkness": { type: "fv1", value: [] },
  10186. "shadowMatrix" : { type: "m4v", value: [] }
  10187. }
  10188. };
  10189. THREE.ShaderLib = {
  10190. 'basic': {
  10191. uniforms: THREE.UniformsUtils.merge( [
  10192. THREE.UniformsLib[ "common" ],
  10193. THREE.UniformsLib[ "fog" ],
  10194. THREE.UniformsLib[ "shadowmap" ]
  10195. ] ),
  10196. vertexShader: [
  10197. THREE.ShaderChunk[ "map_pars_vertex" ],
  10198. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10199. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10200. THREE.ShaderChunk[ "color_pars_vertex" ],
  10201. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10202. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10203. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10204. "void main() {",
  10205. THREE.ShaderChunk[ "map_vertex" ],
  10206. THREE.ShaderChunk[ "lightmap_vertex" ],
  10207. THREE.ShaderChunk[ "color_vertex" ],
  10208. THREE.ShaderChunk[ "skinbase_vertex" ],
  10209. "#ifdef USE_ENVMAP",
  10210. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10211. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10212. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10213. "#endif",
  10214. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10215. THREE.ShaderChunk[ "skinning_vertex" ],
  10216. THREE.ShaderChunk[ "default_vertex" ],
  10217. THREE.ShaderChunk[ "worldpos_vertex" ],
  10218. THREE.ShaderChunk[ "envmap_vertex" ],
  10219. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10220. "}"
  10221. ].join("\n"),
  10222. fragmentShader: [
  10223. "uniform vec3 diffuse;",
  10224. "uniform float opacity;",
  10225. THREE.ShaderChunk[ "color_pars_fragment" ],
  10226. THREE.ShaderChunk[ "map_pars_fragment" ],
  10227. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10228. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10229. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10230. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10231. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10232. "void main() {",
  10233. "gl_FragColor = vec4( diffuse, opacity );",
  10234. THREE.ShaderChunk[ "map_fragment" ],
  10235. THREE.ShaderChunk[ "alphatest_fragment" ],
  10236. THREE.ShaderChunk[ "specularmap_fragment" ],
  10237. THREE.ShaderChunk[ "lightmap_fragment" ],
  10238. THREE.ShaderChunk[ "color_fragment" ],
  10239. THREE.ShaderChunk[ "envmap_fragment" ],
  10240. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10241. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10242. THREE.ShaderChunk[ "fog_fragment" ],
  10243. "}"
  10244. ].join("\n")
  10245. },
  10246. 'lambert': {
  10247. uniforms: THREE.UniformsUtils.merge( [
  10248. THREE.UniformsLib[ "common" ],
  10249. THREE.UniformsLib[ "fog" ],
  10250. THREE.UniformsLib[ "lights" ],
  10251. THREE.UniformsLib[ "shadowmap" ],
  10252. {
  10253. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10254. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10255. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10256. }
  10257. ] ),
  10258. vertexShader: [
  10259. "#define LAMBERT",
  10260. "varying vec3 vLightFront;",
  10261. "#ifdef DOUBLE_SIDED",
  10262. "varying vec3 vLightBack;",
  10263. "#endif",
  10264. THREE.ShaderChunk[ "map_pars_vertex" ],
  10265. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10266. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10267. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10268. THREE.ShaderChunk[ "color_pars_vertex" ],
  10269. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10270. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10271. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10272. "void main() {",
  10273. THREE.ShaderChunk[ "map_vertex" ],
  10274. THREE.ShaderChunk[ "lightmap_vertex" ],
  10275. THREE.ShaderChunk[ "color_vertex" ],
  10276. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10277. THREE.ShaderChunk[ "skinbase_vertex" ],
  10278. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10279. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10280. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10281. THREE.ShaderChunk[ "skinning_vertex" ],
  10282. THREE.ShaderChunk[ "default_vertex" ],
  10283. THREE.ShaderChunk[ "worldpos_vertex" ],
  10284. THREE.ShaderChunk[ "envmap_vertex" ],
  10285. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10286. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10287. "}"
  10288. ].join("\n"),
  10289. fragmentShader: [
  10290. "uniform float opacity;",
  10291. "varying vec3 vLightFront;",
  10292. "#ifdef DOUBLE_SIDED",
  10293. "varying vec3 vLightBack;",
  10294. "#endif",
  10295. THREE.ShaderChunk[ "color_pars_fragment" ],
  10296. THREE.ShaderChunk[ "map_pars_fragment" ],
  10297. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10298. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10299. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10300. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10301. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10302. "void main() {",
  10303. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10304. THREE.ShaderChunk[ "map_fragment" ],
  10305. THREE.ShaderChunk[ "alphatest_fragment" ],
  10306. THREE.ShaderChunk[ "specularmap_fragment" ],
  10307. "#ifdef DOUBLE_SIDED",
  10308. //"float isFront = float( gl_FrontFacing );",
  10309. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10310. "if ( gl_FrontFacing )",
  10311. "gl_FragColor.xyz *= vLightFront;",
  10312. "else",
  10313. "gl_FragColor.xyz *= vLightBack;",
  10314. "#else",
  10315. "gl_FragColor.xyz *= vLightFront;",
  10316. "#endif",
  10317. THREE.ShaderChunk[ "lightmap_fragment" ],
  10318. THREE.ShaderChunk[ "color_fragment" ],
  10319. THREE.ShaderChunk[ "envmap_fragment" ],
  10320. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10321. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10322. THREE.ShaderChunk[ "fog_fragment" ],
  10323. "}"
  10324. ].join("\n")
  10325. },
  10326. 'phong': {
  10327. uniforms: THREE.UniformsUtils.merge( [
  10328. THREE.UniformsLib[ "common" ],
  10329. THREE.UniformsLib[ "bump" ],
  10330. THREE.UniformsLib[ "normalmap" ],
  10331. THREE.UniformsLib[ "fog" ],
  10332. THREE.UniformsLib[ "lights" ],
  10333. THREE.UniformsLib[ "shadowmap" ],
  10334. {
  10335. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10336. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10337. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10338. "shininess": { type: "f", value: 30 },
  10339. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10340. }
  10341. ] ),
  10342. vertexShader: [
  10343. "#define PHONG",
  10344. "varying vec3 vViewPosition;",
  10345. "varying vec3 vNormal;",
  10346. THREE.ShaderChunk[ "map_pars_vertex" ],
  10347. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10348. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10349. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10350. THREE.ShaderChunk[ "color_pars_vertex" ],
  10351. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10352. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10353. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10354. "void main() {",
  10355. THREE.ShaderChunk[ "map_vertex" ],
  10356. THREE.ShaderChunk[ "lightmap_vertex" ],
  10357. THREE.ShaderChunk[ "color_vertex" ],
  10358. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10359. THREE.ShaderChunk[ "skinbase_vertex" ],
  10360. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10361. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10362. "vNormal = normalize( transformedNormal );",
  10363. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10364. THREE.ShaderChunk[ "skinning_vertex" ],
  10365. THREE.ShaderChunk[ "default_vertex" ],
  10366. "vViewPosition = -mvPosition.xyz;",
  10367. THREE.ShaderChunk[ "worldpos_vertex" ],
  10368. THREE.ShaderChunk[ "envmap_vertex" ],
  10369. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10370. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10371. "}"
  10372. ].join("\n"),
  10373. fragmentShader: [
  10374. "uniform vec3 diffuse;",
  10375. "uniform float opacity;",
  10376. "uniform vec3 ambient;",
  10377. "uniform vec3 emissive;",
  10378. "uniform vec3 specular;",
  10379. "uniform float shininess;",
  10380. THREE.ShaderChunk[ "color_pars_fragment" ],
  10381. THREE.ShaderChunk[ "map_pars_fragment" ],
  10382. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10383. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10384. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10385. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10386. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10387. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10388. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10389. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10390. "void main() {",
  10391. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10392. THREE.ShaderChunk[ "map_fragment" ],
  10393. THREE.ShaderChunk[ "alphatest_fragment" ],
  10394. THREE.ShaderChunk[ "specularmap_fragment" ],
  10395. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10396. THREE.ShaderChunk[ "lightmap_fragment" ],
  10397. THREE.ShaderChunk[ "color_fragment" ],
  10398. THREE.ShaderChunk[ "envmap_fragment" ],
  10399. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10400. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10401. THREE.ShaderChunk[ "fog_fragment" ],
  10402. "}"
  10403. ].join("\n")
  10404. },
  10405. 'particle_basic': {
  10406. uniforms: THREE.UniformsUtils.merge( [
  10407. THREE.UniformsLib[ "particle" ],
  10408. THREE.UniformsLib[ "shadowmap" ]
  10409. ] ),
  10410. vertexShader: [
  10411. "uniform float size;",
  10412. "uniform float scale;",
  10413. THREE.ShaderChunk[ "color_pars_vertex" ],
  10414. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10415. "void main() {",
  10416. THREE.ShaderChunk[ "color_vertex" ],
  10417. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10418. "#ifdef USE_SIZEATTENUATION",
  10419. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10420. "#else",
  10421. "gl_PointSize = size;",
  10422. "#endif",
  10423. "gl_Position = projectionMatrix * mvPosition;",
  10424. THREE.ShaderChunk[ "worldpos_vertex" ],
  10425. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10426. "}"
  10427. ].join("\n"),
  10428. fragmentShader: [
  10429. "uniform vec3 psColor;",
  10430. "uniform float opacity;",
  10431. THREE.ShaderChunk[ "color_pars_fragment" ],
  10432. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10433. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10434. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10435. "void main() {",
  10436. "gl_FragColor = vec4( psColor, opacity );",
  10437. THREE.ShaderChunk[ "map_particle_fragment" ],
  10438. THREE.ShaderChunk[ "alphatest_fragment" ],
  10439. THREE.ShaderChunk[ "color_fragment" ],
  10440. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10441. THREE.ShaderChunk[ "fog_fragment" ],
  10442. "}"
  10443. ].join("\n")
  10444. },
  10445. 'dashed': {
  10446. uniforms: THREE.UniformsUtils.merge( [
  10447. THREE.UniformsLib[ "common" ],
  10448. THREE.UniformsLib[ "fog" ],
  10449. {
  10450. "scale": { type: "f", value: 1 },
  10451. "dashSize": { type: "f", value: 1 },
  10452. "totalSize": { type: "f", value: 2 }
  10453. }
  10454. ] ),
  10455. vertexShader: [
  10456. "uniform float scale;",
  10457. "attribute float lineDistance;",
  10458. "varying float vLineDistance;",
  10459. THREE.ShaderChunk[ "color_pars_vertex" ],
  10460. "void main() {",
  10461. THREE.ShaderChunk[ "color_vertex" ],
  10462. "vLineDistance = scale * lineDistance;",
  10463. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10464. "gl_Position = projectionMatrix * mvPosition;",
  10465. "}"
  10466. ].join("\n"),
  10467. fragmentShader: [
  10468. "uniform vec3 diffuse;",
  10469. "uniform float opacity;",
  10470. "uniform float dashSize;",
  10471. "uniform float totalSize;",
  10472. "varying float vLineDistance;",
  10473. THREE.ShaderChunk[ "color_pars_fragment" ],
  10474. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10475. "void main() {",
  10476. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10477. "discard;",
  10478. "}",
  10479. "gl_FragColor = vec4( diffuse, opacity );",
  10480. THREE.ShaderChunk[ "color_fragment" ],
  10481. THREE.ShaderChunk[ "fog_fragment" ],
  10482. "}"
  10483. ].join("\n")
  10484. },
  10485. 'depth': {
  10486. uniforms: {
  10487. "mNear": { type: "f", value: 1.0 },
  10488. "mFar" : { type: "f", value: 2000.0 },
  10489. "opacity" : { type: "f", value: 1.0 }
  10490. },
  10491. vertexShader: [
  10492. "void main() {",
  10493. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10494. "}"
  10495. ].join("\n"),
  10496. fragmentShader: [
  10497. "uniform float mNear;",
  10498. "uniform float mFar;",
  10499. "uniform float opacity;",
  10500. "void main() {",
  10501. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10502. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10503. "gl_FragColor = vec4( vec3( color ), opacity );",
  10504. "}"
  10505. ].join("\n")
  10506. },
  10507. 'normal': {
  10508. uniforms: {
  10509. "opacity" : { type: "f", value: 1.0 }
  10510. },
  10511. vertexShader: [
  10512. "varying vec3 vNormal;",
  10513. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10514. "void main() {",
  10515. "vNormal = normalize( normalMatrix * normal );",
  10516. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10517. THREE.ShaderChunk[ "default_vertex" ],
  10518. "}"
  10519. ].join("\n"),
  10520. fragmentShader: [
  10521. "uniform float opacity;",
  10522. "varying vec3 vNormal;",
  10523. "void main() {",
  10524. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10525. "}"
  10526. ].join("\n")
  10527. },
  10528. /* -------------------------------------------------------------------------
  10529. // Normal map shader
  10530. // - Blinn-Phong
  10531. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10532. // - point and directional lights (use with "lights: true" material option)
  10533. ------------------------------------------------------------------------- */
  10534. 'normalmap' : {
  10535. uniforms: THREE.UniformsUtils.merge( [
  10536. THREE.UniformsLib[ "fog" ],
  10537. THREE.UniformsLib[ "lights" ],
  10538. THREE.UniformsLib[ "shadowmap" ],
  10539. {
  10540. "enableAO" : { type: "i", value: 0 },
  10541. "enableDiffuse" : { type: "i", value: 0 },
  10542. "enableSpecular" : { type: "i", value: 0 },
  10543. "enableReflection": { type: "i", value: 0 },
  10544. "enableDisplacement": { type: "i", value: 0 },
  10545. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  10546. "tDiffuse" : { type: "t", value: null },
  10547. "tCube" : { type: "t", value: null },
  10548. "tNormal" : { type: "t", value: null },
  10549. "tSpecular" : { type: "t", value: null },
  10550. "tAO" : { type: "t", value: null },
  10551. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10552. "uDisplacementBias": { type: "f", value: 0.0 },
  10553. "uDisplacementScale": { type: "f", value: 1.0 },
  10554. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10555. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10556. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10557. "uShininess": { type: "f", value: 30 },
  10558. "uOpacity": { type: "f", value: 1 },
  10559. "useRefract": { type: "i", value: 0 },
  10560. "uRefractionRatio": { type: "f", value: 0.98 },
  10561. "uReflectivity": { type: "f", value: 0.5 },
  10562. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  10563. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10564. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10565. }
  10566. ] ),
  10567. fragmentShader: [
  10568. "uniform vec3 uAmbientColor;",
  10569. "uniform vec3 uDiffuseColor;",
  10570. "uniform vec3 uSpecularColor;",
  10571. "uniform float uShininess;",
  10572. "uniform float uOpacity;",
  10573. "uniform bool enableDiffuse;",
  10574. "uniform bool enableSpecular;",
  10575. "uniform bool enableAO;",
  10576. "uniform bool enableReflection;",
  10577. "uniform sampler2D tDiffuse;",
  10578. "uniform sampler2D tNormal;",
  10579. "uniform sampler2D tSpecular;",
  10580. "uniform sampler2D tAO;",
  10581. "uniform samplerCube tCube;",
  10582. "uniform vec2 uNormalScale;",
  10583. "uniform bool useRefract;",
  10584. "uniform float uRefractionRatio;",
  10585. "uniform float uReflectivity;",
  10586. "varying vec3 vTangent;",
  10587. "varying vec3 vBinormal;",
  10588. "varying vec3 vNormal;",
  10589. "varying vec2 vUv;",
  10590. "uniform vec3 ambientLightColor;",
  10591. "#if MAX_DIR_LIGHTS > 0",
  10592. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10593. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10594. "#endif",
  10595. "#if MAX_HEMI_LIGHTS > 0",
  10596. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10597. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10598. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10599. "#endif",
  10600. "#if MAX_POINT_LIGHTS > 0",
  10601. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10602. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10603. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10604. "#endif",
  10605. "#if MAX_SPOT_LIGHTS > 0",
  10606. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10607. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10608. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10609. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10610. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10611. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10612. "#endif",
  10613. "#ifdef WRAP_AROUND",
  10614. "uniform vec3 wrapRGB;",
  10615. "#endif",
  10616. "varying vec3 vWorldPosition;",
  10617. "varying vec3 vViewPosition;",
  10618. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10619. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10620. "void main() {",
  10621. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  10622. "vec3 specularTex = vec3( 1.0 );",
  10623. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  10624. "normalTex.xy *= uNormalScale;",
  10625. "normalTex = normalize( normalTex );",
  10626. "if( enableDiffuse ) {",
  10627. "#ifdef GAMMA_INPUT",
  10628. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  10629. "texelColor.xyz *= texelColor.xyz;",
  10630. "gl_FragColor = gl_FragColor * texelColor;",
  10631. "#else",
  10632. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  10633. "#endif",
  10634. "}",
  10635. "if( enableAO ) {",
  10636. "#ifdef GAMMA_INPUT",
  10637. "vec4 aoColor = texture2D( tAO, vUv );",
  10638. "aoColor.xyz *= aoColor.xyz;",
  10639. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  10640. "#else",
  10641. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  10642. "#endif",
  10643. "}",
  10644. "if( enableSpecular )",
  10645. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  10646. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  10647. "vec3 finalNormal = tsb * normalTex;",
  10648. "#ifdef FLIP_SIDED",
  10649. "finalNormal = -finalNormal;",
  10650. "#endif",
  10651. "vec3 normal = normalize( finalNormal );",
  10652. "vec3 viewPosition = normalize( vViewPosition );",
  10653. // point lights
  10654. "#if MAX_POINT_LIGHTS > 0",
  10655. "vec3 pointDiffuse = vec3( 0.0 );",
  10656. "vec3 pointSpecular = vec3( 0.0 );",
  10657. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10658. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10659. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  10660. "float pointDistance = 1.0;",
  10661. "if ( pointLightDistance[ i ] > 0.0 )",
  10662. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  10663. "pointVector = normalize( pointVector );",
  10664. // diffuse
  10665. "#ifdef WRAP_AROUND",
  10666. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  10667. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  10668. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10669. "#else",
  10670. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  10671. "#endif",
  10672. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  10673. // specular
  10674. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  10675. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10676. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  10677. "#ifdef PHYSICALLY_BASED_SHADING",
  10678. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10679. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10680. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  10681. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  10682. "#else",
  10683. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  10684. "#endif",
  10685. "}",
  10686. "#endif",
  10687. // spot lights
  10688. "#if MAX_SPOT_LIGHTS > 0",
  10689. "vec3 spotDiffuse = vec3( 0.0 );",
  10690. "vec3 spotSpecular = vec3( 0.0 );",
  10691. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10692. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10693. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  10694. "float spotDistance = 1.0;",
  10695. "if ( spotLightDistance[ i ] > 0.0 )",
  10696. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  10697. "spotVector = normalize( spotVector );",
  10698. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10699. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10700. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10701. // diffuse
  10702. "#ifdef WRAP_AROUND",
  10703. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  10704. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  10705. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10706. "#else",
  10707. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  10708. "#endif",
  10709. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  10710. // specular
  10711. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  10712. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10713. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  10714. "#ifdef PHYSICALLY_BASED_SHADING",
  10715. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10716. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10717. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  10718. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  10719. "#else",
  10720. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  10721. "#endif",
  10722. "}",
  10723. "}",
  10724. "#endif",
  10725. // directional lights
  10726. "#if MAX_DIR_LIGHTS > 0",
  10727. "vec3 dirDiffuse = vec3( 0.0 );",
  10728. "vec3 dirSpecular = vec3( 0.0 );",
  10729. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  10730. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10731. "vec3 dirVector = normalize( lDirection.xyz );",
  10732. // diffuse
  10733. "#ifdef WRAP_AROUND",
  10734. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  10735. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  10736. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  10737. "#else",
  10738. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  10739. "#endif",
  10740. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  10741. // specular
  10742. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10743. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10744. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  10745. "#ifdef PHYSICALLY_BASED_SHADING",
  10746. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10747. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10748. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10749. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10750. "#else",
  10751. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  10752. "#endif",
  10753. "}",
  10754. "#endif",
  10755. // hemisphere lights
  10756. "#if MAX_HEMI_LIGHTS > 0",
  10757. "vec3 hemiDiffuse = vec3( 0.0 );",
  10758. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10759. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10760. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10761. "vec3 lVector = normalize( lDirection.xyz );",
  10762. // diffuse
  10763. "float dotProduct = dot( normal, lVector );",
  10764. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10765. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10766. "hemiDiffuse += uDiffuseColor * hemiColor;",
  10767. // specular (sky light)
  10768. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10769. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10770. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  10771. // specular (ground light)
  10772. "vec3 lVectorGround = -lVector;",
  10773. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10774. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10775. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  10776. "#ifdef PHYSICALLY_BASED_SHADING",
  10777. "float dotProductGround = dot( normal, lVectorGround );",
  10778. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10779. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10780. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10781. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10782. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10783. "#else",
  10784. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10785. "#endif",
  10786. "}",
  10787. "#endif",
  10788. // all lights contribution summation
  10789. "vec3 totalDiffuse = vec3( 0.0 );",
  10790. "vec3 totalSpecular = vec3( 0.0 );",
  10791. "#if MAX_DIR_LIGHTS > 0",
  10792. "totalDiffuse += dirDiffuse;",
  10793. "totalSpecular += dirSpecular;",
  10794. "#endif",
  10795. "#if MAX_HEMI_LIGHTS > 0",
  10796. "totalDiffuse += hemiDiffuse;",
  10797. "totalSpecular += hemiSpecular;",
  10798. "#endif",
  10799. "#if MAX_POINT_LIGHTS > 0",
  10800. "totalDiffuse += pointDiffuse;",
  10801. "totalSpecular += pointSpecular;",
  10802. "#endif",
  10803. "#if MAX_SPOT_LIGHTS > 0",
  10804. "totalDiffuse += spotDiffuse;",
  10805. "totalSpecular += spotSpecular;",
  10806. "#endif",
  10807. "#ifdef METAL",
  10808. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  10809. "#else",
  10810. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  10811. "#endif",
  10812. "if ( enableReflection ) {",
  10813. "vec3 vReflect;",
  10814. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10815. "if ( useRefract ) {",
  10816. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  10817. "} else {",
  10818. "vReflect = reflect( cameraToVertex, normal );",
  10819. "}",
  10820. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10821. "#ifdef GAMMA_INPUT",
  10822. "cubeColor.xyz *= cubeColor.xyz;",
  10823. "#endif",
  10824. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  10825. "}",
  10826. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10827. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10828. THREE.ShaderChunk[ "fog_fragment" ],
  10829. "}"
  10830. ].join("\n"),
  10831. vertexShader: [
  10832. "attribute vec4 tangent;",
  10833. "uniform vec2 uOffset;",
  10834. "uniform vec2 uRepeat;",
  10835. "uniform bool enableDisplacement;",
  10836. "#ifdef VERTEX_TEXTURES",
  10837. "uniform sampler2D tDisplacement;",
  10838. "uniform float uDisplacementScale;",
  10839. "uniform float uDisplacementBias;",
  10840. "#endif",
  10841. "varying vec3 vTangent;",
  10842. "varying vec3 vBinormal;",
  10843. "varying vec3 vNormal;",
  10844. "varying vec2 vUv;",
  10845. "varying vec3 vWorldPosition;",
  10846. "varying vec3 vViewPosition;",
  10847. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10848. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10849. "void main() {",
  10850. THREE.ShaderChunk[ "skinbase_vertex" ],
  10851. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10852. // normal, tangent and binormal vectors
  10853. "#ifdef USE_SKINNING",
  10854. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  10855. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  10856. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  10857. "#else",
  10858. "vNormal = normalize( normalMatrix * normal );",
  10859. "vTangent = normalize( normalMatrix * tangent.xyz );",
  10860. "#endif",
  10861. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  10862. "vUv = uv * uRepeat + uOffset;",
  10863. // displacement mapping
  10864. "vec3 displacedPosition;",
  10865. "#ifdef VERTEX_TEXTURES",
  10866. "if ( enableDisplacement ) {",
  10867. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  10868. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  10869. "displacedPosition = position + normalize( normal ) * df;",
  10870. "} else {",
  10871. "#ifdef USE_SKINNING",
  10872. "vec4 skinVertex = vec4( position, 1.0 );",
  10873. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10874. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10875. "displacedPosition = skinned.xyz;",
  10876. "#else",
  10877. "displacedPosition = position;",
  10878. "#endif",
  10879. "}",
  10880. "#else",
  10881. "#ifdef USE_SKINNING",
  10882. "vec4 skinVertex = vec4( position, 1.0 );",
  10883. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10884. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10885. "displacedPosition = skinned.xyz;",
  10886. "#else",
  10887. "displacedPosition = position;",
  10888. "#endif",
  10889. "#endif",
  10890. //
  10891. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  10892. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  10893. "gl_Position = projectionMatrix * mvPosition;",
  10894. //
  10895. "vWorldPosition = worldPosition.xyz;",
  10896. "vViewPosition = -mvPosition.xyz;",
  10897. // shadows
  10898. "#ifdef USE_SHADOWMAP",
  10899. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10900. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10901. "}",
  10902. "#endif",
  10903. "}"
  10904. ].join("\n")
  10905. },
  10906. /* -------------------------------------------------------------------------
  10907. // Cube map shader
  10908. ------------------------------------------------------------------------- */
  10909. 'cube': {
  10910. uniforms: { "tCube": { type: "t", value: null },
  10911. "tFlip": { type: "f", value: -1 } },
  10912. vertexShader: [
  10913. "varying vec3 vWorldPosition;",
  10914. "void main() {",
  10915. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10916. "vWorldPosition = worldPosition.xyz;",
  10917. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10918. "}"
  10919. ].join("\n"),
  10920. fragmentShader: [
  10921. "uniform samplerCube tCube;",
  10922. "uniform float tFlip;",
  10923. "varying vec3 vWorldPosition;",
  10924. "void main() {",
  10925. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10926. "}"
  10927. ].join("\n")
  10928. },
  10929. // Depth encoding into RGBA texture
  10930. // based on SpiderGL shadow map example
  10931. // http://spidergl.org/example.php?id=6
  10932. // originally from
  10933. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10934. // see also here:
  10935. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10936. 'depthRGBA': {
  10937. uniforms: {},
  10938. vertexShader: [
  10939. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10940. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10941. "void main() {",
  10942. THREE.ShaderChunk[ "skinbase_vertex" ],
  10943. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10944. THREE.ShaderChunk[ "skinning_vertex" ],
  10945. THREE.ShaderChunk[ "default_vertex" ],
  10946. "}"
  10947. ].join("\n"),
  10948. fragmentShader: [
  10949. "vec4 pack_depth( const in float depth ) {",
  10950. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10951. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10952. "vec4 res = fract( depth * bit_shift );",
  10953. "res -= res.xxyz * bit_mask;",
  10954. "return res;",
  10955. "}",
  10956. "void main() {",
  10957. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10958. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10959. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10960. //"gl_FragData[ 0 ] = pack_depth( z );",
  10961. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10962. "}"
  10963. ].join("\n")
  10964. }
  10965. };
  10966. /**
  10967. * @author supereggbert / http://www.paulbrunt.co.uk/
  10968. * @author mrdoob / http://mrdoob.com/
  10969. * @author alteredq / http://alteredqualia.com/
  10970. * @author szimek / https://github.com/szimek/
  10971. */
  10972. THREE.WebGLRenderer = function ( parameters ) {
  10973. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10974. parameters = parameters || {};
  10975. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10976. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10977. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10978. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10979. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10980. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10981. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10982. _clearColor = new THREE.Color( 0x000000 ),
  10983. _clearAlpha = 0;
  10984. if ( parameters.clearColor !== undefined ) {
  10985. console.warn( 'DEPRECATED: clearColor in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  10986. _clearColor.setHex( parameters.clearColor );
  10987. }
  10988. if ( parameters.clearAlpha !== undefined ) {
  10989. console.warn( 'DEPRECATED: clearAlpha in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  10990. _clearAlpha = parameters.clearAlpha;
  10991. }
  10992. // public properties
  10993. this.domElement = _canvas;
  10994. this.context = null;
  10995. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10996. ? parameters.devicePixelRatio
  10997. : window.devicePixelRatio !== undefined
  10998. ? window.devicePixelRatio
  10999. : 1;
  11000. // clearing
  11001. this.autoClear = true;
  11002. this.autoClearColor = true;
  11003. this.autoClearDepth = true;
  11004. this.autoClearStencil = true;
  11005. // scene graph
  11006. this.sortObjects = true;
  11007. this.autoUpdateObjects = true;
  11008. // physically based shading
  11009. this.gammaInput = false;
  11010. this.gammaOutput = false;
  11011. this.physicallyBasedShading = false;
  11012. // shadow map
  11013. this.shadowMapEnabled = false;
  11014. this.shadowMapAutoUpdate = true;
  11015. this.shadowMapType = THREE.PCFShadowMap;
  11016. this.shadowMapCullFace = THREE.CullFaceFront;
  11017. this.shadowMapDebug = false;
  11018. this.shadowMapCascade = false;
  11019. // morphs
  11020. this.maxMorphTargets = 8;
  11021. this.maxMorphNormals = 4;
  11022. // flags
  11023. this.autoScaleCubemaps = true;
  11024. // custom render plugins
  11025. this.renderPluginsPre = [];
  11026. this.renderPluginsPost = [];
  11027. // info
  11028. this.info = {
  11029. memory: {
  11030. programs: 0,
  11031. geometries: 0,
  11032. textures: 0
  11033. },
  11034. render: {
  11035. calls: 0,
  11036. vertices: 0,
  11037. faces: 0,
  11038. points: 0
  11039. }
  11040. };
  11041. // internal properties
  11042. var _this = this,
  11043. _programs = [],
  11044. _programs_counter = 0,
  11045. // internal state cache
  11046. _currentProgram = null,
  11047. _currentFramebuffer = null,
  11048. _currentMaterialId = -1,
  11049. _currentGeometryGroupHash = null,
  11050. _currentCamera = null,
  11051. _geometryGroupCounter = 0,
  11052. _usedTextureUnits = 0,
  11053. // GL state cache
  11054. _oldDoubleSided = -1,
  11055. _oldFlipSided = -1,
  11056. _oldBlending = -1,
  11057. _oldBlendEquation = -1,
  11058. _oldBlendSrc = -1,
  11059. _oldBlendDst = -1,
  11060. _oldDepthTest = -1,
  11061. _oldDepthWrite = -1,
  11062. _oldPolygonOffset = null,
  11063. _oldPolygonOffsetFactor = null,
  11064. _oldPolygonOffsetUnits = null,
  11065. _oldLineWidth = null,
  11066. _viewportX = 0,
  11067. _viewportY = 0,
  11068. _viewportWidth = 0,
  11069. _viewportHeight = 0,
  11070. _currentWidth = 0,
  11071. _currentHeight = 0,
  11072. _enabledAttributes = {},
  11073. // frustum
  11074. _frustum = new THREE.Frustum(),
  11075. // camera matrices cache
  11076. _projScreenMatrix = new THREE.Matrix4(),
  11077. _projScreenMatrixPS = new THREE.Matrix4(),
  11078. _vector3 = new THREE.Vector3(),
  11079. // light arrays cache
  11080. _direction = new THREE.Vector3(),
  11081. _lightsNeedUpdate = true,
  11082. _lights = {
  11083. ambient: [ 0, 0, 0 ],
  11084. directional: { length: 0, colors: new Array(), positions: new Array() },
  11085. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11086. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11087. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11088. };
  11089. // initialize
  11090. var _gl;
  11091. var _glExtensionTextureFloat;
  11092. var _glExtensionStandardDerivatives;
  11093. var _glExtensionTextureFilterAnisotropic;
  11094. var _glExtensionCompressedTextureS3TC;
  11095. initGL();
  11096. setDefaultGLState();
  11097. this.context = _gl;
  11098. // GPU capabilities
  11099. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11100. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11101. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11102. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11103. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11104. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11105. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11106. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11107. //
  11108. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11109. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11110. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11111. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11112. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11113. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11114. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11115. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11116. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11117. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11118. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11119. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11120. // clamp precision to maximum available
  11121. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11122. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11123. if ( _precision === "highp" && ! highpAvailable ) {
  11124. if ( mediumpAvailable ) {
  11125. _precision = "mediump";
  11126. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11127. } else {
  11128. _precision = "lowp";
  11129. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11130. }
  11131. }
  11132. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11133. _precision = "lowp";
  11134. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11135. }
  11136. // API
  11137. this.getContext = function () {
  11138. return _gl;
  11139. };
  11140. this.supportsVertexTextures = function () {
  11141. return _supportsVertexTextures;
  11142. };
  11143. this.supportsFloatTextures = function () {
  11144. return _glExtensionTextureFloat;
  11145. };
  11146. this.supportsStandardDerivatives = function () {
  11147. return _glExtensionStandardDerivatives;
  11148. };
  11149. this.supportsCompressedTextureS3TC = function () {
  11150. return _glExtensionCompressedTextureS3TC;
  11151. };
  11152. this.getMaxAnisotropy = function () {
  11153. return _maxAnisotropy;
  11154. };
  11155. this.getPrecision = function () {
  11156. return _precision;
  11157. };
  11158. this.setSize = function ( width, height, updateStyle ) {
  11159. _canvas.width = width * this.devicePixelRatio;
  11160. _canvas.height = height * this.devicePixelRatio;
  11161. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11162. _canvas.style.width = width + 'px';
  11163. _canvas.style.height = height + 'px';
  11164. }
  11165. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11166. };
  11167. this.setViewport = function ( x, y, width, height ) {
  11168. _viewportX = x !== undefined ? x : 0;
  11169. _viewportY = y !== undefined ? y : 0;
  11170. _viewportWidth = width !== undefined ? width : _canvas.width;
  11171. _viewportHeight = height !== undefined ? height : _canvas.height;
  11172. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11173. };
  11174. this.setScissor = function ( x, y, width, height ) {
  11175. _gl.scissor( x, y, width, height );
  11176. };
  11177. this.enableScissorTest = function ( enable ) {
  11178. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11179. };
  11180. // Clearing
  11181. this.setClearColor = function ( color, alpha ) {
  11182. _clearColor.set( color );
  11183. _clearAlpha = alpha !== undefined ? alpha : 1;
  11184. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11185. };
  11186. this.setClearColorHex = function ( hex, alpha ) {
  11187. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11188. this.setClearColor( hex, alpha );
  11189. };
  11190. this.getClearColor = function () {
  11191. return _clearColor;
  11192. };
  11193. this.getClearAlpha = function () {
  11194. return _clearAlpha;
  11195. };
  11196. this.clear = function ( color, depth, stencil ) {
  11197. var bits = 0;
  11198. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11199. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11200. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11201. _gl.clear( bits );
  11202. };
  11203. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11204. this.setRenderTarget( renderTarget );
  11205. this.clear( color, depth, stencil );
  11206. };
  11207. // Plugins
  11208. this.addPostPlugin = function ( plugin ) {
  11209. plugin.init( this );
  11210. this.renderPluginsPost.push( plugin );
  11211. };
  11212. this.addPrePlugin = function ( plugin ) {
  11213. plugin.init( this );
  11214. this.renderPluginsPre.push( plugin );
  11215. };
  11216. // Rendering
  11217. this.updateShadowMap = function ( scene, camera ) {
  11218. _currentProgram = null;
  11219. _oldBlending = -1;
  11220. _oldDepthTest = -1;
  11221. _oldDepthWrite = -1;
  11222. _currentGeometryGroupHash = -1;
  11223. _currentMaterialId = -1;
  11224. _lightsNeedUpdate = true;
  11225. _oldDoubleSided = -1;
  11226. _oldFlipSided = -1;
  11227. this.shadowMapPlugin.update( scene, camera );
  11228. };
  11229. // Internal functions
  11230. // Buffer allocation
  11231. function createParticleBuffers ( geometry ) {
  11232. geometry.__webglVertexBuffer = _gl.createBuffer();
  11233. geometry.__webglColorBuffer = _gl.createBuffer();
  11234. _this.info.memory.geometries ++;
  11235. };
  11236. function createLineBuffers ( geometry ) {
  11237. geometry.__webglVertexBuffer = _gl.createBuffer();
  11238. geometry.__webglColorBuffer = _gl.createBuffer();
  11239. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11240. _this.info.memory.geometries ++;
  11241. };
  11242. function createRibbonBuffers ( geometry ) {
  11243. geometry.__webglVertexBuffer = _gl.createBuffer();
  11244. geometry.__webglColorBuffer = _gl.createBuffer();
  11245. geometry.__webglNormalBuffer = _gl.createBuffer();
  11246. _this.info.memory.geometries ++;
  11247. };
  11248. function createMeshBuffers ( geometryGroup ) {
  11249. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11250. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11251. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11252. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11253. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11254. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11255. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11256. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11257. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11258. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11259. var m, ml;
  11260. if ( geometryGroup.numMorphTargets ) {
  11261. geometryGroup.__webglMorphTargetsBuffers = [];
  11262. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11263. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11264. }
  11265. }
  11266. if ( geometryGroup.numMorphNormals ) {
  11267. geometryGroup.__webglMorphNormalsBuffers = [];
  11268. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11269. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11270. }
  11271. }
  11272. _this.info.memory.geometries ++;
  11273. };
  11274. // Events
  11275. var onGeometryDispose = function ( event ) {
  11276. var geometry = event.target;
  11277. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11278. deallocateGeometry( geometry );
  11279. _this.info.memory.geometries --;
  11280. };
  11281. var onTextureDispose = function ( event ) {
  11282. var texture = event.target;
  11283. texture.removeEventListener( 'dispose', onTextureDispose );
  11284. deallocateTexture( texture );
  11285. _this.info.memory.textures --;
  11286. };
  11287. var onRenderTargetDispose = function ( event ) {
  11288. var renderTarget = event.target;
  11289. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11290. deallocateRenderTarget( renderTarget );
  11291. _this.info.memory.textures --;
  11292. };
  11293. var onMaterialDispose = function ( event ) {
  11294. var material = event.target;
  11295. material.removeEventListener( 'dispose', onMaterialDispose );
  11296. deallocateMaterial( material );
  11297. };
  11298. // Buffer deallocation
  11299. var deallocateGeometry = function ( geometry ) {
  11300. geometry.__webglInit = undefined;
  11301. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11302. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11303. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11304. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11305. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11306. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11307. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11308. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11309. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11310. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11311. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11312. // geometry groups
  11313. if ( geometry.geometryGroups !== undefined ) {
  11314. for ( var g in geometry.geometryGroups ) {
  11315. var geometryGroup = geometry.geometryGroups[ g ];
  11316. if ( geometryGroup.numMorphTargets !== undefined ) {
  11317. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11318. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11319. }
  11320. }
  11321. if ( geometryGroup.numMorphNormals !== undefined ) {
  11322. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11323. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11324. }
  11325. }
  11326. deleteCustomAttributesBuffers( geometryGroup );
  11327. }
  11328. }
  11329. deleteCustomAttributesBuffers( geometry );
  11330. };
  11331. var deallocateTexture = function ( texture ) {
  11332. if ( texture.image && texture.image.__webglTextureCube ) {
  11333. // cube texture
  11334. _gl.deleteTexture( texture.image.__webglTextureCube );
  11335. } else {
  11336. // 2D texture
  11337. if ( ! texture.__webglInit ) return;
  11338. texture.__webglInit = false;
  11339. _gl.deleteTexture( texture.__webglTexture );
  11340. }
  11341. };
  11342. var deallocateRenderTarget = function ( renderTarget ) {
  11343. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11344. _gl.deleteTexture( renderTarget.__webglTexture );
  11345. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11346. for ( var i = 0; i < 6; i ++ ) {
  11347. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11348. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11349. }
  11350. } else {
  11351. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11352. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11353. }
  11354. };
  11355. var deallocateMaterial = function ( material ) {
  11356. var program = material.program;
  11357. if ( program === undefined ) return;
  11358. material.program = undefined;
  11359. // only deallocate GL program if this was the last use of shared program
  11360. // assumed there is only single copy of any program in the _programs list
  11361. // (that's how it's constructed)
  11362. var i, il, programInfo;
  11363. var deleteProgram = false;
  11364. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11365. programInfo = _programs[ i ];
  11366. if ( programInfo.program === program ) {
  11367. programInfo.usedTimes --;
  11368. if ( programInfo.usedTimes === 0 ) {
  11369. deleteProgram = true;
  11370. }
  11371. break;
  11372. }
  11373. }
  11374. if ( deleteProgram === true ) {
  11375. // avoid using array.splice, this is costlier than creating new array from scratch
  11376. var newPrograms = [];
  11377. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11378. programInfo = _programs[ i ];
  11379. if ( programInfo.program !== program ) {
  11380. newPrograms.push( programInfo );
  11381. }
  11382. }
  11383. _programs = newPrograms;
  11384. _gl.deleteProgram( program );
  11385. _this.info.memory.programs --;
  11386. }
  11387. };
  11388. //
  11389. /*
  11390. function deleteParticleBuffers ( geometry ) {
  11391. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11392. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11393. deleteCustomAttributesBuffers( geometry );
  11394. _this.info.memory.geometries --;
  11395. };
  11396. function deleteLineBuffers ( geometry ) {
  11397. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11398. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11399. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11400. deleteCustomAttributesBuffers( geometry );
  11401. _this.info.memory.geometries --;
  11402. };
  11403. function deleteRibbonBuffers ( geometry ) {
  11404. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11405. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11406. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11407. deleteCustomAttributesBuffers( geometry );
  11408. _this.info.memory.geometries --;
  11409. };
  11410. function deleteMeshBuffers ( geometryGroup ) {
  11411. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  11412. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  11413. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  11414. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  11415. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  11416. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  11417. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  11418. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  11419. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  11420. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  11421. var m, ml;
  11422. if ( geometryGroup.numMorphTargets ) {
  11423. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11424. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11425. }
  11426. }
  11427. if ( geometryGroup.numMorphNormals ) {
  11428. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11429. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11430. }
  11431. }
  11432. deleteCustomAttributesBuffers( geometryGroup );
  11433. _this.info.memory.geometries --;
  11434. };
  11435. */
  11436. function deleteCustomAttributesBuffers( geometry ) {
  11437. if ( geometry.__webglCustomAttributesList ) {
  11438. for ( var id in geometry.__webglCustomAttributesList ) {
  11439. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11440. }
  11441. }
  11442. };
  11443. // Buffer initialization
  11444. function initCustomAttributes ( geometry, object ) {
  11445. var nvertices = geometry.vertices.length;
  11446. var material = object.material;
  11447. if ( material.attributes ) {
  11448. if ( geometry.__webglCustomAttributesList === undefined ) {
  11449. geometry.__webglCustomAttributesList = [];
  11450. }
  11451. for ( var a in material.attributes ) {
  11452. var attribute = material.attributes[ a ];
  11453. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11454. attribute.__webglInitialized = true;
  11455. var size = 1; // "f" and "i"
  11456. if ( attribute.type === "v2" ) size = 2;
  11457. else if ( attribute.type === "v3" ) size = 3;
  11458. else if ( attribute.type === "v4" ) size = 4;
  11459. else if ( attribute.type === "c" ) size = 3;
  11460. attribute.size = size;
  11461. attribute.array = new Float32Array( nvertices * size );
  11462. attribute.buffer = _gl.createBuffer();
  11463. attribute.buffer.belongsToAttribute = a;
  11464. attribute.needsUpdate = true;
  11465. }
  11466. geometry.__webglCustomAttributesList.push( attribute );
  11467. }
  11468. }
  11469. };
  11470. function initParticleBuffers ( geometry, object ) {
  11471. var nvertices = geometry.vertices.length;
  11472. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11473. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11474. geometry.__sortArray = [];
  11475. geometry.__webglParticleCount = nvertices;
  11476. initCustomAttributes ( geometry, object );
  11477. };
  11478. function initLineBuffers ( geometry, object ) {
  11479. var nvertices = geometry.vertices.length;
  11480. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11481. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11482. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11483. geometry.__webglLineCount = nvertices;
  11484. initCustomAttributes ( geometry, object );
  11485. };
  11486. function initRibbonBuffers ( geometry, object ) {
  11487. var nvertices = geometry.vertices.length;
  11488. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11489. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11490. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11491. geometry.__webglVertexCount = nvertices;
  11492. initCustomAttributes ( geometry, object );
  11493. };
  11494. function initMeshBuffers ( geometryGroup, object ) {
  11495. var geometry = object.geometry,
  11496. faces3 = geometryGroup.faces3,
  11497. faces4 = geometryGroup.faces4,
  11498. nvertices = faces3.length * 3 + faces4.length * 4,
  11499. ntris = faces3.length * 1 + faces4.length * 2,
  11500. nlines = faces3.length * 3 + faces4.length * 4,
  11501. material = getBufferMaterial( object, geometryGroup ),
  11502. uvType = bufferGuessUVType( material ),
  11503. normalType = bufferGuessNormalType( material ),
  11504. vertexColorType = bufferGuessVertexColorType( material );
  11505. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11506. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11507. if ( normalType ) {
  11508. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11509. }
  11510. if ( geometry.hasTangents ) {
  11511. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11512. }
  11513. if ( vertexColorType ) {
  11514. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11515. }
  11516. if ( uvType ) {
  11517. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11518. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11519. }
  11520. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11521. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11522. }
  11523. }
  11524. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11525. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11526. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11527. }
  11528. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11529. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11530. var m, ml;
  11531. if ( geometryGroup.numMorphTargets ) {
  11532. geometryGroup.__morphTargetsArrays = [];
  11533. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11534. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11535. }
  11536. }
  11537. if ( geometryGroup.numMorphNormals ) {
  11538. geometryGroup.__morphNormalsArrays = [];
  11539. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11540. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11541. }
  11542. }
  11543. geometryGroup.__webglFaceCount = ntris * 3;
  11544. geometryGroup.__webglLineCount = nlines * 2;
  11545. // custom attributes
  11546. if ( material.attributes ) {
  11547. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11548. geometryGroup.__webglCustomAttributesList = [];
  11549. }
  11550. for ( var a in material.attributes ) {
  11551. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11552. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11553. var originalAttribute = material.attributes[ a ];
  11554. var attribute = {};
  11555. for ( var property in originalAttribute ) {
  11556. attribute[ property ] = originalAttribute[ property ];
  11557. }
  11558. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11559. attribute.__webglInitialized = true;
  11560. var size = 1; // "f" and "i"
  11561. if( attribute.type === "v2" ) size = 2;
  11562. else if( attribute.type === "v3" ) size = 3;
  11563. else if( attribute.type === "v4" ) size = 4;
  11564. else if( attribute.type === "c" ) size = 3;
  11565. attribute.size = size;
  11566. attribute.array = new Float32Array( nvertices * size );
  11567. attribute.buffer = _gl.createBuffer();
  11568. attribute.buffer.belongsToAttribute = a;
  11569. originalAttribute.needsUpdate = true;
  11570. attribute.__original = originalAttribute;
  11571. }
  11572. geometryGroup.__webglCustomAttributesList.push( attribute );
  11573. }
  11574. }
  11575. geometryGroup.__inittedArrays = true;
  11576. };
  11577. function getBufferMaterial( object, geometryGroup ) {
  11578. return object.material instanceof THREE.MeshFaceMaterial
  11579. ? object.material.materials[ geometryGroup.materialIndex ]
  11580. : object.material;
  11581. };
  11582. function materialNeedsSmoothNormals ( material ) {
  11583. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11584. };
  11585. function bufferGuessNormalType ( material ) {
  11586. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  11587. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  11588. return false;
  11589. }
  11590. if ( materialNeedsSmoothNormals( material ) ) {
  11591. return THREE.SmoothShading;
  11592. } else {
  11593. return THREE.FlatShading;
  11594. }
  11595. };
  11596. function bufferGuessVertexColorType( material ) {
  11597. if ( material.vertexColors ) {
  11598. return material.vertexColors;
  11599. }
  11600. return false;
  11601. };
  11602. function bufferGuessUVType( material ) {
  11603. // material must use some texture to require uvs
  11604. if ( material.map ||
  11605. material.lightMap ||
  11606. material.bumpMap ||
  11607. material.normalMap ||
  11608. material.specularMap ||
  11609. material instanceof THREE.ShaderMaterial ) {
  11610. return true;
  11611. }
  11612. return false;
  11613. };
  11614. //
  11615. function initDirectBuffers( geometry ) {
  11616. var a, attribute, type;
  11617. for ( a in geometry.attributes ) {
  11618. if ( a === "index" ) {
  11619. type = _gl.ELEMENT_ARRAY_BUFFER;
  11620. } else {
  11621. type = _gl.ARRAY_BUFFER;
  11622. }
  11623. attribute = geometry.attributes[ a ];
  11624. attribute.buffer = _gl.createBuffer();
  11625. _gl.bindBuffer( type, attribute.buffer );
  11626. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  11627. }
  11628. };
  11629. // Buffer setting
  11630. function setParticleBuffers ( geometry, hint, object ) {
  11631. var v, c, vertex, offset, index, color,
  11632. vertices = geometry.vertices,
  11633. vl = vertices.length,
  11634. colors = geometry.colors,
  11635. cl = colors.length,
  11636. vertexArray = geometry.__vertexArray,
  11637. colorArray = geometry.__colorArray,
  11638. sortArray = geometry.__sortArray,
  11639. dirtyVertices = geometry.verticesNeedUpdate,
  11640. dirtyElements = geometry.elementsNeedUpdate,
  11641. dirtyColors = geometry.colorsNeedUpdate,
  11642. customAttributes = geometry.__webglCustomAttributesList,
  11643. i, il,
  11644. a, ca, cal, value,
  11645. customAttribute;
  11646. if ( object.sortParticles ) {
  11647. _projScreenMatrixPS.copy( _projScreenMatrix );
  11648. _projScreenMatrixPS.multiply( object.matrixWorld );
  11649. for ( v = 0; v < vl; v ++ ) {
  11650. vertex = vertices[ v ];
  11651. _vector3.copy( vertex );
  11652. _vector3.applyProjection( _projScreenMatrixPS );
  11653. sortArray[ v ] = [ _vector3.z, v ];
  11654. }
  11655. sortArray.sort( numericalSort );
  11656. for ( v = 0; v < vl; v ++ ) {
  11657. vertex = vertices[ sortArray[v][1] ];
  11658. offset = v * 3;
  11659. vertexArray[ offset ] = vertex.x;
  11660. vertexArray[ offset + 1 ] = vertex.y;
  11661. vertexArray[ offset + 2 ] = vertex.z;
  11662. }
  11663. for ( c = 0; c < cl; c ++ ) {
  11664. offset = c * 3;
  11665. color = colors[ sortArray[c][1] ];
  11666. colorArray[ offset ] = color.r;
  11667. colorArray[ offset + 1 ] = color.g;
  11668. colorArray[ offset + 2 ] = color.b;
  11669. }
  11670. if ( customAttributes ) {
  11671. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11672. customAttribute = customAttributes[ i ];
  11673. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  11674. offset = 0;
  11675. cal = customAttribute.value.length;
  11676. if ( customAttribute.size === 1 ) {
  11677. for ( ca = 0; ca < cal; ca ++ ) {
  11678. index = sortArray[ ca ][ 1 ];
  11679. customAttribute.array[ ca ] = customAttribute.value[ index ];
  11680. }
  11681. } else if ( customAttribute.size === 2 ) {
  11682. for ( ca = 0; ca < cal; ca ++ ) {
  11683. index = sortArray[ ca ][ 1 ];
  11684. value = customAttribute.value[ index ];
  11685. customAttribute.array[ offset ] = value.x;
  11686. customAttribute.array[ offset + 1 ] = value.y;
  11687. offset += 2;
  11688. }
  11689. } else if ( customAttribute.size === 3 ) {
  11690. if ( customAttribute.type === "c" ) {
  11691. for ( ca = 0; ca < cal; ca ++ ) {
  11692. index = sortArray[ ca ][ 1 ];
  11693. value = customAttribute.value[ index ];
  11694. customAttribute.array[ offset ] = value.r;
  11695. customAttribute.array[ offset + 1 ] = value.g;
  11696. customAttribute.array[ offset + 2 ] = value.b;
  11697. offset += 3;
  11698. }
  11699. } else {
  11700. for ( ca = 0; ca < cal; ca ++ ) {
  11701. index = sortArray[ ca ][ 1 ];
  11702. value = customAttribute.value[ index ];
  11703. customAttribute.array[ offset ] = value.x;
  11704. customAttribute.array[ offset + 1 ] = value.y;
  11705. customAttribute.array[ offset + 2 ] = value.z;
  11706. offset += 3;
  11707. }
  11708. }
  11709. } else if ( customAttribute.size === 4 ) {
  11710. for ( ca = 0; ca < cal; ca ++ ) {
  11711. index = sortArray[ ca ][ 1 ];
  11712. value = customAttribute.value[ index ];
  11713. customAttribute.array[ offset ] = value.x;
  11714. customAttribute.array[ offset + 1 ] = value.y;
  11715. customAttribute.array[ offset + 2 ] = value.z;
  11716. customAttribute.array[ offset + 3 ] = value.w;
  11717. offset += 4;
  11718. }
  11719. }
  11720. }
  11721. }
  11722. } else {
  11723. if ( dirtyVertices ) {
  11724. for ( v = 0; v < vl; v ++ ) {
  11725. vertex = vertices[ v ];
  11726. offset = v * 3;
  11727. vertexArray[ offset ] = vertex.x;
  11728. vertexArray[ offset + 1 ] = vertex.y;
  11729. vertexArray[ offset + 2 ] = vertex.z;
  11730. }
  11731. }
  11732. if ( dirtyColors ) {
  11733. for ( c = 0; c < cl; c ++ ) {
  11734. color = colors[ c ];
  11735. offset = c * 3;
  11736. colorArray[ offset ] = color.r;
  11737. colorArray[ offset + 1 ] = color.g;
  11738. colorArray[ offset + 2 ] = color.b;
  11739. }
  11740. }
  11741. if ( customAttributes ) {
  11742. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11743. customAttribute = customAttributes[ i ];
  11744. if ( customAttribute.needsUpdate &&
  11745. ( customAttribute.boundTo === undefined ||
  11746. customAttribute.boundTo === "vertices") ) {
  11747. cal = customAttribute.value.length;
  11748. offset = 0;
  11749. if ( customAttribute.size === 1 ) {
  11750. for ( ca = 0; ca < cal; ca ++ ) {
  11751. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11752. }
  11753. } else if ( customAttribute.size === 2 ) {
  11754. for ( ca = 0; ca < cal; ca ++ ) {
  11755. value = customAttribute.value[ ca ];
  11756. customAttribute.array[ offset ] = value.x;
  11757. customAttribute.array[ offset + 1 ] = value.y;
  11758. offset += 2;
  11759. }
  11760. } else if ( customAttribute.size === 3 ) {
  11761. if ( customAttribute.type === "c" ) {
  11762. for ( ca = 0; ca < cal; ca ++ ) {
  11763. value = customAttribute.value[ ca ];
  11764. customAttribute.array[ offset ] = value.r;
  11765. customAttribute.array[ offset + 1 ] = value.g;
  11766. customAttribute.array[ offset + 2 ] = value.b;
  11767. offset += 3;
  11768. }
  11769. } else {
  11770. for ( ca = 0; ca < cal; ca ++ ) {
  11771. value = customAttribute.value[ ca ];
  11772. customAttribute.array[ offset ] = value.x;
  11773. customAttribute.array[ offset + 1 ] = value.y;
  11774. customAttribute.array[ offset + 2 ] = value.z;
  11775. offset += 3;
  11776. }
  11777. }
  11778. } else if ( customAttribute.size === 4 ) {
  11779. for ( ca = 0; ca < cal; ca ++ ) {
  11780. value = customAttribute.value[ ca ];
  11781. customAttribute.array[ offset ] = value.x;
  11782. customAttribute.array[ offset + 1 ] = value.y;
  11783. customAttribute.array[ offset + 2 ] = value.z;
  11784. customAttribute.array[ offset + 3 ] = value.w;
  11785. offset += 4;
  11786. }
  11787. }
  11788. }
  11789. }
  11790. }
  11791. }
  11792. if ( dirtyVertices || object.sortParticles ) {
  11793. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11794. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11795. }
  11796. if ( dirtyColors || object.sortParticles ) {
  11797. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11798. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11799. }
  11800. if ( customAttributes ) {
  11801. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11802. customAttribute = customAttributes[ i ];
  11803. if ( customAttribute.needsUpdate || object.sortParticles ) {
  11804. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11805. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11806. }
  11807. }
  11808. }
  11809. };
  11810. function setLineBuffers ( geometry, hint ) {
  11811. var v, c, d, vertex, offset, color,
  11812. vertices = geometry.vertices,
  11813. colors = geometry.colors,
  11814. lineDistances = geometry.lineDistances,
  11815. vl = vertices.length,
  11816. cl = colors.length,
  11817. dl = lineDistances.length,
  11818. vertexArray = geometry.__vertexArray,
  11819. colorArray = geometry.__colorArray,
  11820. lineDistanceArray = geometry.__lineDistanceArray,
  11821. dirtyVertices = geometry.verticesNeedUpdate,
  11822. dirtyColors = geometry.colorsNeedUpdate,
  11823. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11824. customAttributes = geometry.__webglCustomAttributesList,
  11825. i, il,
  11826. a, ca, cal, value,
  11827. customAttribute;
  11828. if ( dirtyVertices ) {
  11829. for ( v = 0; v < vl; v ++ ) {
  11830. vertex = vertices[ v ];
  11831. offset = v * 3;
  11832. vertexArray[ offset ] = vertex.x;
  11833. vertexArray[ offset + 1 ] = vertex.y;
  11834. vertexArray[ offset + 2 ] = vertex.z;
  11835. }
  11836. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11837. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11838. }
  11839. if ( dirtyColors ) {
  11840. for ( c = 0; c < cl; c ++ ) {
  11841. color = colors[ c ];
  11842. offset = c * 3;
  11843. colorArray[ offset ] = color.r;
  11844. colorArray[ offset + 1 ] = color.g;
  11845. colorArray[ offset + 2 ] = color.b;
  11846. }
  11847. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11848. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11849. }
  11850. if ( dirtyLineDistances ) {
  11851. for ( d = 0; d < dl; d ++ ) {
  11852. lineDistanceArray[ d ] = lineDistances[ d ];
  11853. }
  11854. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11855. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11856. }
  11857. if ( customAttributes ) {
  11858. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11859. customAttribute = customAttributes[ i ];
  11860. if ( customAttribute.needsUpdate &&
  11861. ( customAttribute.boundTo === undefined ||
  11862. customAttribute.boundTo === "vertices" ) ) {
  11863. offset = 0;
  11864. cal = customAttribute.value.length;
  11865. if ( customAttribute.size === 1 ) {
  11866. for ( ca = 0; ca < cal; ca ++ ) {
  11867. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11868. }
  11869. } else if ( customAttribute.size === 2 ) {
  11870. for ( ca = 0; ca < cal; ca ++ ) {
  11871. value = customAttribute.value[ ca ];
  11872. customAttribute.array[ offset ] = value.x;
  11873. customAttribute.array[ offset + 1 ] = value.y;
  11874. offset += 2;
  11875. }
  11876. } else if ( customAttribute.size === 3 ) {
  11877. if ( customAttribute.type === "c" ) {
  11878. for ( ca = 0; ca < cal; ca ++ ) {
  11879. value = customAttribute.value[ ca ];
  11880. customAttribute.array[ offset ] = value.r;
  11881. customAttribute.array[ offset + 1 ] = value.g;
  11882. customAttribute.array[ offset + 2 ] = value.b;
  11883. offset += 3;
  11884. }
  11885. } else {
  11886. for ( ca = 0; ca < cal; ca ++ ) {
  11887. value = customAttribute.value[ ca ];
  11888. customAttribute.array[ offset ] = value.x;
  11889. customAttribute.array[ offset + 1 ] = value.y;
  11890. customAttribute.array[ offset + 2 ] = value.z;
  11891. offset += 3;
  11892. }
  11893. }
  11894. } else if ( customAttribute.size === 4 ) {
  11895. for ( ca = 0; ca < cal; ca ++ ) {
  11896. value = customAttribute.value[ ca ];
  11897. customAttribute.array[ offset ] = value.x;
  11898. customAttribute.array[ offset + 1 ] = value.y;
  11899. customAttribute.array[ offset + 2 ] = value.z;
  11900. customAttribute.array[ offset + 3 ] = value.w;
  11901. offset += 4;
  11902. }
  11903. }
  11904. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11905. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11906. }
  11907. }
  11908. }
  11909. };
  11910. function setRibbonBuffers ( geometry, hint ) {
  11911. var v, c, n, vertex, offset, color, normal,
  11912. i, il, ca, cal, customAttribute, value,
  11913. vertices = geometry.vertices,
  11914. colors = geometry.colors,
  11915. normals = geometry.normals,
  11916. vl = vertices.length,
  11917. cl = colors.length,
  11918. nl = normals.length,
  11919. vertexArray = geometry.__vertexArray,
  11920. colorArray = geometry.__colorArray,
  11921. normalArray = geometry.__normalArray,
  11922. dirtyVertices = geometry.verticesNeedUpdate,
  11923. dirtyColors = geometry.colorsNeedUpdate,
  11924. dirtyNormals = geometry.normalsNeedUpdate,
  11925. customAttributes = geometry.__webglCustomAttributesList;
  11926. if ( dirtyVertices ) {
  11927. for ( v = 0; v < vl; v ++ ) {
  11928. vertex = vertices[ v ];
  11929. offset = v * 3;
  11930. vertexArray[ offset ] = vertex.x;
  11931. vertexArray[ offset + 1 ] = vertex.y;
  11932. vertexArray[ offset + 2 ] = vertex.z;
  11933. }
  11934. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11935. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11936. }
  11937. if ( dirtyColors ) {
  11938. for ( c = 0; c < cl; c ++ ) {
  11939. color = colors[ c ];
  11940. offset = c * 3;
  11941. colorArray[ offset ] = color.r;
  11942. colorArray[ offset + 1 ] = color.g;
  11943. colorArray[ offset + 2 ] = color.b;
  11944. }
  11945. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11946. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11947. }
  11948. if ( dirtyNormals ) {
  11949. for ( n = 0; n < nl; n ++ ) {
  11950. normal = normals[ n ];
  11951. offset = n * 3;
  11952. normalArray[ offset ] = normal.x;
  11953. normalArray[ offset + 1 ] = normal.y;
  11954. normalArray[ offset + 2 ] = normal.z;
  11955. }
  11956. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11957. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11958. }
  11959. if ( customAttributes ) {
  11960. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11961. customAttribute = customAttributes[ i ];
  11962. if ( customAttribute.needsUpdate &&
  11963. ( customAttribute.boundTo === undefined ||
  11964. customAttribute.boundTo === "vertices" ) ) {
  11965. offset = 0;
  11966. cal = customAttribute.value.length;
  11967. if ( customAttribute.size === 1 ) {
  11968. for ( ca = 0; ca < cal; ca ++ ) {
  11969. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11970. }
  11971. } else if ( customAttribute.size === 2 ) {
  11972. for ( ca = 0; ca < cal; ca ++ ) {
  11973. value = customAttribute.value[ ca ];
  11974. customAttribute.array[ offset ] = value.x;
  11975. customAttribute.array[ offset + 1 ] = value.y;
  11976. offset += 2;
  11977. }
  11978. } else if ( customAttribute.size === 3 ) {
  11979. if ( customAttribute.type === "c" ) {
  11980. for ( ca = 0; ca < cal; ca ++ ) {
  11981. value = customAttribute.value[ ca ];
  11982. customAttribute.array[ offset ] = value.r;
  11983. customAttribute.array[ offset + 1 ] = value.g;
  11984. customAttribute.array[ offset + 2 ] = value.b;
  11985. offset += 3;
  11986. }
  11987. } else {
  11988. for ( ca = 0; ca < cal; ca ++ ) {
  11989. value = customAttribute.value[ ca ];
  11990. customAttribute.array[ offset ] = value.x;
  11991. customAttribute.array[ offset + 1 ] = value.y;
  11992. customAttribute.array[ offset + 2 ] = value.z;
  11993. offset += 3;
  11994. }
  11995. }
  11996. } else if ( customAttribute.size === 4 ) {
  11997. for ( ca = 0; ca < cal; ca ++ ) {
  11998. value = customAttribute.value[ ca ];
  11999. customAttribute.array[ offset ] = value.x;
  12000. customAttribute.array[ offset + 1 ] = value.y;
  12001. customAttribute.array[ offset + 2 ] = value.z;
  12002. customAttribute.array[ offset + 3 ] = value.w;
  12003. offset += 4;
  12004. }
  12005. }
  12006. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12007. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12008. }
  12009. }
  12010. }
  12011. };
  12012. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12013. if ( ! geometryGroup.__inittedArrays ) {
  12014. return;
  12015. }
  12016. var normalType = bufferGuessNormalType( material ),
  12017. vertexColorType = bufferGuessVertexColorType( material ),
  12018. uvType = bufferGuessUVType( material ),
  12019. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12020. var f, fl, fi, face,
  12021. vertexNormals, faceNormal, normal,
  12022. vertexColors, faceColor,
  12023. vertexTangents,
  12024. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12025. c1, c2, c3, c4,
  12026. sw1, sw2, sw3, sw4,
  12027. si1, si2, si3, si4,
  12028. sa1, sa2, sa3, sa4,
  12029. sb1, sb2, sb3, sb4,
  12030. m, ml, i, il,
  12031. vn, uvi, uv2i,
  12032. vk, vkl, vka,
  12033. nka, chf, faceVertexNormals,
  12034. a,
  12035. vertexIndex = 0,
  12036. offset = 0,
  12037. offset_uv = 0,
  12038. offset_uv2 = 0,
  12039. offset_face = 0,
  12040. offset_normal = 0,
  12041. offset_tangent = 0,
  12042. offset_line = 0,
  12043. offset_color = 0,
  12044. offset_skin = 0,
  12045. offset_morphTarget = 0,
  12046. offset_custom = 0,
  12047. offset_customSrc = 0,
  12048. value,
  12049. vertexArray = geometryGroup.__vertexArray,
  12050. uvArray = geometryGroup.__uvArray,
  12051. uv2Array = geometryGroup.__uv2Array,
  12052. normalArray = geometryGroup.__normalArray,
  12053. tangentArray = geometryGroup.__tangentArray,
  12054. colorArray = geometryGroup.__colorArray,
  12055. skinIndexArray = geometryGroup.__skinIndexArray,
  12056. skinWeightArray = geometryGroup.__skinWeightArray,
  12057. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12058. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12059. customAttributes = geometryGroup.__webglCustomAttributesList,
  12060. customAttribute,
  12061. faceArray = geometryGroup.__faceArray,
  12062. lineArray = geometryGroup.__lineArray,
  12063. geometry = object.geometry, // this is shared for all chunks
  12064. dirtyVertices = geometry.verticesNeedUpdate,
  12065. dirtyElements = geometry.elementsNeedUpdate,
  12066. dirtyUvs = geometry.uvsNeedUpdate,
  12067. dirtyNormals = geometry.normalsNeedUpdate,
  12068. dirtyTangents = geometry.tangentsNeedUpdate,
  12069. dirtyColors = geometry.colorsNeedUpdate,
  12070. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12071. vertices = geometry.vertices,
  12072. chunk_faces3 = geometryGroup.faces3,
  12073. chunk_faces4 = geometryGroup.faces4,
  12074. obj_faces = geometry.faces,
  12075. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12076. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12077. obj_colors = geometry.colors,
  12078. obj_skinIndices = geometry.skinIndices,
  12079. obj_skinWeights = geometry.skinWeights,
  12080. morphTargets = geometry.morphTargets,
  12081. morphNormals = geometry.morphNormals;
  12082. if ( dirtyVertices ) {
  12083. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12084. face = obj_faces[ chunk_faces3[ f ] ];
  12085. v1 = vertices[ face.a ];
  12086. v2 = vertices[ face.b ];
  12087. v3 = vertices[ face.c ];
  12088. vertexArray[ offset ] = v1.x;
  12089. vertexArray[ offset + 1 ] = v1.y;
  12090. vertexArray[ offset + 2 ] = v1.z;
  12091. vertexArray[ offset + 3 ] = v2.x;
  12092. vertexArray[ offset + 4 ] = v2.y;
  12093. vertexArray[ offset + 5 ] = v2.z;
  12094. vertexArray[ offset + 6 ] = v3.x;
  12095. vertexArray[ offset + 7 ] = v3.y;
  12096. vertexArray[ offset + 8 ] = v3.z;
  12097. offset += 9;
  12098. }
  12099. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12100. face = obj_faces[ chunk_faces4[ f ] ];
  12101. v1 = vertices[ face.a ];
  12102. v2 = vertices[ face.b ];
  12103. v3 = vertices[ face.c ];
  12104. v4 = vertices[ face.d ];
  12105. vertexArray[ offset ] = v1.x;
  12106. vertexArray[ offset + 1 ] = v1.y;
  12107. vertexArray[ offset + 2 ] = v1.z;
  12108. vertexArray[ offset + 3 ] = v2.x;
  12109. vertexArray[ offset + 4 ] = v2.y;
  12110. vertexArray[ offset + 5 ] = v2.z;
  12111. vertexArray[ offset + 6 ] = v3.x;
  12112. vertexArray[ offset + 7 ] = v3.y;
  12113. vertexArray[ offset + 8 ] = v3.z;
  12114. vertexArray[ offset + 9 ] = v4.x;
  12115. vertexArray[ offset + 10 ] = v4.y;
  12116. vertexArray[ offset + 11 ] = v4.z;
  12117. offset += 12;
  12118. }
  12119. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12120. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12121. }
  12122. if ( dirtyMorphTargets ) {
  12123. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12124. offset_morphTarget = 0;
  12125. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12126. chf = chunk_faces3[ f ];
  12127. face = obj_faces[ chf ];
  12128. // morph positions
  12129. v1 = morphTargets[ vk ].vertices[ face.a ];
  12130. v2 = morphTargets[ vk ].vertices[ face.b ];
  12131. v3 = morphTargets[ vk ].vertices[ face.c ];
  12132. vka = morphTargetsArrays[ vk ];
  12133. vka[ offset_morphTarget ] = v1.x;
  12134. vka[ offset_morphTarget + 1 ] = v1.y;
  12135. vka[ offset_morphTarget + 2 ] = v1.z;
  12136. vka[ offset_morphTarget + 3 ] = v2.x;
  12137. vka[ offset_morphTarget + 4 ] = v2.y;
  12138. vka[ offset_morphTarget + 5 ] = v2.z;
  12139. vka[ offset_morphTarget + 6 ] = v3.x;
  12140. vka[ offset_morphTarget + 7 ] = v3.y;
  12141. vka[ offset_morphTarget + 8 ] = v3.z;
  12142. // morph normals
  12143. if ( material.morphNormals ) {
  12144. if ( needsSmoothNormals ) {
  12145. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12146. n1 = faceVertexNormals.a;
  12147. n2 = faceVertexNormals.b;
  12148. n3 = faceVertexNormals.c;
  12149. } else {
  12150. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12151. n2 = n1;
  12152. n3 = n1;
  12153. }
  12154. nka = morphNormalsArrays[ vk ];
  12155. nka[ offset_morphTarget ] = n1.x;
  12156. nka[ offset_morphTarget + 1 ] = n1.y;
  12157. nka[ offset_morphTarget + 2 ] = n1.z;
  12158. nka[ offset_morphTarget + 3 ] = n2.x;
  12159. nka[ offset_morphTarget + 4 ] = n2.y;
  12160. nka[ offset_morphTarget + 5 ] = n2.z;
  12161. nka[ offset_morphTarget + 6 ] = n3.x;
  12162. nka[ offset_morphTarget + 7 ] = n3.y;
  12163. nka[ offset_morphTarget + 8 ] = n3.z;
  12164. }
  12165. //
  12166. offset_morphTarget += 9;
  12167. }
  12168. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12169. chf = chunk_faces4[ f ];
  12170. face = obj_faces[ chf ];
  12171. // morph positions
  12172. v1 = morphTargets[ vk ].vertices[ face.a ];
  12173. v2 = morphTargets[ vk ].vertices[ face.b ];
  12174. v3 = morphTargets[ vk ].vertices[ face.c ];
  12175. v4 = morphTargets[ vk ].vertices[ face.d ];
  12176. vka = morphTargetsArrays[ vk ];
  12177. vka[ offset_morphTarget ] = v1.x;
  12178. vka[ offset_morphTarget + 1 ] = v1.y;
  12179. vka[ offset_morphTarget + 2 ] = v1.z;
  12180. vka[ offset_morphTarget + 3 ] = v2.x;
  12181. vka[ offset_morphTarget + 4 ] = v2.y;
  12182. vka[ offset_morphTarget + 5 ] = v2.z;
  12183. vka[ offset_morphTarget + 6 ] = v3.x;
  12184. vka[ offset_morphTarget + 7 ] = v3.y;
  12185. vka[ offset_morphTarget + 8 ] = v3.z;
  12186. vka[ offset_morphTarget + 9 ] = v4.x;
  12187. vka[ offset_morphTarget + 10 ] = v4.y;
  12188. vka[ offset_morphTarget + 11 ] = v4.z;
  12189. // morph normals
  12190. if ( material.morphNormals ) {
  12191. if ( needsSmoothNormals ) {
  12192. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12193. n1 = faceVertexNormals.a;
  12194. n2 = faceVertexNormals.b;
  12195. n3 = faceVertexNormals.c;
  12196. n4 = faceVertexNormals.d;
  12197. } else {
  12198. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12199. n2 = n1;
  12200. n3 = n1;
  12201. n4 = n1;
  12202. }
  12203. nka = morphNormalsArrays[ vk ];
  12204. nka[ offset_morphTarget ] = n1.x;
  12205. nka[ offset_morphTarget + 1 ] = n1.y;
  12206. nka[ offset_morphTarget + 2 ] = n1.z;
  12207. nka[ offset_morphTarget + 3 ] = n2.x;
  12208. nka[ offset_morphTarget + 4 ] = n2.y;
  12209. nka[ offset_morphTarget + 5 ] = n2.z;
  12210. nka[ offset_morphTarget + 6 ] = n3.x;
  12211. nka[ offset_morphTarget + 7 ] = n3.y;
  12212. nka[ offset_morphTarget + 8 ] = n3.z;
  12213. nka[ offset_morphTarget + 9 ] = n4.x;
  12214. nka[ offset_morphTarget + 10 ] = n4.y;
  12215. nka[ offset_morphTarget + 11 ] = n4.z;
  12216. }
  12217. //
  12218. offset_morphTarget += 12;
  12219. }
  12220. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12221. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12222. if ( material.morphNormals ) {
  12223. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12224. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12225. }
  12226. }
  12227. }
  12228. if ( obj_skinWeights.length ) {
  12229. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12230. face = obj_faces[ chunk_faces3[ f ] ];
  12231. // weights
  12232. sw1 = obj_skinWeights[ face.a ];
  12233. sw2 = obj_skinWeights[ face.b ];
  12234. sw3 = obj_skinWeights[ face.c ];
  12235. skinWeightArray[ offset_skin ] = sw1.x;
  12236. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12237. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12238. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12239. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12240. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12241. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12242. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12243. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12244. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12245. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12246. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12247. // indices
  12248. si1 = obj_skinIndices[ face.a ];
  12249. si2 = obj_skinIndices[ face.b ];
  12250. si3 = obj_skinIndices[ face.c ];
  12251. skinIndexArray[ offset_skin ] = si1.x;
  12252. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12253. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12254. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12255. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12256. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12257. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12258. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12259. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12260. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12261. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12262. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12263. offset_skin += 12;
  12264. }
  12265. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12266. face = obj_faces[ chunk_faces4[ f ] ];
  12267. // weights
  12268. sw1 = obj_skinWeights[ face.a ];
  12269. sw2 = obj_skinWeights[ face.b ];
  12270. sw3 = obj_skinWeights[ face.c ];
  12271. sw4 = obj_skinWeights[ face.d ];
  12272. skinWeightArray[ offset_skin ] = sw1.x;
  12273. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12274. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12275. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12276. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12277. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12278. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12279. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12280. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12281. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12282. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12283. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12284. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  12285. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  12286. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  12287. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  12288. // indices
  12289. si1 = obj_skinIndices[ face.a ];
  12290. si2 = obj_skinIndices[ face.b ];
  12291. si3 = obj_skinIndices[ face.c ];
  12292. si4 = obj_skinIndices[ face.d ];
  12293. skinIndexArray[ offset_skin ] = si1.x;
  12294. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12295. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12296. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12297. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12298. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12299. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12300. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12301. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12302. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12303. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12304. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12305. skinIndexArray[ offset_skin + 12 ] = si4.x;
  12306. skinIndexArray[ offset_skin + 13 ] = si4.y;
  12307. skinIndexArray[ offset_skin + 14 ] = si4.z;
  12308. skinIndexArray[ offset_skin + 15 ] = si4.w;
  12309. offset_skin += 16;
  12310. }
  12311. if ( offset_skin > 0 ) {
  12312. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12313. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12314. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12315. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12316. }
  12317. }
  12318. if ( dirtyColors && vertexColorType ) {
  12319. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12320. face = obj_faces[ chunk_faces3[ f ] ];
  12321. vertexColors = face.vertexColors;
  12322. faceColor = face.color;
  12323. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12324. c1 = vertexColors[ 0 ];
  12325. c2 = vertexColors[ 1 ];
  12326. c3 = vertexColors[ 2 ];
  12327. } else {
  12328. c1 = faceColor;
  12329. c2 = faceColor;
  12330. c3 = faceColor;
  12331. }
  12332. colorArray[ offset_color ] = c1.r;
  12333. colorArray[ offset_color + 1 ] = c1.g;
  12334. colorArray[ offset_color + 2 ] = c1.b;
  12335. colorArray[ offset_color + 3 ] = c2.r;
  12336. colorArray[ offset_color + 4 ] = c2.g;
  12337. colorArray[ offset_color + 5 ] = c2.b;
  12338. colorArray[ offset_color + 6 ] = c3.r;
  12339. colorArray[ offset_color + 7 ] = c3.g;
  12340. colorArray[ offset_color + 8 ] = c3.b;
  12341. offset_color += 9;
  12342. }
  12343. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12344. face = obj_faces[ chunk_faces4[ f ] ];
  12345. vertexColors = face.vertexColors;
  12346. faceColor = face.color;
  12347. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12348. c1 = vertexColors[ 0 ];
  12349. c2 = vertexColors[ 1 ];
  12350. c3 = vertexColors[ 2 ];
  12351. c4 = vertexColors[ 3 ];
  12352. } else {
  12353. c1 = faceColor;
  12354. c2 = faceColor;
  12355. c3 = faceColor;
  12356. c4 = faceColor;
  12357. }
  12358. colorArray[ offset_color ] = c1.r;
  12359. colorArray[ offset_color + 1 ] = c1.g;
  12360. colorArray[ offset_color + 2 ] = c1.b;
  12361. colorArray[ offset_color + 3 ] = c2.r;
  12362. colorArray[ offset_color + 4 ] = c2.g;
  12363. colorArray[ offset_color + 5 ] = c2.b;
  12364. colorArray[ offset_color + 6 ] = c3.r;
  12365. colorArray[ offset_color + 7 ] = c3.g;
  12366. colorArray[ offset_color + 8 ] = c3.b;
  12367. colorArray[ offset_color + 9 ] = c4.r;
  12368. colorArray[ offset_color + 10 ] = c4.g;
  12369. colorArray[ offset_color + 11 ] = c4.b;
  12370. offset_color += 12;
  12371. }
  12372. if ( offset_color > 0 ) {
  12373. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12374. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12375. }
  12376. }
  12377. if ( dirtyTangents && geometry.hasTangents ) {
  12378. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12379. face = obj_faces[ chunk_faces3[ f ] ];
  12380. vertexTangents = face.vertexTangents;
  12381. t1 = vertexTangents[ 0 ];
  12382. t2 = vertexTangents[ 1 ];
  12383. t3 = vertexTangents[ 2 ];
  12384. tangentArray[ offset_tangent ] = t1.x;
  12385. tangentArray[ offset_tangent + 1 ] = t1.y;
  12386. tangentArray[ offset_tangent + 2 ] = t1.z;
  12387. tangentArray[ offset_tangent + 3 ] = t1.w;
  12388. tangentArray[ offset_tangent + 4 ] = t2.x;
  12389. tangentArray[ offset_tangent + 5 ] = t2.y;
  12390. tangentArray[ offset_tangent + 6 ] = t2.z;
  12391. tangentArray[ offset_tangent + 7 ] = t2.w;
  12392. tangentArray[ offset_tangent + 8 ] = t3.x;
  12393. tangentArray[ offset_tangent + 9 ] = t3.y;
  12394. tangentArray[ offset_tangent + 10 ] = t3.z;
  12395. tangentArray[ offset_tangent + 11 ] = t3.w;
  12396. offset_tangent += 12;
  12397. }
  12398. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12399. face = obj_faces[ chunk_faces4[ f ] ];
  12400. vertexTangents = face.vertexTangents;
  12401. t1 = vertexTangents[ 0 ];
  12402. t2 = vertexTangents[ 1 ];
  12403. t3 = vertexTangents[ 2 ];
  12404. t4 = vertexTangents[ 3 ];
  12405. tangentArray[ offset_tangent ] = t1.x;
  12406. tangentArray[ offset_tangent + 1 ] = t1.y;
  12407. tangentArray[ offset_tangent + 2 ] = t1.z;
  12408. tangentArray[ offset_tangent + 3 ] = t1.w;
  12409. tangentArray[ offset_tangent + 4 ] = t2.x;
  12410. tangentArray[ offset_tangent + 5 ] = t2.y;
  12411. tangentArray[ offset_tangent + 6 ] = t2.z;
  12412. tangentArray[ offset_tangent + 7 ] = t2.w;
  12413. tangentArray[ offset_tangent + 8 ] = t3.x;
  12414. tangentArray[ offset_tangent + 9 ] = t3.y;
  12415. tangentArray[ offset_tangent + 10 ] = t3.z;
  12416. tangentArray[ offset_tangent + 11 ] = t3.w;
  12417. tangentArray[ offset_tangent + 12 ] = t4.x;
  12418. tangentArray[ offset_tangent + 13 ] = t4.y;
  12419. tangentArray[ offset_tangent + 14 ] = t4.z;
  12420. tangentArray[ offset_tangent + 15 ] = t4.w;
  12421. offset_tangent += 16;
  12422. }
  12423. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12424. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12425. }
  12426. if ( dirtyNormals && normalType ) {
  12427. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12428. face = obj_faces[ chunk_faces3[ f ] ];
  12429. vertexNormals = face.vertexNormals;
  12430. faceNormal = face.normal;
  12431. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12432. for ( i = 0; i < 3; i ++ ) {
  12433. vn = vertexNormals[ i ];
  12434. normalArray[ offset_normal ] = vn.x;
  12435. normalArray[ offset_normal + 1 ] = vn.y;
  12436. normalArray[ offset_normal + 2 ] = vn.z;
  12437. offset_normal += 3;
  12438. }
  12439. } else {
  12440. for ( i = 0; i < 3; i ++ ) {
  12441. normalArray[ offset_normal ] = faceNormal.x;
  12442. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12443. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12444. offset_normal += 3;
  12445. }
  12446. }
  12447. }
  12448. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12449. face = obj_faces[ chunk_faces4[ f ] ];
  12450. vertexNormals = face.vertexNormals;
  12451. faceNormal = face.normal;
  12452. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12453. for ( i = 0; i < 4; i ++ ) {
  12454. vn = vertexNormals[ i ];
  12455. normalArray[ offset_normal ] = vn.x;
  12456. normalArray[ offset_normal + 1 ] = vn.y;
  12457. normalArray[ offset_normal + 2 ] = vn.z;
  12458. offset_normal += 3;
  12459. }
  12460. } else {
  12461. for ( i = 0; i < 4; i ++ ) {
  12462. normalArray[ offset_normal ] = faceNormal.x;
  12463. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12464. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12465. offset_normal += 3;
  12466. }
  12467. }
  12468. }
  12469. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12470. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12471. }
  12472. if ( dirtyUvs && obj_uvs && uvType ) {
  12473. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12474. fi = chunk_faces3[ f ];
  12475. uv = obj_uvs[ fi ];
  12476. if ( uv === undefined ) continue;
  12477. for ( i = 0; i < 3; i ++ ) {
  12478. uvi = uv[ i ];
  12479. uvArray[ offset_uv ] = uvi.x;
  12480. uvArray[ offset_uv + 1 ] = uvi.y;
  12481. offset_uv += 2;
  12482. }
  12483. }
  12484. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12485. fi = chunk_faces4[ f ];
  12486. uv = obj_uvs[ fi ];
  12487. if ( uv === undefined ) continue;
  12488. for ( i = 0; i < 4; i ++ ) {
  12489. uvi = uv[ i ];
  12490. uvArray[ offset_uv ] = uvi.x;
  12491. uvArray[ offset_uv + 1 ] = uvi.y;
  12492. offset_uv += 2;
  12493. }
  12494. }
  12495. if ( offset_uv > 0 ) {
  12496. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12497. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12498. }
  12499. }
  12500. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12501. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12502. fi = chunk_faces3[ f ];
  12503. uv2 = obj_uvs2[ fi ];
  12504. if ( uv2 === undefined ) continue;
  12505. for ( i = 0; i < 3; i ++ ) {
  12506. uv2i = uv2[ i ];
  12507. uv2Array[ offset_uv2 ] = uv2i.x;
  12508. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12509. offset_uv2 += 2;
  12510. }
  12511. }
  12512. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12513. fi = chunk_faces4[ f ];
  12514. uv2 = obj_uvs2[ fi ];
  12515. if ( uv2 === undefined ) continue;
  12516. for ( i = 0; i < 4; i ++ ) {
  12517. uv2i = uv2[ i ];
  12518. uv2Array[ offset_uv2 ] = uv2i.x;
  12519. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12520. offset_uv2 += 2;
  12521. }
  12522. }
  12523. if ( offset_uv2 > 0 ) {
  12524. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12525. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12526. }
  12527. }
  12528. if ( dirtyElements ) {
  12529. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12530. faceArray[ offset_face ] = vertexIndex;
  12531. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12532. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12533. offset_face += 3;
  12534. lineArray[ offset_line ] = vertexIndex;
  12535. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12536. lineArray[ offset_line + 2 ] = vertexIndex;
  12537. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12538. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12539. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12540. offset_line += 6;
  12541. vertexIndex += 3;
  12542. }
  12543. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12544. faceArray[ offset_face ] = vertexIndex;
  12545. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12546. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12547. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12548. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12549. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12550. offset_face += 6;
  12551. lineArray[ offset_line ] = vertexIndex;
  12552. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12553. lineArray[ offset_line + 2 ] = vertexIndex;
  12554. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12555. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12556. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12557. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12558. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12559. offset_line += 8;
  12560. vertexIndex += 4;
  12561. }
  12562. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12563. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12564. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12565. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12566. }
  12567. if ( customAttributes ) {
  12568. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12569. customAttribute = customAttributes[ i ];
  12570. if ( ! customAttribute.__original.needsUpdate ) continue;
  12571. offset_custom = 0;
  12572. offset_customSrc = 0;
  12573. if ( customAttribute.size === 1 ) {
  12574. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12575. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12576. face = obj_faces[ chunk_faces3[ f ] ];
  12577. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12578. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12579. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12580. offset_custom += 3;
  12581. }
  12582. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12583. face = obj_faces[ chunk_faces4[ f ] ];
  12584. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12585. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12586. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12587. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  12588. offset_custom += 4;
  12589. }
  12590. } else if ( customAttribute.boundTo === "faces" ) {
  12591. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12592. value = customAttribute.value[ chunk_faces3[ f ] ];
  12593. customAttribute.array[ offset_custom ] = value;
  12594. customAttribute.array[ offset_custom + 1 ] = value;
  12595. customAttribute.array[ offset_custom + 2 ] = value;
  12596. offset_custom += 3;
  12597. }
  12598. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12599. value = customAttribute.value[ chunk_faces4[ f ] ];
  12600. customAttribute.array[ offset_custom ] = value;
  12601. customAttribute.array[ offset_custom + 1 ] = value;
  12602. customAttribute.array[ offset_custom + 2 ] = value;
  12603. customAttribute.array[ offset_custom + 3 ] = value;
  12604. offset_custom += 4;
  12605. }
  12606. }
  12607. } else if ( customAttribute.size === 2 ) {
  12608. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12609. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12610. face = obj_faces[ chunk_faces3[ f ] ];
  12611. v1 = customAttribute.value[ face.a ];
  12612. v2 = customAttribute.value[ face.b ];
  12613. v3 = customAttribute.value[ face.c ];
  12614. customAttribute.array[ offset_custom ] = v1.x;
  12615. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12616. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12617. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12618. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12619. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12620. offset_custom += 6;
  12621. }
  12622. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12623. face = obj_faces[ chunk_faces4[ f ] ];
  12624. v1 = customAttribute.value[ face.a ];
  12625. v2 = customAttribute.value[ face.b ];
  12626. v3 = customAttribute.value[ face.c ];
  12627. v4 = customAttribute.value[ face.d ];
  12628. customAttribute.array[ offset_custom ] = v1.x;
  12629. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12630. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12631. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12632. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12633. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12634. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12635. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12636. offset_custom += 8;
  12637. }
  12638. } else if ( customAttribute.boundTo === "faces" ) {
  12639. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12640. value = customAttribute.value[ chunk_faces3[ f ] ];
  12641. v1 = value;
  12642. v2 = value;
  12643. v3 = value;
  12644. customAttribute.array[ offset_custom ] = v1.x;
  12645. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12646. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12647. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12648. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12649. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12650. offset_custom += 6;
  12651. }
  12652. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12653. value = customAttribute.value[ chunk_faces4[ f ] ];
  12654. v1 = value;
  12655. v2 = value;
  12656. v3 = value;
  12657. v4 = value;
  12658. customAttribute.array[ offset_custom ] = v1.x;
  12659. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12660. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12661. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12662. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12663. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12664. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12665. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12666. offset_custom += 8;
  12667. }
  12668. }
  12669. } else if ( customAttribute.size === 3 ) {
  12670. var pp;
  12671. if ( customAttribute.type === "c" ) {
  12672. pp = [ "r", "g", "b" ];
  12673. } else {
  12674. pp = [ "x", "y", "z" ];
  12675. }
  12676. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12677. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12678. face = obj_faces[ chunk_faces3[ f ] ];
  12679. v1 = customAttribute.value[ face.a ];
  12680. v2 = customAttribute.value[ face.b ];
  12681. v3 = customAttribute.value[ face.c ];
  12682. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12683. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12684. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12685. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12686. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12687. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12688. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12689. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12690. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12691. offset_custom += 9;
  12692. }
  12693. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12694. face = obj_faces[ chunk_faces4[ f ] ];
  12695. v1 = customAttribute.value[ face.a ];
  12696. v2 = customAttribute.value[ face.b ];
  12697. v3 = customAttribute.value[ face.c ];
  12698. v4 = customAttribute.value[ face.d ];
  12699. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12700. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12701. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12702. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12703. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12704. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12705. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12706. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12707. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12708. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12709. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12710. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12711. offset_custom += 12;
  12712. }
  12713. } else if ( customAttribute.boundTo === "faces" ) {
  12714. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12715. value = customAttribute.value[ chunk_faces3[ f ] ];
  12716. v1 = value;
  12717. v2 = value;
  12718. v3 = value;
  12719. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12720. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12721. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12722. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12723. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12724. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12725. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12726. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12727. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12728. offset_custom += 9;
  12729. }
  12730. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12731. value = customAttribute.value[ chunk_faces4[ f ] ];
  12732. v1 = value;
  12733. v2 = value;
  12734. v3 = value;
  12735. v4 = value;
  12736. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12737. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12738. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12739. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12740. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12741. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12742. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12743. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12744. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12745. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12746. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12747. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12748. offset_custom += 12;
  12749. }
  12750. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12751. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12752. value = customAttribute.value[ chunk_faces3[ f ] ];
  12753. v1 = value[ 0 ];
  12754. v2 = value[ 1 ];
  12755. v3 = value[ 2 ];
  12756. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12757. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12758. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12759. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12760. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12761. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12762. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12763. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12764. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12765. offset_custom += 9;
  12766. }
  12767. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12768. value = customAttribute.value[ chunk_faces4[ f ] ];
  12769. v1 = value[ 0 ];
  12770. v2 = value[ 1 ];
  12771. v3 = value[ 2 ];
  12772. v4 = value[ 3 ];
  12773. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12774. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12775. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12776. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12777. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12778. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12779. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12780. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12781. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12782. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12783. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12784. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12785. offset_custom += 12;
  12786. }
  12787. }
  12788. } else if ( customAttribute.size === 4 ) {
  12789. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12790. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12791. face = obj_faces[ chunk_faces3[ f ] ];
  12792. v1 = customAttribute.value[ face.a ];
  12793. v2 = customAttribute.value[ face.b ];
  12794. v3 = customAttribute.value[ face.c ];
  12795. customAttribute.array[ offset_custom ] = v1.x;
  12796. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12797. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12798. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12799. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12800. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12801. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12802. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12803. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12804. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12805. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12806. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12807. offset_custom += 12;
  12808. }
  12809. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12810. face = obj_faces[ chunk_faces4[ f ] ];
  12811. v1 = customAttribute.value[ face.a ];
  12812. v2 = customAttribute.value[ face.b ];
  12813. v3 = customAttribute.value[ face.c ];
  12814. v4 = customAttribute.value[ face.d ];
  12815. customAttribute.array[ offset_custom ] = v1.x;
  12816. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12817. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12818. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12819. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12820. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12821. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12822. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12823. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12824. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12825. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12826. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12827. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12828. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12829. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12830. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12831. offset_custom += 16;
  12832. }
  12833. } else if ( customAttribute.boundTo === "faces" ) {
  12834. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12835. value = customAttribute.value[ chunk_faces3[ f ] ];
  12836. v1 = value;
  12837. v2 = value;
  12838. v3 = value;
  12839. customAttribute.array[ offset_custom ] = v1.x;
  12840. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12841. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12842. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12843. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12844. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12845. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12846. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12847. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12848. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12849. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12850. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12851. offset_custom += 12;
  12852. }
  12853. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12854. value = customAttribute.value[ chunk_faces4[ f ] ];
  12855. v1 = value;
  12856. v2 = value;
  12857. v3 = value;
  12858. v4 = value;
  12859. customAttribute.array[ offset_custom ] = v1.x;
  12860. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12861. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12862. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12863. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12864. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12865. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12866. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12867. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12868. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12869. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12870. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12871. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12872. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12873. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12874. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12875. offset_custom += 16;
  12876. }
  12877. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12878. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12879. value = customAttribute.value[ chunk_faces3[ f ] ];
  12880. v1 = value[ 0 ];
  12881. v2 = value[ 1 ];
  12882. v3 = value[ 2 ];
  12883. customAttribute.array[ offset_custom ] = v1.x;
  12884. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12885. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12886. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12887. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12888. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12889. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12890. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12891. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12892. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12893. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12894. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12895. offset_custom += 12;
  12896. }
  12897. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12898. value = customAttribute.value[ chunk_faces4[ f ] ];
  12899. v1 = value[ 0 ];
  12900. v2 = value[ 1 ];
  12901. v3 = value[ 2 ];
  12902. v4 = value[ 3 ];
  12903. customAttribute.array[ offset_custom ] = v1.x;
  12904. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12905. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12906. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12907. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12908. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12909. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12910. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12911. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12912. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12913. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12914. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12915. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12916. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12917. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12918. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12919. offset_custom += 16;
  12920. }
  12921. }
  12922. }
  12923. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12924. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12925. }
  12926. }
  12927. if ( dispose ) {
  12928. delete geometryGroup.__inittedArrays;
  12929. delete geometryGroup.__colorArray;
  12930. delete geometryGroup.__normalArray;
  12931. delete geometryGroup.__tangentArray;
  12932. delete geometryGroup.__uvArray;
  12933. delete geometryGroup.__uv2Array;
  12934. delete geometryGroup.__faceArray;
  12935. delete geometryGroup.__vertexArray;
  12936. delete geometryGroup.__lineArray;
  12937. delete geometryGroup.__skinIndexArray;
  12938. delete geometryGroup.__skinWeightArray;
  12939. }
  12940. };
  12941. function setDirectBuffers ( geometry, hint, dispose ) {
  12942. var attributes = geometry.attributes;
  12943. var attributeName, attributeItem;
  12944. for ( attributeName in attributes ) {
  12945. attributeItem = attributes[ attributeName ];
  12946. if ( attributeItem.needsUpdate ) {
  12947. if ( attributeName === 'index' ) {
  12948. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  12949. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  12950. } else {
  12951. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  12952. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  12953. }
  12954. attributeItem.needsUpdate = false;
  12955. }
  12956. if ( dispose && ! attributeItem.dynamic ) {
  12957. delete attributeItem.array;
  12958. }
  12959. }
  12960. };
  12961. // Buffer rendering
  12962. this.renderBufferImmediate = function ( object, program, material ) {
  12963. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12964. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12965. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12966. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12967. if ( object.hasPositions ) {
  12968. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12969. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12970. _gl.enableVertexAttribArray( program.attributes.position );
  12971. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12972. }
  12973. if ( object.hasNormals ) {
  12974. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12975. if ( material.shading === THREE.FlatShading ) {
  12976. var nx, ny, nz,
  12977. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12978. normalArray,
  12979. i, il = object.count * 3;
  12980. for( i = 0; i < il; i += 9 ) {
  12981. normalArray = object.normalArray;
  12982. nax = normalArray[ i ];
  12983. nay = normalArray[ i + 1 ];
  12984. naz = normalArray[ i + 2 ];
  12985. nbx = normalArray[ i + 3 ];
  12986. nby = normalArray[ i + 4 ];
  12987. nbz = normalArray[ i + 5 ];
  12988. ncx = normalArray[ i + 6 ];
  12989. ncy = normalArray[ i + 7 ];
  12990. ncz = normalArray[ i + 8 ];
  12991. nx = ( nax + nbx + ncx ) / 3;
  12992. ny = ( nay + nby + ncy ) / 3;
  12993. nz = ( naz + nbz + ncz ) / 3;
  12994. normalArray[ i ] = nx;
  12995. normalArray[ i + 1 ] = ny;
  12996. normalArray[ i + 2 ] = nz;
  12997. normalArray[ i + 3 ] = nx;
  12998. normalArray[ i + 4 ] = ny;
  12999. normalArray[ i + 5 ] = nz;
  13000. normalArray[ i + 6 ] = nx;
  13001. normalArray[ i + 7 ] = ny;
  13002. normalArray[ i + 8 ] = nz;
  13003. }
  13004. }
  13005. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13006. _gl.enableVertexAttribArray( program.attributes.normal );
  13007. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13008. }
  13009. if ( object.hasUvs && material.map ) {
  13010. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13011. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13012. _gl.enableVertexAttribArray( program.attributes.uv );
  13013. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13014. }
  13015. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13016. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13017. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13018. _gl.enableVertexAttribArray( program.attributes.color );
  13019. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13020. }
  13021. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13022. object.count = 0;
  13023. };
  13024. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13025. if ( material.visible === false ) return;
  13026. var program, programAttributes, linewidth, primitives, a, attribute, geometryAttributes;
  13027. var attributeItem, attributeName, attributePointer, attributeSize;
  13028. program = setProgram( camera, lights, fog, material, object );
  13029. programAttributes = program.attributes;
  13030. geometryAttributes = geometry.attributes;
  13031. var updateBuffers = false,
  13032. wireframeBit = material.wireframe ? 1 : 0,
  13033. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13034. if ( geometryHash !== _currentGeometryGroupHash ) {
  13035. _currentGeometryGroupHash = geometryHash;
  13036. updateBuffers = true;
  13037. }
  13038. if ( updateBuffers ) {
  13039. disableAttributes();
  13040. }
  13041. // render mesh
  13042. if ( object instanceof THREE.Mesh ) {
  13043. var index = geometryAttributes[ "index" ];
  13044. // indexed triangles
  13045. if ( index ) {
  13046. var offsets = geometry.offsets;
  13047. // if there is more than 1 chunk
  13048. // must set attribute pointers to use new offsets for each chunk
  13049. // even if geometry and materials didn't change
  13050. if ( offsets.length > 1 ) updateBuffers = true;
  13051. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13052. var startIndex = offsets[ i ].index;
  13053. if ( updateBuffers ) {
  13054. for ( attributeName in geometryAttributes ) {
  13055. if ( attributeName === 'index' ) continue;
  13056. attributePointer = programAttributes[ attributeName ];
  13057. attributeItem = geometryAttributes[ attributeName ];
  13058. attributeSize = attributeItem.itemSize;
  13059. if ( attributePointer >= 0 ) {
  13060. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13061. enableAttribute( attributePointer );
  13062. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13063. }
  13064. }
  13065. // indices
  13066. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13067. }
  13068. // render indexed triangles
  13069. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13070. _this.info.render.calls ++;
  13071. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13072. _this.info.render.faces += offsets[ i ].count / 3;
  13073. }
  13074. // non-indexed triangles
  13075. } else {
  13076. if ( updateBuffers ) {
  13077. for ( attributeName in geometryAttributes ) {
  13078. if ( attributeName === 'index') continue;
  13079. attributePointer = programAttributes[ attributeName ];
  13080. attributeItem = geometryAttributes[ attributeName ];
  13081. attributeSize = attributeItem.itemSize;
  13082. if ( attributePointer >= 0 ) {
  13083. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13084. enableAttribute( attributePointer );
  13085. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13086. }
  13087. }
  13088. }
  13089. var position = geometry.attributes[ "position" ];
  13090. // render non-indexed triangles
  13091. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13092. _this.info.render.calls ++;
  13093. _this.info.render.vertices += position.numItems / 3;
  13094. _this.info.render.faces += position.numItems / 3 / 3;
  13095. }
  13096. // render particles
  13097. } else if ( object instanceof THREE.ParticleSystem ) {
  13098. if ( updateBuffers ) {
  13099. for ( attributeName in geometryAttributes ) {
  13100. attributePointer = programAttributes[ attributeName ];
  13101. attributeItem = geometryAttributes[ attributeName ];
  13102. attributeSize = attributeItem.itemSize;
  13103. if ( attributePointer >= 0 ) {
  13104. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13105. enableAttribute( attributePointer );
  13106. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13107. }
  13108. }
  13109. var position = geometryAttributes[ "position" ];
  13110. // render particles
  13111. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13112. _this.info.render.calls ++;
  13113. _this.info.render.points += position.numItems / 3;
  13114. }
  13115. } else if ( object instanceof THREE.Line ) {
  13116. if ( updateBuffers ) {
  13117. for ( attributeName in geometryAttributes ) {
  13118. attributePointer = programAttributes[ attributeName ];
  13119. attributeItem = geometryAttributes[ attributeName ];
  13120. attributeSize = attributeItem.itemSize;
  13121. if ( attributePointer >= 0 ) {
  13122. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13123. enableAttribute( attributePointer );
  13124. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13125. }
  13126. }
  13127. // render lines
  13128. setLineWidth( material.linewidth );
  13129. var position = geometryAttributes[ "position" ];
  13130. _gl.drawArrays( _gl.LINE_STRIP, 0, position.numItems / 3 );
  13131. _this.info.render.calls ++;
  13132. _this.info.render.points += position.numItems;
  13133. }
  13134. }
  13135. };
  13136. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13137. if ( material.visible === false ) return;
  13138. var program, attributes, linewidth, primitives, a, attribute, i, il;
  13139. program = setProgram( camera, lights, fog, material, object );
  13140. attributes = program.attributes;
  13141. var updateBuffers = false,
  13142. wireframeBit = material.wireframe ? 1 : 0,
  13143. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13144. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13145. _currentGeometryGroupHash = geometryGroupHash;
  13146. updateBuffers = true;
  13147. }
  13148. if ( updateBuffers ) {
  13149. disableAttributes();
  13150. }
  13151. // vertices
  13152. if ( !material.morphTargets && attributes.position >= 0 ) {
  13153. if ( updateBuffers ) {
  13154. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13155. enableAttribute( attributes.position );
  13156. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13157. }
  13158. } else {
  13159. if ( object.morphTargetBase ) {
  13160. setupMorphTargets( material, geometryGroup, object );
  13161. }
  13162. }
  13163. if ( updateBuffers ) {
  13164. // custom attributes
  13165. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13166. if ( geometryGroup.__webglCustomAttributesList ) {
  13167. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13168. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13169. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13170. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13171. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13172. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13173. }
  13174. }
  13175. }
  13176. // colors
  13177. if ( attributes.color >= 0 ) {
  13178. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13179. enableAttribute( attributes.color );
  13180. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13181. }
  13182. // normals
  13183. if ( attributes.normal >= 0 ) {
  13184. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13185. enableAttribute( attributes.normal );
  13186. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13187. }
  13188. // tangents
  13189. if ( attributes.tangent >= 0 ) {
  13190. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13191. enableAttribute( attributes.tangent );
  13192. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13193. }
  13194. // uvs
  13195. if ( attributes.uv >= 0 ) {
  13196. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13197. enableAttribute( attributes.uv );
  13198. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13199. }
  13200. if ( attributes.uv2 >= 0 ) {
  13201. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13202. enableAttribute( attributes.uv2 );
  13203. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13204. }
  13205. if ( material.skinning &&
  13206. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13207. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13208. enableAttribute( attributes.skinIndex );
  13209. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13210. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13211. enableAttribute( attributes.skinWeight );
  13212. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13213. }
  13214. // line distances
  13215. if ( attributes.lineDistance >= 0 ) {
  13216. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13217. enableAttribute( attributes.lineDistance );
  13218. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13219. }
  13220. }
  13221. // render mesh
  13222. if ( object instanceof THREE.Mesh ) {
  13223. // wireframe
  13224. if ( material.wireframe ) {
  13225. setLineWidth( material.wireframeLinewidth );
  13226. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13227. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13228. // triangles
  13229. } else {
  13230. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13231. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13232. }
  13233. _this.info.render.calls ++;
  13234. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13235. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13236. // render lines
  13237. } else if ( object instanceof THREE.Line ) {
  13238. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13239. setLineWidth( material.linewidth );
  13240. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13241. _this.info.render.calls ++;
  13242. // render particles
  13243. } else if ( object instanceof THREE.ParticleSystem ) {
  13244. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13245. _this.info.render.calls ++;
  13246. _this.info.render.points += geometryGroup.__webglParticleCount;
  13247. // render ribbon
  13248. } else if ( object instanceof THREE.Ribbon ) {
  13249. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13250. _this.info.render.calls ++;
  13251. }
  13252. };
  13253. function enableAttribute( attribute ) {
  13254. if ( ! _enabledAttributes[ attribute ] ) {
  13255. _gl.enableVertexAttribArray( attribute );
  13256. _enabledAttributes[ attribute ] = true;
  13257. }
  13258. };
  13259. function disableAttributes() {
  13260. for ( var attribute in _enabledAttributes ) {
  13261. if ( _enabledAttributes[ attribute ] ) {
  13262. _gl.disableVertexAttribArray( attribute );
  13263. _enabledAttributes[ attribute ] = false;
  13264. }
  13265. }
  13266. };
  13267. function setupMorphTargets ( material, geometryGroup, object ) {
  13268. // set base
  13269. var attributes = material.program.attributes;
  13270. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13271. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13272. enableAttribute( attributes.position );
  13273. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13274. } else if ( attributes.position >= 0 ) {
  13275. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13276. enableAttribute( attributes.position );
  13277. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13278. }
  13279. if ( object.morphTargetForcedOrder.length ) {
  13280. // set forced order
  13281. var m = 0;
  13282. var order = object.morphTargetForcedOrder;
  13283. var influences = object.morphTargetInfluences;
  13284. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13285. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13286. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13287. enableAttribute( attributes[ "morphTarget" + m ] );
  13288. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13289. }
  13290. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13291. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13292. enableAttribute( attributes[ "morphNormal" + m ] );
  13293. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13294. }
  13295. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13296. m ++;
  13297. }
  13298. } else {
  13299. // find the most influencing
  13300. var influence, activeInfluenceIndices = [];
  13301. var influences = object.morphTargetInfluences;
  13302. var i, il = influences.length;
  13303. for ( i = 0; i < il; i ++ ) {
  13304. influence = influences[ i ];
  13305. if ( influence > 0 ) {
  13306. activeInfluenceIndices.push( [ influence, i ] );
  13307. }
  13308. }
  13309. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13310. activeInfluenceIndices.sort( numericalSort );
  13311. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13312. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13313. activeInfluenceIndices.sort( numericalSort );
  13314. } else if ( activeInfluenceIndices.length === 0 ) {
  13315. activeInfluenceIndices.push( [ 0, 0 ] );
  13316. };
  13317. var influenceIndex, m = 0;
  13318. while ( m < material.numSupportedMorphTargets ) {
  13319. if ( activeInfluenceIndices[ m ] ) {
  13320. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13321. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13322. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13323. enableAttribute( attributes[ "morphTarget" + m ] );
  13324. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13325. }
  13326. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13327. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13328. enableAttribute( attributes[ "morphNormal" + m ] );
  13329. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13330. }
  13331. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13332. } else {
  13333. /*
  13334. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13335. if ( material.morphNormals ) {
  13336. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13337. }
  13338. */
  13339. object.__webglMorphTargetInfluences[ m ] = 0;
  13340. }
  13341. m ++;
  13342. }
  13343. }
  13344. // load updated influences uniform
  13345. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13346. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13347. }
  13348. };
  13349. // Sorting
  13350. function painterSortStable ( a, b ) {
  13351. if ( a.z !== b.z ) {
  13352. return b.z - a.z;
  13353. } else {
  13354. return a.id - b.id;
  13355. }
  13356. };
  13357. function numericalSort ( a, b ) {
  13358. return b[ 0 ] - a[ 0 ];
  13359. };
  13360. // Rendering
  13361. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13362. if ( camera instanceof THREE.Camera === false ) {
  13363. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13364. return;
  13365. }
  13366. var i, il,
  13367. webglObject, object,
  13368. renderList,
  13369. lights = scene.__lights,
  13370. fog = scene.fog;
  13371. // reset caching for this frame
  13372. _currentMaterialId = -1;
  13373. _lightsNeedUpdate = true;
  13374. // update scene graph
  13375. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13376. // update camera matrices and frustum
  13377. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13378. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13379. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13380. _frustum.setFromMatrix( _projScreenMatrix );
  13381. // update WebGL objects
  13382. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13383. // custom render plugins (pre pass)
  13384. renderPlugins( this.renderPluginsPre, scene, camera );
  13385. //
  13386. _this.info.render.calls = 0;
  13387. _this.info.render.vertices = 0;
  13388. _this.info.render.faces = 0;
  13389. _this.info.render.points = 0;
  13390. this.setRenderTarget( renderTarget );
  13391. if ( this.autoClear || forceClear ) {
  13392. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13393. }
  13394. // set matrices for regular objects (frustum culled)
  13395. renderList = scene.__webglObjects;
  13396. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13397. webglObject = renderList[ i ];
  13398. object = webglObject.object;
  13399. webglObject.id = i;
  13400. webglObject.render = false;
  13401. if ( object.visible ) {
  13402. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13403. setupMatrices( object, camera );
  13404. unrollBufferMaterial( webglObject );
  13405. webglObject.render = true;
  13406. if ( this.sortObjects === true ) {
  13407. if ( object.renderDepth !== null ) {
  13408. webglObject.z = object.renderDepth;
  13409. } else {
  13410. _vector3.getPositionFromMatrix( object.matrixWorld );
  13411. _vector3.applyProjection( _projScreenMatrix );
  13412. webglObject.z = _vector3.z;
  13413. }
  13414. }
  13415. }
  13416. }
  13417. }
  13418. if ( this.sortObjects ) {
  13419. renderList.sort( painterSortStable );
  13420. }
  13421. // set matrices for immediate objects
  13422. renderList = scene.__webglObjectsImmediate;
  13423. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13424. webglObject = renderList[ i ];
  13425. object = webglObject.object;
  13426. if ( object.visible ) {
  13427. setupMatrices( object, camera );
  13428. unrollImmediateBufferMaterial( webglObject );
  13429. }
  13430. }
  13431. if ( scene.overrideMaterial ) {
  13432. var material = scene.overrideMaterial;
  13433. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13434. this.setDepthTest( material.depthTest );
  13435. this.setDepthWrite( material.depthWrite );
  13436. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13437. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13438. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13439. } else {
  13440. var material = null;
  13441. // opaque pass (front-to-back order)
  13442. this.setBlending( THREE.NoBlending );
  13443. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13444. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13445. // transparent pass (back-to-front order)
  13446. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13447. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13448. }
  13449. // custom render plugins (post pass)
  13450. renderPlugins( this.renderPluginsPost, scene, camera );
  13451. // Generate mipmap if we're using any kind of mipmap filtering
  13452. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13453. updateRenderTargetMipmap( renderTarget );
  13454. }
  13455. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13456. this.setDepthTest( true );
  13457. this.setDepthWrite( true );
  13458. // _gl.finish();
  13459. };
  13460. function renderPlugins( plugins, scene, camera ) {
  13461. if ( ! plugins.length ) return;
  13462. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13463. // reset state for plugin (to start from clean slate)
  13464. _currentProgram = null;
  13465. _currentCamera = null;
  13466. _oldBlending = -1;
  13467. _oldDepthTest = -1;
  13468. _oldDepthWrite = -1;
  13469. _oldDoubleSided = -1;
  13470. _oldFlipSided = -1;
  13471. _currentGeometryGroupHash = -1;
  13472. _currentMaterialId = -1;
  13473. _lightsNeedUpdate = true;
  13474. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13475. // reset state after plugin (anything could have changed)
  13476. _currentProgram = null;
  13477. _currentCamera = null;
  13478. _oldBlending = -1;
  13479. _oldDepthTest = -1;
  13480. _oldDepthWrite = -1;
  13481. _oldDoubleSided = -1;
  13482. _oldFlipSided = -1;
  13483. _currentGeometryGroupHash = -1;
  13484. _currentMaterialId = -1;
  13485. _lightsNeedUpdate = true;
  13486. }
  13487. };
  13488. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13489. var webglObject, object, buffer, material, start, end, delta;
  13490. if ( reverse ) {
  13491. start = renderList.length - 1;
  13492. end = -1;
  13493. delta = -1;
  13494. } else {
  13495. start = 0;
  13496. end = renderList.length;
  13497. delta = 1;
  13498. }
  13499. for ( var i = start; i !== end; i += delta ) {
  13500. webglObject = renderList[ i ];
  13501. if ( webglObject.render ) {
  13502. object = webglObject.object;
  13503. buffer = webglObject.buffer;
  13504. if ( overrideMaterial ) {
  13505. material = overrideMaterial;
  13506. } else {
  13507. material = webglObject[ materialType ];
  13508. if ( ! material ) continue;
  13509. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13510. _this.setDepthTest( material.depthTest );
  13511. _this.setDepthWrite( material.depthWrite );
  13512. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13513. }
  13514. _this.setMaterialFaces( material );
  13515. if ( buffer instanceof THREE.BufferGeometry ) {
  13516. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13517. } else {
  13518. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13519. }
  13520. }
  13521. }
  13522. };
  13523. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13524. var webglObject, object, material, program;
  13525. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13526. webglObject = renderList[ i ];
  13527. object = webglObject.object;
  13528. if ( object.visible ) {
  13529. if ( overrideMaterial ) {
  13530. material = overrideMaterial;
  13531. } else {
  13532. material = webglObject[ materialType ];
  13533. if ( ! material ) continue;
  13534. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13535. _this.setDepthTest( material.depthTest );
  13536. _this.setDepthWrite( material.depthWrite );
  13537. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13538. }
  13539. _this.renderImmediateObject( camera, lights, fog, material, object );
  13540. }
  13541. }
  13542. };
  13543. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13544. var program = setProgram( camera, lights, fog, material, object );
  13545. _currentGeometryGroupHash = -1;
  13546. _this.setMaterialFaces( material );
  13547. if ( object.immediateRenderCallback ) {
  13548. object.immediateRenderCallback( program, _gl, _frustum );
  13549. } else {
  13550. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13551. }
  13552. };
  13553. function unrollImmediateBufferMaterial ( globject ) {
  13554. var object = globject.object,
  13555. material = object.material;
  13556. if ( material.transparent ) {
  13557. globject.transparent = material;
  13558. globject.opaque = null;
  13559. } else {
  13560. globject.opaque = material;
  13561. globject.transparent = null;
  13562. }
  13563. };
  13564. function unrollBufferMaterial ( globject ) {
  13565. var object = globject.object,
  13566. buffer = globject.buffer,
  13567. material, materialIndex, meshMaterial;
  13568. meshMaterial = object.material;
  13569. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13570. materialIndex = buffer.materialIndex;
  13571. material = meshMaterial.materials[ materialIndex ];
  13572. if ( material.transparent ) {
  13573. globject.transparent = material;
  13574. globject.opaque = null;
  13575. } else {
  13576. globject.opaque = material;
  13577. globject.transparent = null;
  13578. }
  13579. } else {
  13580. material = meshMaterial;
  13581. if ( material ) {
  13582. if ( material.transparent ) {
  13583. globject.transparent = material;
  13584. globject.opaque = null;
  13585. } else {
  13586. globject.opaque = material;
  13587. globject.transparent = null;
  13588. }
  13589. }
  13590. }
  13591. };
  13592. // Geometry splitting
  13593. function sortFacesByMaterial ( geometry, material ) {
  13594. var f, fl, face, materialIndex, vertices,
  13595. groupHash, hash_map = {};
  13596. var numMorphTargets = geometry.morphTargets.length;
  13597. var numMorphNormals = geometry.morphNormals.length;
  13598. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13599. geometry.geometryGroups = {};
  13600. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13601. face = geometry.faces[ f ];
  13602. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13603. if ( hash_map[ materialIndex ] === undefined ) {
  13604. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13605. }
  13606. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13607. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13608. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13609. }
  13610. vertices = face instanceof THREE.Face3 ? 3 : 4;
  13611. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13612. hash_map[ materialIndex ].counter += 1;
  13613. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13614. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13615. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13616. }
  13617. }
  13618. if ( face instanceof THREE.Face3 ) {
  13619. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13620. } else {
  13621. geometry.geometryGroups[ groupHash ].faces4.push( f );
  13622. }
  13623. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13624. }
  13625. geometry.geometryGroupsList = [];
  13626. for ( var g in geometry.geometryGroups ) {
  13627. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13628. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13629. }
  13630. };
  13631. // Objects refresh
  13632. this.initWebGLObjects = function ( scene ) {
  13633. if ( !scene.__webglObjects ) {
  13634. scene.__webglObjects = [];
  13635. scene.__webglObjectsImmediate = [];
  13636. scene.__webglSprites = [];
  13637. scene.__webglFlares = [];
  13638. }
  13639. while ( scene.__objectsAdded.length ) {
  13640. addObject( scene.__objectsAdded[ 0 ], scene );
  13641. scene.__objectsAdded.splice( 0, 1 );
  13642. }
  13643. while ( scene.__objectsRemoved.length ) {
  13644. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13645. scene.__objectsRemoved.splice( 0, 1 );
  13646. }
  13647. // update must be called after objects adding / removal
  13648. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13649. var object = scene.__webglObjects[ o ].object;
  13650. // TODO: Remove this hack (WebGLRenderer refactoring)
  13651. if ( object.__webglInit === undefined ) {
  13652. if ( object.__webglActive !== undefined ) {
  13653. removeObject( object, scene );
  13654. }
  13655. addObject( object, scene );
  13656. }
  13657. updateObject( object );
  13658. }
  13659. };
  13660. // Objects adding
  13661. function addObject( object, scene ) {
  13662. var g, geometry, material, geometryGroup;
  13663. if ( object.__webglInit === undefined ) {
  13664. object.__webglInit = true;
  13665. object._modelViewMatrix = new THREE.Matrix4();
  13666. object._normalMatrix = new THREE.Matrix3();
  13667. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13668. object.geometry.__webglInit = true;
  13669. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13670. }
  13671. geometry = object.geometry;
  13672. if ( geometry === undefined ) {
  13673. // fail silently for now
  13674. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13675. initDirectBuffers( geometry );
  13676. } else if ( object instanceof THREE.Mesh ) {
  13677. material = object.material;
  13678. if ( geometry.geometryGroups === undefined ) {
  13679. sortFacesByMaterial( geometry, material );
  13680. }
  13681. // create separate VBOs per geometry chunk
  13682. for ( g in geometry.geometryGroups ) {
  13683. geometryGroup = geometry.geometryGroups[ g ];
  13684. // initialise VBO on the first access
  13685. if ( ! geometryGroup.__webglVertexBuffer ) {
  13686. createMeshBuffers( geometryGroup );
  13687. initMeshBuffers( geometryGroup, object );
  13688. geometry.verticesNeedUpdate = true;
  13689. geometry.morphTargetsNeedUpdate = true;
  13690. geometry.elementsNeedUpdate = true;
  13691. geometry.uvsNeedUpdate = true;
  13692. geometry.normalsNeedUpdate = true;
  13693. geometry.tangentsNeedUpdate = true;
  13694. geometry.colorsNeedUpdate = true;
  13695. }
  13696. }
  13697. } else if ( object instanceof THREE.Ribbon ) {
  13698. if ( ! geometry.__webglVertexBuffer ) {
  13699. createRibbonBuffers( geometry );
  13700. initRibbonBuffers( geometry, object );
  13701. geometry.verticesNeedUpdate = true;
  13702. geometry.colorsNeedUpdate = true;
  13703. geometry.normalsNeedUpdate = true;
  13704. }
  13705. } else if ( object instanceof THREE.Line ) {
  13706. if ( ! geometry.__webglVertexBuffer ) {
  13707. createLineBuffers( geometry );
  13708. initLineBuffers( geometry, object );
  13709. geometry.verticesNeedUpdate = true;
  13710. geometry.colorsNeedUpdate = true;
  13711. geometry.lineDistancesNeedUpdate = true;
  13712. }
  13713. } else if ( object instanceof THREE.ParticleSystem ) {
  13714. if ( ! geometry.__webglVertexBuffer ) {
  13715. createParticleBuffers( geometry );
  13716. initParticleBuffers( geometry, object );
  13717. geometry.verticesNeedUpdate = true;
  13718. geometry.colorsNeedUpdate = true;
  13719. }
  13720. }
  13721. }
  13722. if ( object.__webglActive === undefined ) {
  13723. if ( object instanceof THREE.Mesh ) {
  13724. geometry = object.geometry;
  13725. if ( geometry instanceof THREE.BufferGeometry ) {
  13726. addBuffer( scene.__webglObjects, geometry, object );
  13727. } else if ( geometry instanceof THREE.Geometry ) {
  13728. for ( g in geometry.geometryGroups ) {
  13729. geometryGroup = geometry.geometryGroups[ g ];
  13730. addBuffer( scene.__webglObjects, geometryGroup, object );
  13731. }
  13732. }
  13733. } else if ( object instanceof THREE.Ribbon ||
  13734. object instanceof THREE.Line ||
  13735. object instanceof THREE.ParticleSystem ) {
  13736. geometry = object.geometry;
  13737. addBuffer( scene.__webglObjects, geometry, object );
  13738. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13739. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13740. } else if ( object instanceof THREE.Sprite ) {
  13741. scene.__webglSprites.push( object );
  13742. } else if ( object instanceof THREE.LensFlare ) {
  13743. scene.__webglFlares.push( object );
  13744. }
  13745. object.__webglActive = true;
  13746. }
  13747. };
  13748. function addBuffer( objlist, buffer, object ) {
  13749. objlist.push(
  13750. {
  13751. buffer: buffer,
  13752. object: object,
  13753. opaque: null,
  13754. transparent: null
  13755. }
  13756. );
  13757. };
  13758. function addBufferImmediate( objlist, object ) {
  13759. objlist.push(
  13760. {
  13761. object: object,
  13762. opaque: null,
  13763. transparent: null
  13764. }
  13765. );
  13766. };
  13767. // Objects updates
  13768. function updateObject( object ) {
  13769. var geometry = object.geometry,
  13770. geometryGroup, customAttributesDirty, material;
  13771. if ( geometry instanceof THREE.BufferGeometry ) {
  13772. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13773. } else if ( object instanceof THREE.Mesh ) {
  13774. // check all geometry groups
  13775. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13776. geometryGroup = geometry.geometryGroupsList[ i ];
  13777. material = getBufferMaterial( object, geometryGroup );
  13778. if ( geometry.buffersNeedUpdate ) {
  13779. initMeshBuffers( geometryGroup, object );
  13780. }
  13781. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13782. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13783. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13784. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13785. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13786. }
  13787. }
  13788. geometry.verticesNeedUpdate = false;
  13789. geometry.morphTargetsNeedUpdate = false;
  13790. geometry.elementsNeedUpdate = false;
  13791. geometry.uvsNeedUpdate = false;
  13792. geometry.normalsNeedUpdate = false;
  13793. geometry.colorsNeedUpdate = false;
  13794. geometry.tangentsNeedUpdate = false;
  13795. geometry.buffersNeedUpdate = false;
  13796. material.attributes && clearCustomAttributes( material );
  13797. } else if ( object instanceof THREE.Ribbon ) {
  13798. material = getBufferMaterial( object, geometry );
  13799. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13800. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13801. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13802. }
  13803. geometry.verticesNeedUpdate = false;
  13804. geometry.colorsNeedUpdate = false;
  13805. geometry.normalsNeedUpdate = false;
  13806. material.attributes && clearCustomAttributes( material );
  13807. } else if ( object instanceof THREE.Line ) {
  13808. material = getBufferMaterial( object, geometry );
  13809. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13810. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13811. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13812. }
  13813. geometry.verticesNeedUpdate = false;
  13814. geometry.colorsNeedUpdate = false;
  13815. geometry.lineDistancesNeedUpdate = false;
  13816. material.attributes && clearCustomAttributes( material );
  13817. } else if ( object instanceof THREE.ParticleSystem ) {
  13818. material = getBufferMaterial( object, geometry );
  13819. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13820. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13821. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13822. }
  13823. geometry.verticesNeedUpdate = false;
  13824. geometry.colorsNeedUpdate = false;
  13825. material.attributes && clearCustomAttributes( material );
  13826. }
  13827. };
  13828. // Objects updates - custom attributes check
  13829. function areCustomAttributesDirty( material ) {
  13830. for ( var a in material.attributes ) {
  13831. if ( material.attributes[ a ].needsUpdate ) return true;
  13832. }
  13833. return false;
  13834. };
  13835. function clearCustomAttributes( material ) {
  13836. for ( var a in material.attributes ) {
  13837. material.attributes[ a ].needsUpdate = false;
  13838. }
  13839. };
  13840. // Objects removal
  13841. function removeObject( object, scene ) {
  13842. if ( object instanceof THREE.Mesh ||
  13843. object instanceof THREE.ParticleSystem ||
  13844. object instanceof THREE.Ribbon ||
  13845. object instanceof THREE.Line ) {
  13846. removeInstances( scene.__webglObjects, object );
  13847. } else if ( object instanceof THREE.Sprite ) {
  13848. removeInstancesDirect( scene.__webglSprites, object );
  13849. } else if ( object instanceof THREE.LensFlare ) {
  13850. removeInstancesDirect( scene.__webglFlares, object );
  13851. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13852. removeInstances( scene.__webglObjectsImmediate, object );
  13853. }
  13854. delete object.__webglActive;
  13855. };
  13856. function removeInstances( objlist, object ) {
  13857. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13858. if ( objlist[ o ].object === object ) {
  13859. objlist.splice( o, 1 );
  13860. }
  13861. }
  13862. };
  13863. function removeInstancesDirect( objlist, object ) {
  13864. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13865. if ( objlist[ o ] === object ) {
  13866. objlist.splice( o, 1 );
  13867. }
  13868. }
  13869. };
  13870. // Materials
  13871. this.initMaterial = function ( material, lights, fog, object ) {
  13872. material.addEventListener( 'dispose', onMaterialDispose );
  13873. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13874. if ( material instanceof THREE.MeshDepthMaterial ) {
  13875. shaderID = 'depth';
  13876. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13877. shaderID = 'normal';
  13878. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13879. shaderID = 'basic';
  13880. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13881. shaderID = 'lambert';
  13882. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13883. shaderID = 'phong';
  13884. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13885. shaderID = 'basic';
  13886. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13887. shaderID = 'dashed';
  13888. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13889. shaderID = 'particle_basic';
  13890. }
  13891. if ( shaderID ) {
  13892. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13893. }
  13894. // heuristics to create shader parameters according to lights in the scene
  13895. // (not to blow over maxLights budget)
  13896. maxLightCount = allocateLights( lights );
  13897. maxShadows = allocateShadows( lights );
  13898. maxBones = allocateBones( object );
  13899. parameters = {
  13900. map: !!material.map,
  13901. envMap: !!material.envMap,
  13902. lightMap: !!material.lightMap,
  13903. bumpMap: !!material.bumpMap,
  13904. normalMap: !!material.normalMap,
  13905. specularMap: !!material.specularMap,
  13906. vertexColors: material.vertexColors,
  13907. fog: fog,
  13908. useFog: material.fog,
  13909. fogExp: fog instanceof THREE.FogExp2,
  13910. sizeAttenuation: material.sizeAttenuation,
  13911. skinning: material.skinning,
  13912. maxBones: maxBones,
  13913. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13914. boneTextureWidth: object && object.boneTextureWidth,
  13915. boneTextureHeight: object && object.boneTextureHeight,
  13916. morphTargets: material.morphTargets,
  13917. morphNormals: material.morphNormals,
  13918. maxMorphTargets: this.maxMorphTargets,
  13919. maxMorphNormals: this.maxMorphNormals,
  13920. maxDirLights: maxLightCount.directional,
  13921. maxPointLights: maxLightCount.point,
  13922. maxSpotLights: maxLightCount.spot,
  13923. maxHemiLights: maxLightCount.hemi,
  13924. maxShadows: maxShadows,
  13925. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13926. shadowMapType: this.shadowMapType,
  13927. shadowMapDebug: this.shadowMapDebug,
  13928. shadowMapCascade: this.shadowMapCascade,
  13929. alphaTest: material.alphaTest,
  13930. metal: material.metal,
  13931. perPixel: material.perPixel,
  13932. wrapAround: material.wrapAround,
  13933. doubleSided: material.side === THREE.DoubleSide,
  13934. flipSided: material.side === THREE.BackSide
  13935. };
  13936. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13937. var attributes = material.program.attributes;
  13938. if ( material.morphTargets ) {
  13939. material.numSupportedMorphTargets = 0;
  13940. var id, base = "morphTarget";
  13941. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13942. id = base + i;
  13943. if ( attributes[ id ] >= 0 ) {
  13944. material.numSupportedMorphTargets ++;
  13945. }
  13946. }
  13947. }
  13948. if ( material.morphNormals ) {
  13949. material.numSupportedMorphNormals = 0;
  13950. var id, base = "morphNormal";
  13951. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13952. id = base + i;
  13953. if ( attributes[ id ] >= 0 ) {
  13954. material.numSupportedMorphNormals ++;
  13955. }
  13956. }
  13957. }
  13958. material.uniformsList = [];
  13959. for ( u in material.uniforms ) {
  13960. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13961. }
  13962. };
  13963. function setMaterialShaders( material, shaders ) {
  13964. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13965. material.vertexShader = shaders.vertexShader;
  13966. material.fragmentShader = shaders.fragmentShader;
  13967. };
  13968. function setProgram( camera, lights, fog, material, object ) {
  13969. _usedTextureUnits = 0;
  13970. if ( material.needsUpdate ) {
  13971. if ( material.program ) deallocateMaterial( material );
  13972. _this.initMaterial( material, lights, fog, object );
  13973. material.needsUpdate = false;
  13974. }
  13975. if ( material.morphTargets ) {
  13976. if ( ! object.__webglMorphTargetInfluences ) {
  13977. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13978. }
  13979. }
  13980. var refreshMaterial = false;
  13981. var program = material.program,
  13982. p_uniforms = program.uniforms,
  13983. m_uniforms = material.uniforms;
  13984. if ( program !== _currentProgram ) {
  13985. _gl.useProgram( program );
  13986. _currentProgram = program;
  13987. refreshMaterial = true;
  13988. }
  13989. if ( material.id !== _currentMaterialId ) {
  13990. _currentMaterialId = material.id;
  13991. refreshMaterial = true;
  13992. }
  13993. if ( refreshMaterial || camera !== _currentCamera ) {
  13994. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13995. if ( camera !== _currentCamera ) _currentCamera = camera;
  13996. }
  13997. // skinning uniforms must be set even if material didn't change
  13998. // auto-setting of texture unit for bone texture must go before other textures
  13999. // not sure why, but otherwise weird things happen
  14000. if ( material.skinning ) {
  14001. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14002. if ( p_uniforms.boneTexture !== null ) {
  14003. var textureUnit = getTextureUnit();
  14004. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14005. _this.setTexture( object.boneTexture, textureUnit );
  14006. }
  14007. } else {
  14008. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14009. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14010. }
  14011. }
  14012. }
  14013. if ( refreshMaterial ) {
  14014. // refresh uniforms common to several materials
  14015. if ( fog && material.fog ) {
  14016. refreshUniformsFog( m_uniforms, fog );
  14017. }
  14018. if ( material instanceof THREE.MeshPhongMaterial ||
  14019. material instanceof THREE.MeshLambertMaterial ||
  14020. material.lights ) {
  14021. if ( _lightsNeedUpdate ) {
  14022. setupLights( program, lights );
  14023. _lightsNeedUpdate = false;
  14024. }
  14025. refreshUniformsLights( m_uniforms, _lights );
  14026. }
  14027. if ( material instanceof THREE.MeshBasicMaterial ||
  14028. material instanceof THREE.MeshLambertMaterial ||
  14029. material instanceof THREE.MeshPhongMaterial ) {
  14030. refreshUniformsCommon( m_uniforms, material );
  14031. }
  14032. // refresh single material specific uniforms
  14033. if ( material instanceof THREE.LineBasicMaterial ) {
  14034. refreshUniformsLine( m_uniforms, material );
  14035. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14036. refreshUniformsLine( m_uniforms, material );
  14037. refreshUniformsDash( m_uniforms, material );
  14038. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14039. refreshUniformsParticle( m_uniforms, material );
  14040. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14041. refreshUniformsPhong( m_uniforms, material );
  14042. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14043. refreshUniformsLambert( m_uniforms, material );
  14044. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14045. m_uniforms.mNear.value = camera.near;
  14046. m_uniforms.mFar.value = camera.far;
  14047. m_uniforms.opacity.value = material.opacity;
  14048. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14049. m_uniforms.opacity.value = material.opacity;
  14050. }
  14051. if ( object.receiveShadow && ! material._shadowPass ) {
  14052. refreshUniformsShadow( m_uniforms, lights );
  14053. }
  14054. // load common uniforms
  14055. loadUniformsGeneric( program, material.uniformsList );
  14056. // load material specific uniforms
  14057. // (shader material also gets them for the sake of genericity)
  14058. if ( material instanceof THREE.ShaderMaterial ||
  14059. material instanceof THREE.MeshPhongMaterial ||
  14060. material.envMap ) {
  14061. if ( p_uniforms.cameraPosition !== null ) {
  14062. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14063. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14064. }
  14065. }
  14066. if ( material instanceof THREE.MeshPhongMaterial ||
  14067. material instanceof THREE.MeshLambertMaterial ||
  14068. material instanceof THREE.ShaderMaterial ||
  14069. material.skinning ) {
  14070. if ( p_uniforms.viewMatrix !== null ) {
  14071. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14072. }
  14073. }
  14074. }
  14075. loadUniformsMatrices( p_uniforms, object );
  14076. if ( p_uniforms.modelMatrix !== null ) {
  14077. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14078. }
  14079. return program;
  14080. };
  14081. // Uniforms (refresh uniforms objects)
  14082. function refreshUniformsCommon ( uniforms, material ) {
  14083. uniforms.opacity.value = material.opacity;
  14084. if ( _this.gammaInput ) {
  14085. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14086. } else {
  14087. uniforms.diffuse.value = material.color;
  14088. }
  14089. uniforms.map.value = material.map;
  14090. uniforms.lightMap.value = material.lightMap;
  14091. uniforms.specularMap.value = material.specularMap;
  14092. if ( material.bumpMap ) {
  14093. uniforms.bumpMap.value = material.bumpMap;
  14094. uniforms.bumpScale.value = material.bumpScale;
  14095. }
  14096. if ( material.normalMap ) {
  14097. uniforms.normalMap.value = material.normalMap;
  14098. uniforms.normalScale.value.copy( material.normalScale );
  14099. }
  14100. // uv repeat and offset setting priorities
  14101. // 1. color map
  14102. // 2. specular map
  14103. // 3. normal map
  14104. // 4. bump map
  14105. var uvScaleMap;
  14106. if ( material.map ) {
  14107. uvScaleMap = material.map;
  14108. } else if ( material.specularMap ) {
  14109. uvScaleMap = material.specularMap;
  14110. } else if ( material.normalMap ) {
  14111. uvScaleMap = material.normalMap;
  14112. } else if ( material.bumpMap ) {
  14113. uvScaleMap = material.bumpMap;
  14114. }
  14115. if ( uvScaleMap !== undefined ) {
  14116. var offset = uvScaleMap.offset;
  14117. var repeat = uvScaleMap.repeat;
  14118. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14119. }
  14120. uniforms.envMap.value = material.envMap;
  14121. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14122. if ( _this.gammaInput ) {
  14123. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14124. uniforms.reflectivity.value = material.reflectivity;
  14125. } else {
  14126. uniforms.reflectivity.value = material.reflectivity;
  14127. }
  14128. uniforms.refractionRatio.value = material.refractionRatio;
  14129. uniforms.combine.value = material.combine;
  14130. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14131. };
  14132. function refreshUniformsLine ( uniforms, material ) {
  14133. uniforms.diffuse.value = material.color;
  14134. uniforms.opacity.value = material.opacity;
  14135. };
  14136. function refreshUniformsDash ( uniforms, material ) {
  14137. uniforms.dashSize.value = material.dashSize;
  14138. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14139. uniforms.scale.value = material.scale;
  14140. };
  14141. function refreshUniformsParticle ( uniforms, material ) {
  14142. uniforms.psColor.value = material.color;
  14143. uniforms.opacity.value = material.opacity;
  14144. uniforms.size.value = material.size;
  14145. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14146. uniforms.map.value = material.map;
  14147. };
  14148. function refreshUniformsFog ( uniforms, fog ) {
  14149. uniforms.fogColor.value = fog.color;
  14150. if ( fog instanceof THREE.Fog ) {
  14151. uniforms.fogNear.value = fog.near;
  14152. uniforms.fogFar.value = fog.far;
  14153. } else if ( fog instanceof THREE.FogExp2 ) {
  14154. uniforms.fogDensity.value = fog.density;
  14155. }
  14156. };
  14157. function refreshUniformsPhong ( uniforms, material ) {
  14158. uniforms.shininess.value = material.shininess;
  14159. if ( _this.gammaInput ) {
  14160. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14161. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14162. uniforms.specular.value.copyGammaToLinear( material.specular );
  14163. } else {
  14164. uniforms.ambient.value = material.ambient;
  14165. uniforms.emissive.value = material.emissive;
  14166. uniforms.specular.value = material.specular;
  14167. }
  14168. if ( material.wrapAround ) {
  14169. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14170. }
  14171. };
  14172. function refreshUniformsLambert ( uniforms, material ) {
  14173. if ( _this.gammaInput ) {
  14174. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14175. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14176. } else {
  14177. uniforms.ambient.value = material.ambient;
  14178. uniforms.emissive.value = material.emissive;
  14179. }
  14180. if ( material.wrapAround ) {
  14181. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14182. }
  14183. };
  14184. function refreshUniformsLights ( uniforms, lights ) {
  14185. uniforms.ambientLightColor.value = lights.ambient;
  14186. uniforms.directionalLightColor.value = lights.directional.colors;
  14187. uniforms.directionalLightDirection.value = lights.directional.positions;
  14188. uniforms.pointLightColor.value = lights.point.colors;
  14189. uniforms.pointLightPosition.value = lights.point.positions;
  14190. uniforms.pointLightDistance.value = lights.point.distances;
  14191. uniforms.spotLightColor.value = lights.spot.colors;
  14192. uniforms.spotLightPosition.value = lights.spot.positions;
  14193. uniforms.spotLightDistance.value = lights.spot.distances;
  14194. uniforms.spotLightDirection.value = lights.spot.directions;
  14195. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14196. uniforms.spotLightExponent.value = lights.spot.exponents;
  14197. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14198. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14199. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14200. };
  14201. function refreshUniformsShadow ( uniforms, lights ) {
  14202. if ( uniforms.shadowMatrix ) {
  14203. var j = 0;
  14204. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14205. var light = lights[ i ];
  14206. if ( ! light.castShadow ) continue;
  14207. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14208. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14209. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14210. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14211. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14212. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14213. j ++;
  14214. }
  14215. }
  14216. }
  14217. };
  14218. // Uniforms (load to GPU)
  14219. function loadUniformsMatrices ( uniforms, object ) {
  14220. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14221. if ( uniforms.normalMatrix ) {
  14222. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14223. }
  14224. };
  14225. function getTextureUnit() {
  14226. var textureUnit = _usedTextureUnits;
  14227. if ( textureUnit >= _maxTextures ) {
  14228. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14229. }
  14230. _usedTextureUnits += 1;
  14231. return textureUnit;
  14232. };
  14233. function loadUniformsGeneric ( program, uniforms ) {
  14234. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14235. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14236. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14237. if ( !location ) continue;
  14238. uniform = uniforms[ j ][ 0 ];
  14239. type = uniform.type;
  14240. value = uniform.value;
  14241. if ( type === "i" ) { // single integer
  14242. _gl.uniform1i( location, value );
  14243. } else if ( type === "f" ) { // single float
  14244. _gl.uniform1f( location, value );
  14245. } else if ( type === "v2" ) { // single THREE.Vector2
  14246. _gl.uniform2f( location, value.x, value.y );
  14247. } else if ( type === "v3" ) { // single THREE.Vector3
  14248. _gl.uniform3f( location, value.x, value.y, value.z );
  14249. } else if ( type === "v4" ) { // single THREE.Vector4
  14250. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14251. } else if ( type === "c" ) { // single THREE.Color
  14252. _gl.uniform3f( location, value.r, value.g, value.b );
  14253. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14254. _gl.uniform1iv( location, value );
  14255. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14256. _gl.uniform3iv( location, value );
  14257. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14258. _gl.uniform1fv( location, value );
  14259. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14260. _gl.uniform3fv( location, value );
  14261. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14262. if ( uniform._array === undefined ) {
  14263. uniform._array = new Float32Array( 2 * value.length );
  14264. }
  14265. for ( i = 0, il = value.length; i < il; i ++ ) {
  14266. offset = i * 2;
  14267. uniform._array[ offset ] = value[ i ].x;
  14268. uniform._array[ offset + 1 ] = value[ i ].y;
  14269. }
  14270. _gl.uniform2fv( location, uniform._array );
  14271. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14272. if ( uniform._array === undefined ) {
  14273. uniform._array = new Float32Array( 3 * value.length );
  14274. }
  14275. for ( i = 0, il = value.length; i < il; i ++ ) {
  14276. offset = i * 3;
  14277. uniform._array[ offset ] = value[ i ].x;
  14278. uniform._array[ offset + 1 ] = value[ i ].y;
  14279. uniform._array[ offset + 2 ] = value[ i ].z;
  14280. }
  14281. _gl.uniform3fv( location, uniform._array );
  14282. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14283. if ( uniform._array === undefined ) {
  14284. uniform._array = new Float32Array( 4 * value.length );
  14285. }
  14286. for ( i = 0, il = value.length; i < il; i ++ ) {
  14287. offset = i * 4;
  14288. uniform._array[ offset ] = value[ i ].x;
  14289. uniform._array[ offset + 1 ] = value[ i ].y;
  14290. uniform._array[ offset + 2 ] = value[ i ].z;
  14291. uniform._array[ offset + 3 ] = value[ i ].w;
  14292. }
  14293. _gl.uniform4fv( location, uniform._array );
  14294. } else if ( type === "m4") { // single THREE.Matrix4
  14295. if ( uniform._array === undefined ) {
  14296. uniform._array = new Float32Array( 16 );
  14297. }
  14298. value.flattenToArray( uniform._array );
  14299. _gl.uniformMatrix4fv( location, false, uniform._array );
  14300. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14301. if ( uniform._array === undefined ) {
  14302. uniform._array = new Float32Array( 16 * value.length );
  14303. }
  14304. for ( i = 0, il = value.length; i < il; i ++ ) {
  14305. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14306. }
  14307. _gl.uniformMatrix4fv( location, false, uniform._array );
  14308. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14309. texture = value;
  14310. textureUnit = getTextureUnit();
  14311. _gl.uniform1i( location, textureUnit );
  14312. if ( !texture ) continue;
  14313. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14314. setCubeTexture( texture, textureUnit );
  14315. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14316. setCubeTextureDynamic( texture, textureUnit );
  14317. } else {
  14318. _this.setTexture( texture, textureUnit );
  14319. }
  14320. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14321. if ( uniform._array === undefined ) {
  14322. uniform._array = [];
  14323. }
  14324. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14325. uniform._array[ i ] = getTextureUnit();
  14326. }
  14327. _gl.uniform1iv( location, uniform._array );
  14328. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14329. texture = uniform.value[ i ];
  14330. textureUnit = uniform._array[ i ];
  14331. if ( !texture ) continue;
  14332. _this.setTexture( texture, textureUnit );
  14333. }
  14334. }
  14335. }
  14336. };
  14337. function setupMatrices ( object, camera ) {
  14338. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14339. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14340. };
  14341. //
  14342. function setColorGamma( array, offset, color, intensitySq ) {
  14343. array[ offset ] = color.r * color.r * intensitySq;
  14344. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14345. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14346. };
  14347. function setColorLinear( array, offset, color, intensity ) {
  14348. array[ offset ] = color.r * intensity;
  14349. array[ offset + 1 ] = color.g * intensity;
  14350. array[ offset + 2 ] = color.b * intensity;
  14351. };
  14352. function setupLights ( program, lights ) {
  14353. var l, ll, light, n,
  14354. r = 0, g = 0, b = 0,
  14355. color, skyColor, groundColor,
  14356. intensity, intensitySq,
  14357. position,
  14358. distance,
  14359. zlights = _lights,
  14360. dirColors = zlights.directional.colors,
  14361. dirPositions = zlights.directional.positions,
  14362. pointColors = zlights.point.colors,
  14363. pointPositions = zlights.point.positions,
  14364. pointDistances = zlights.point.distances,
  14365. spotColors = zlights.spot.colors,
  14366. spotPositions = zlights.spot.positions,
  14367. spotDistances = zlights.spot.distances,
  14368. spotDirections = zlights.spot.directions,
  14369. spotAnglesCos = zlights.spot.anglesCos,
  14370. spotExponents = zlights.spot.exponents,
  14371. hemiSkyColors = zlights.hemi.skyColors,
  14372. hemiGroundColors = zlights.hemi.groundColors,
  14373. hemiPositions = zlights.hemi.positions,
  14374. dirLength = 0,
  14375. pointLength = 0,
  14376. spotLength = 0,
  14377. hemiLength = 0,
  14378. dirCount = 0,
  14379. pointCount = 0,
  14380. spotCount = 0,
  14381. hemiCount = 0,
  14382. dirOffset = 0,
  14383. pointOffset = 0,
  14384. spotOffset = 0,
  14385. hemiOffset = 0;
  14386. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14387. light = lights[ l ];
  14388. if ( light.onlyShadow ) continue;
  14389. color = light.color;
  14390. intensity = light.intensity;
  14391. distance = light.distance;
  14392. if ( light instanceof THREE.AmbientLight ) {
  14393. if ( ! light.visible ) continue;
  14394. if ( _this.gammaInput ) {
  14395. r += color.r * color.r;
  14396. g += color.g * color.g;
  14397. b += color.b * color.b;
  14398. } else {
  14399. r += color.r;
  14400. g += color.g;
  14401. b += color.b;
  14402. }
  14403. } else if ( light instanceof THREE.DirectionalLight ) {
  14404. dirCount += 1;
  14405. if ( ! light.visible ) continue;
  14406. _direction.getPositionFromMatrix( light.matrixWorld );
  14407. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14408. _direction.sub( _vector3 );
  14409. _direction.normalize();
  14410. // skip lights with undefined direction
  14411. // these create troubles in OpenGL (making pixel black)
  14412. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14413. dirOffset = dirLength * 3;
  14414. dirPositions[ dirOffset ] = _direction.x;
  14415. dirPositions[ dirOffset + 1 ] = _direction.y;
  14416. dirPositions[ dirOffset + 2 ] = _direction.z;
  14417. if ( _this.gammaInput ) {
  14418. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14419. } else {
  14420. setColorLinear( dirColors, dirOffset, color, intensity );
  14421. }
  14422. dirLength += 1;
  14423. } else if ( light instanceof THREE.PointLight ) {
  14424. pointCount += 1;
  14425. if ( ! light.visible ) continue;
  14426. pointOffset = pointLength * 3;
  14427. if ( _this.gammaInput ) {
  14428. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14429. } else {
  14430. setColorLinear( pointColors, pointOffset, color, intensity );
  14431. }
  14432. _vector3.getPositionFromMatrix( light.matrixWorld );
  14433. pointPositions[ pointOffset ] = _vector3.x;
  14434. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14435. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14436. pointDistances[ pointLength ] = distance;
  14437. pointLength += 1;
  14438. } else if ( light instanceof THREE.SpotLight ) {
  14439. spotCount += 1;
  14440. if ( ! light.visible ) continue;
  14441. spotOffset = spotLength * 3;
  14442. if ( _this.gammaInput ) {
  14443. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14444. } else {
  14445. setColorLinear( spotColors, spotOffset, color, intensity );
  14446. }
  14447. _vector3.getPositionFromMatrix( light.matrixWorld );
  14448. spotPositions[ spotOffset ] = _vector3.x;
  14449. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14450. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14451. spotDistances[ spotLength ] = distance;
  14452. _direction.copy( _vector3 );
  14453. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14454. _direction.sub( _vector3 );
  14455. _direction.normalize();
  14456. spotDirections[ spotOffset ] = _direction.x;
  14457. spotDirections[ spotOffset + 1 ] = _direction.y;
  14458. spotDirections[ spotOffset + 2 ] = _direction.z;
  14459. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14460. spotExponents[ spotLength ] = light.exponent;
  14461. spotLength += 1;
  14462. } else if ( light instanceof THREE.HemisphereLight ) {
  14463. hemiCount += 1;
  14464. if ( ! light.visible ) continue;
  14465. _direction.getPositionFromMatrix( light.matrixWorld );
  14466. _direction.normalize();
  14467. // skip lights with undefined direction
  14468. // these create troubles in OpenGL (making pixel black)
  14469. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14470. hemiOffset = hemiLength * 3;
  14471. hemiPositions[ hemiOffset ] = _direction.x;
  14472. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14473. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14474. skyColor = light.color;
  14475. groundColor = light.groundColor;
  14476. if ( _this.gammaInput ) {
  14477. intensitySq = intensity * intensity;
  14478. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14479. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14480. } else {
  14481. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14482. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14483. }
  14484. hemiLength += 1;
  14485. }
  14486. }
  14487. // null eventual remains from removed lights
  14488. // (this is to avoid if in shader)
  14489. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14490. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14491. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14492. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14493. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14494. zlights.directional.length = dirLength;
  14495. zlights.point.length = pointLength;
  14496. zlights.spot.length = spotLength;
  14497. zlights.hemi.length = hemiLength;
  14498. zlights.ambient[ 0 ] = r;
  14499. zlights.ambient[ 1 ] = g;
  14500. zlights.ambient[ 2 ] = b;
  14501. };
  14502. // GL state setting
  14503. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14504. if ( cullFace === THREE.CullFaceNone ) {
  14505. _gl.disable( _gl.CULL_FACE );
  14506. } else {
  14507. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14508. _gl.frontFace( _gl.CW );
  14509. } else {
  14510. _gl.frontFace( _gl.CCW );
  14511. }
  14512. if ( cullFace === THREE.CullFaceBack ) {
  14513. _gl.cullFace( _gl.BACK );
  14514. } else if ( cullFace === THREE.CullFaceFront ) {
  14515. _gl.cullFace( _gl.FRONT );
  14516. } else {
  14517. _gl.cullFace( _gl.FRONT_AND_BACK );
  14518. }
  14519. _gl.enable( _gl.CULL_FACE );
  14520. }
  14521. };
  14522. this.setMaterialFaces = function ( material ) {
  14523. var doubleSided = material.side === THREE.DoubleSide;
  14524. var flipSided = material.side === THREE.BackSide;
  14525. if ( _oldDoubleSided !== doubleSided ) {
  14526. if ( doubleSided ) {
  14527. _gl.disable( _gl.CULL_FACE );
  14528. } else {
  14529. _gl.enable( _gl.CULL_FACE );
  14530. }
  14531. _oldDoubleSided = doubleSided;
  14532. }
  14533. if ( _oldFlipSided !== flipSided ) {
  14534. if ( flipSided ) {
  14535. _gl.frontFace( _gl.CW );
  14536. } else {
  14537. _gl.frontFace( _gl.CCW );
  14538. }
  14539. _oldFlipSided = flipSided;
  14540. }
  14541. };
  14542. this.setDepthTest = function ( depthTest ) {
  14543. if ( _oldDepthTest !== depthTest ) {
  14544. if ( depthTest ) {
  14545. _gl.enable( _gl.DEPTH_TEST );
  14546. } else {
  14547. _gl.disable( _gl.DEPTH_TEST );
  14548. }
  14549. _oldDepthTest = depthTest;
  14550. }
  14551. };
  14552. this.setDepthWrite = function ( depthWrite ) {
  14553. if ( _oldDepthWrite !== depthWrite ) {
  14554. _gl.depthMask( depthWrite );
  14555. _oldDepthWrite = depthWrite;
  14556. }
  14557. };
  14558. function setLineWidth ( width ) {
  14559. if ( width !== _oldLineWidth ) {
  14560. _gl.lineWidth( width );
  14561. _oldLineWidth = width;
  14562. }
  14563. };
  14564. function setPolygonOffset ( polygonoffset, factor, units ) {
  14565. if ( _oldPolygonOffset !== polygonoffset ) {
  14566. if ( polygonoffset ) {
  14567. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14568. } else {
  14569. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14570. }
  14571. _oldPolygonOffset = polygonoffset;
  14572. }
  14573. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14574. _gl.polygonOffset( factor, units );
  14575. _oldPolygonOffsetFactor = factor;
  14576. _oldPolygonOffsetUnits = units;
  14577. }
  14578. };
  14579. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14580. if ( blending !== _oldBlending ) {
  14581. if ( blending === THREE.NoBlending ) {
  14582. _gl.disable( _gl.BLEND );
  14583. } else if ( blending === THREE.AdditiveBlending ) {
  14584. _gl.enable( _gl.BLEND );
  14585. _gl.blendEquation( _gl.FUNC_ADD );
  14586. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14587. } else if ( blending === THREE.SubtractiveBlending ) {
  14588. // TODO: Find blendFuncSeparate() combination
  14589. _gl.enable( _gl.BLEND );
  14590. _gl.blendEquation( _gl.FUNC_ADD );
  14591. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14592. } else if ( blending === THREE.MultiplyBlending ) {
  14593. // TODO: Find blendFuncSeparate() combination
  14594. _gl.enable( _gl.BLEND );
  14595. _gl.blendEquation( _gl.FUNC_ADD );
  14596. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14597. } else if ( blending === THREE.CustomBlending ) {
  14598. _gl.enable( _gl.BLEND );
  14599. } else {
  14600. _gl.enable( _gl.BLEND );
  14601. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14602. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14603. }
  14604. _oldBlending = blending;
  14605. }
  14606. if ( blending === THREE.CustomBlending ) {
  14607. if ( blendEquation !== _oldBlendEquation ) {
  14608. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14609. _oldBlendEquation = blendEquation;
  14610. }
  14611. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14612. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14613. _oldBlendSrc = blendSrc;
  14614. _oldBlendDst = blendDst;
  14615. }
  14616. } else {
  14617. _oldBlendEquation = null;
  14618. _oldBlendSrc = null;
  14619. _oldBlendDst = null;
  14620. }
  14621. };
  14622. // Defines
  14623. function generateDefines ( defines ) {
  14624. var value, chunk, chunks = [];
  14625. for ( var d in defines ) {
  14626. value = defines[ d ];
  14627. if ( value === false ) continue;
  14628. chunk = "#define " + d + " " + value;
  14629. chunks.push( chunk );
  14630. }
  14631. return chunks.join( "\n" );
  14632. };
  14633. // Shaders
  14634. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  14635. var p, pl, d, program, code;
  14636. var chunks = [];
  14637. // Generate code
  14638. if ( shaderID ) {
  14639. chunks.push( shaderID );
  14640. } else {
  14641. chunks.push( fragmentShader );
  14642. chunks.push( vertexShader );
  14643. }
  14644. for ( d in defines ) {
  14645. chunks.push( d );
  14646. chunks.push( defines[ d ] );
  14647. }
  14648. for ( p in parameters ) {
  14649. chunks.push( p );
  14650. chunks.push( parameters[ p ] );
  14651. }
  14652. code = chunks.join();
  14653. // Check if code has been already compiled
  14654. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14655. var programInfo = _programs[ p ];
  14656. if ( programInfo.code === code ) {
  14657. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14658. programInfo.usedTimes ++;
  14659. return programInfo.program;
  14660. }
  14661. }
  14662. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14663. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14664. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14665. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14666. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14667. }
  14668. // console.log( "building new program " );
  14669. //
  14670. var customDefines = generateDefines( defines );
  14671. //
  14672. program = _gl.createProgram();
  14673. var prefix_vertex = [
  14674. "precision " + _precision + " float;",
  14675. customDefines,
  14676. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14677. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14678. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14679. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14680. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14681. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14682. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14683. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14684. "#define MAX_SHADOWS " + parameters.maxShadows,
  14685. "#define MAX_BONES " + parameters.maxBones,
  14686. parameters.map ? "#define USE_MAP" : "",
  14687. parameters.envMap ? "#define USE_ENVMAP" : "",
  14688. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14689. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14690. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14691. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14692. parameters.vertexColors ? "#define USE_COLOR" : "",
  14693. parameters.skinning ? "#define USE_SKINNING" : "",
  14694. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14695. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  14696. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  14697. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14698. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14699. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14700. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14701. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14702. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14703. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14704. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14705. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14706. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14707. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14708. "uniform mat4 modelMatrix;",
  14709. "uniform mat4 modelViewMatrix;",
  14710. "uniform mat4 projectionMatrix;",
  14711. "uniform mat4 viewMatrix;",
  14712. "uniform mat3 normalMatrix;",
  14713. "uniform vec3 cameraPosition;",
  14714. "attribute vec3 position;",
  14715. "attribute vec3 normal;",
  14716. "attribute vec2 uv;",
  14717. "attribute vec2 uv2;",
  14718. "#ifdef USE_COLOR",
  14719. "attribute vec3 color;",
  14720. "#endif",
  14721. "#ifdef USE_MORPHTARGETS",
  14722. "attribute vec3 morphTarget0;",
  14723. "attribute vec3 morphTarget1;",
  14724. "attribute vec3 morphTarget2;",
  14725. "attribute vec3 morphTarget3;",
  14726. "#ifdef USE_MORPHNORMALS",
  14727. "attribute vec3 morphNormal0;",
  14728. "attribute vec3 morphNormal1;",
  14729. "attribute vec3 morphNormal2;",
  14730. "attribute vec3 morphNormal3;",
  14731. "#else",
  14732. "attribute vec3 morphTarget4;",
  14733. "attribute vec3 morphTarget5;",
  14734. "attribute vec3 morphTarget6;",
  14735. "attribute vec3 morphTarget7;",
  14736. "#endif",
  14737. "#endif",
  14738. "#ifdef USE_SKINNING",
  14739. "attribute vec4 skinIndex;",
  14740. "attribute vec4 skinWeight;",
  14741. "#endif",
  14742. ""
  14743. ].join("\n");
  14744. var prefix_fragment = [
  14745. "precision " + _precision + " float;",
  14746. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14747. customDefines,
  14748. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14749. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14750. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14751. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14752. "#define MAX_SHADOWS " + parameters.maxShadows,
  14753. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14754. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14755. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14756. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14757. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14758. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14759. parameters.map ? "#define USE_MAP" : "",
  14760. parameters.envMap ? "#define USE_ENVMAP" : "",
  14761. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14762. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14763. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14764. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14765. parameters.vertexColors ? "#define USE_COLOR" : "",
  14766. parameters.metal ? "#define METAL" : "",
  14767. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14768. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14769. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14770. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14771. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14772. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14773. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14774. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14775. "uniform mat4 viewMatrix;",
  14776. "uniform vec3 cameraPosition;",
  14777. ""
  14778. ].join("\n");
  14779. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14780. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14781. _gl.attachShader( program, glVertexShader );
  14782. _gl.attachShader( program, glFragmentShader );
  14783. _gl.linkProgram( program );
  14784. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14785. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14786. }
  14787. // clean up
  14788. _gl.deleteShader( glFragmentShader );
  14789. _gl.deleteShader( glVertexShader );
  14790. // console.log( prefix_fragment + fragmentShader );
  14791. // console.log( prefix_vertex + vertexShader );
  14792. program.uniforms = {};
  14793. program.attributes = {};
  14794. var identifiers, u, a, i;
  14795. // cache uniform locations
  14796. identifiers = [
  14797. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14798. 'morphTargetInfluences'
  14799. ];
  14800. if ( parameters.useVertexTexture ) {
  14801. identifiers.push( 'boneTexture' );
  14802. } else {
  14803. identifiers.push( 'boneGlobalMatrices' );
  14804. }
  14805. for ( u in uniforms ) {
  14806. identifiers.push( u );
  14807. }
  14808. cacheUniformLocations( program, identifiers );
  14809. // cache attributes locations
  14810. identifiers = [
  14811. "position", "normal", "uv", "uv2", "tangent", "color",
  14812. "skinIndex", "skinWeight", "lineDistance"
  14813. ];
  14814. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14815. identifiers.push( "morphTarget" + i );
  14816. }
  14817. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14818. identifiers.push( "morphNormal" + i );
  14819. }
  14820. for ( a in attributes ) {
  14821. identifiers.push( a );
  14822. }
  14823. cacheAttributeLocations( program, identifiers );
  14824. program.id = _programs_counter ++;
  14825. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14826. _this.info.memory.programs = _programs.length;
  14827. return program;
  14828. };
  14829. // Shader parameters cache
  14830. function cacheUniformLocations ( program, identifiers ) {
  14831. var i, l, id;
  14832. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14833. id = identifiers[ i ];
  14834. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14835. }
  14836. };
  14837. function cacheAttributeLocations ( program, identifiers ) {
  14838. var i, l, id;
  14839. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14840. id = identifiers[ i ];
  14841. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14842. }
  14843. };
  14844. function addLineNumbers ( string ) {
  14845. var chunks = string.split( "\n" );
  14846. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14847. // Chrome reports shader errors on lines
  14848. // starting counting from 1
  14849. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14850. }
  14851. return chunks.join( "\n" );
  14852. };
  14853. function getShader ( type, string ) {
  14854. var shader;
  14855. if ( type === "fragment" ) {
  14856. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14857. } else if ( type === "vertex" ) {
  14858. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14859. }
  14860. _gl.shaderSource( shader, string );
  14861. _gl.compileShader( shader );
  14862. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14863. console.error( _gl.getShaderInfoLog( shader ) );
  14864. console.error( addLineNumbers( string ) );
  14865. return null;
  14866. }
  14867. return shader;
  14868. };
  14869. // Textures
  14870. function isPowerOfTwo ( value ) {
  14871. return ( value & ( value - 1 ) ) === 0;
  14872. };
  14873. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14874. if ( isImagePowerOfTwo ) {
  14875. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14876. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14877. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14878. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14879. } else {
  14880. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14881. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14882. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14883. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14884. }
  14885. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14886. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14887. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14888. texture.__oldAnisotropy = texture.anisotropy;
  14889. }
  14890. }
  14891. };
  14892. this.setTexture = function ( texture, slot ) {
  14893. if ( texture.needsUpdate ) {
  14894. if ( ! texture.__webglInit ) {
  14895. texture.__webglInit = true;
  14896. texture.addEventListener( 'dispose', onTextureDispose );
  14897. texture.__webglTexture = _gl.createTexture();
  14898. _this.info.memory.textures ++;
  14899. }
  14900. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14901. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14902. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14903. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14904. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14905. var image = texture.image,
  14906. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14907. glFormat = paramThreeToGL( texture.format ),
  14908. glType = paramThreeToGL( texture.type );
  14909. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14910. var mipmap, mipmaps = texture.mipmaps;
  14911. if ( texture instanceof THREE.DataTexture ) {
  14912. // use manually created mipmaps if available
  14913. // if there are no manual mipmaps
  14914. // set 0 level mipmap and then use GL to generate other mipmap levels
  14915. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14916. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14917. mipmap = mipmaps[ i ];
  14918. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14919. }
  14920. texture.generateMipmaps = false;
  14921. } else {
  14922. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14923. }
  14924. } else if ( texture instanceof THREE.CompressedTexture ) {
  14925. // compressed textures can only use manually created mipmaps
  14926. // WebGL can't generate mipmaps for DDS textures
  14927. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14928. mipmap = mipmaps[ i ];
  14929. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14930. }
  14931. } else { // regular Texture (image, video, canvas)
  14932. // use manually created mipmaps if available
  14933. // if there are no manual mipmaps
  14934. // set 0 level mipmap and then use GL to generate other mipmap levels
  14935. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14936. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14937. mipmap = mipmaps[ i ];
  14938. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14939. }
  14940. texture.generateMipmaps = false;
  14941. } else {
  14942. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14943. }
  14944. }
  14945. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14946. texture.needsUpdate = false;
  14947. if ( texture.onUpdate ) texture.onUpdate();
  14948. } else {
  14949. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14950. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14951. }
  14952. };
  14953. function clampToMaxSize ( image, maxSize ) {
  14954. if ( image.width <= maxSize && image.height <= maxSize ) {
  14955. return image;
  14956. }
  14957. // Warning: Scaling through the canvas will only work with images that use
  14958. // premultiplied alpha.
  14959. var maxDimension = Math.max( image.width, image.height );
  14960. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14961. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14962. var canvas = document.createElement( 'canvas' );
  14963. canvas.width = newWidth;
  14964. canvas.height = newHeight;
  14965. var ctx = canvas.getContext( "2d" );
  14966. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14967. return canvas;
  14968. }
  14969. function setCubeTexture ( texture, slot ) {
  14970. if ( texture.image.length === 6 ) {
  14971. if ( texture.needsUpdate ) {
  14972. if ( ! texture.image.__webglTextureCube ) {
  14973. texture.image.__webglTextureCube = _gl.createTexture();
  14974. _this.info.memory.textures ++;
  14975. }
  14976. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14977. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14978. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14979. var isCompressed = texture instanceof THREE.CompressedTexture;
  14980. var cubeImage = [];
  14981. for ( var i = 0; i < 6; i ++ ) {
  14982. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14983. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14984. } else {
  14985. cubeImage[ i ] = texture.image[ i ];
  14986. }
  14987. }
  14988. var image = cubeImage[ 0 ],
  14989. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14990. glFormat = paramThreeToGL( texture.format ),
  14991. glType = paramThreeToGL( texture.type );
  14992. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14993. for ( var i = 0; i < 6; i ++ ) {
  14994. if ( isCompressed ) {
  14995. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14996. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14997. mipmap = mipmaps[ j ];
  14998. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14999. }
  15000. } else {
  15001. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15002. }
  15003. }
  15004. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15005. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15006. }
  15007. texture.needsUpdate = false;
  15008. if ( texture.onUpdate ) texture.onUpdate();
  15009. } else {
  15010. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15011. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15012. }
  15013. }
  15014. };
  15015. function setCubeTextureDynamic ( texture, slot ) {
  15016. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15017. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15018. };
  15019. // Render targets
  15020. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15021. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15022. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15023. };
  15024. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15025. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15026. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15027. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15028. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15029. /* For some reason this is not working. Defaulting to RGBA4.
  15030. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15031. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15032. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15033. */
  15034. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15035. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15036. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15037. } else {
  15038. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15039. }
  15040. };
  15041. this.setRenderTarget = function ( renderTarget ) {
  15042. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15043. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15044. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15045. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15046. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15047. renderTarget.__webglTexture = _gl.createTexture();
  15048. _this.info.memory.textures ++;
  15049. // Setup texture, create render and frame buffers
  15050. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15051. glFormat = paramThreeToGL( renderTarget.format ),
  15052. glType = paramThreeToGL( renderTarget.type );
  15053. if ( isCube ) {
  15054. renderTarget.__webglFramebuffer = [];
  15055. renderTarget.__webglRenderbuffer = [];
  15056. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15057. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15058. for ( var i = 0; i < 6; i ++ ) {
  15059. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15060. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15061. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15062. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15063. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15064. }
  15065. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15066. } else {
  15067. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15068. if ( renderTarget.shareDepthFrom ) {
  15069. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15070. } else {
  15071. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15072. }
  15073. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15074. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15075. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15076. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15077. if ( renderTarget.shareDepthFrom ) {
  15078. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15079. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15080. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15081. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15082. }
  15083. } else {
  15084. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15085. }
  15086. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15087. }
  15088. // Release everything
  15089. if ( isCube ) {
  15090. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15091. } else {
  15092. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15093. }
  15094. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15095. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15096. }
  15097. var framebuffer, width, height, vx, vy;
  15098. if ( renderTarget ) {
  15099. if ( isCube ) {
  15100. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15101. } else {
  15102. framebuffer = renderTarget.__webglFramebuffer;
  15103. }
  15104. width = renderTarget.width;
  15105. height = renderTarget.height;
  15106. vx = 0;
  15107. vy = 0;
  15108. } else {
  15109. framebuffer = null;
  15110. width = _viewportWidth;
  15111. height = _viewportHeight;
  15112. vx = _viewportX;
  15113. vy = _viewportY;
  15114. }
  15115. if ( framebuffer !== _currentFramebuffer ) {
  15116. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15117. _gl.viewport( vx, vy, width, height );
  15118. _currentFramebuffer = framebuffer;
  15119. }
  15120. _currentWidth = width;
  15121. _currentHeight = height;
  15122. };
  15123. function updateRenderTargetMipmap ( renderTarget ) {
  15124. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15125. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15126. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15127. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15128. } else {
  15129. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15130. _gl.generateMipmap( _gl.TEXTURE_2D );
  15131. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15132. }
  15133. };
  15134. // Fallback filters for non-power-of-2 textures
  15135. function filterFallback ( f ) {
  15136. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15137. return _gl.NEAREST;
  15138. }
  15139. return _gl.LINEAR;
  15140. };
  15141. // Map three.js constants to WebGL constants
  15142. function paramThreeToGL ( p ) {
  15143. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15144. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15145. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15146. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15147. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15148. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15149. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15150. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15151. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15152. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15153. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15154. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15155. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15156. if ( p === THREE.ByteType ) return _gl.BYTE;
  15157. if ( p === THREE.ShortType ) return _gl.SHORT;
  15158. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15159. if ( p === THREE.IntType ) return _gl.INT;
  15160. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15161. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15162. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15163. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15164. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15165. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15166. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15167. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15168. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15169. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15170. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15171. if ( p === THREE.OneFactor ) return _gl.ONE;
  15172. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15173. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15174. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15175. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15176. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15177. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15178. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15179. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15180. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15181. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15182. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15183. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15184. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15185. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15186. }
  15187. return 0;
  15188. };
  15189. // Allocations
  15190. function allocateBones ( object ) {
  15191. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15192. return 1024;
  15193. } else {
  15194. // default for when object is not specified
  15195. // ( for example when prebuilding shader
  15196. // to be used with multiple objects )
  15197. //
  15198. // - leave some extra space for other uniforms
  15199. // - limit here is ANGLE's 254 max uniform vectors
  15200. // (up to 54 should be safe)
  15201. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15202. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15203. var maxBones = nVertexMatrices;
  15204. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15205. maxBones = Math.min( object.bones.length, maxBones );
  15206. if ( maxBones < object.bones.length ) {
  15207. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15208. }
  15209. }
  15210. return maxBones;
  15211. }
  15212. };
  15213. function allocateLights ( lights ) {
  15214. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  15215. dirLights = pointLights = spotLights = hemiLights = 0;
  15216. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15217. light = lights[ l ];
  15218. if ( light.onlyShadow ) continue;
  15219. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15220. if ( light instanceof THREE.PointLight ) pointLights ++;
  15221. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15222. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15223. }
  15224. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15225. };
  15226. function allocateShadows ( lights ) {
  15227. var l, ll, light, maxShadows = 0;
  15228. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  15229. light = lights[ l ];
  15230. if ( ! light.castShadow ) continue;
  15231. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15232. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15233. }
  15234. return maxShadows;
  15235. };
  15236. // Initialization
  15237. function initGL () {
  15238. try {
  15239. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15240. throw 'Error creating WebGL context.';
  15241. }
  15242. } catch ( error ) {
  15243. console.error( error );
  15244. }
  15245. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15246. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15247. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  15248. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  15249. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15250. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  15251. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  15252. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15253. if ( ! _glExtensionTextureFloat ) {
  15254. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15255. }
  15256. if ( ! _glExtensionStandardDerivatives ) {
  15257. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15258. }
  15259. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15260. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15261. }
  15262. if ( ! _glExtensionCompressedTextureS3TC ) {
  15263. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15264. }
  15265. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15266. _gl.getShaderPrecisionFormat = function() {
  15267. return {
  15268. "rangeMin" : 1,
  15269. "rangeMax" : 1,
  15270. "precision" : 1
  15271. };
  15272. }
  15273. }
  15274. };
  15275. function setDefaultGLState () {
  15276. _gl.clearColor( 0, 0, 0, 1 );
  15277. _gl.clearDepth( 1 );
  15278. _gl.clearStencil( 0 );
  15279. _gl.enable( _gl.DEPTH_TEST );
  15280. _gl.depthFunc( _gl.LEQUAL );
  15281. _gl.frontFace( _gl.CCW );
  15282. _gl.cullFace( _gl.BACK );
  15283. _gl.enable( _gl.CULL_FACE );
  15284. _gl.enable( _gl.BLEND );
  15285. _gl.blendEquation( _gl.FUNC_ADD );
  15286. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15287. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15288. };
  15289. // default plugins (order is important)
  15290. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15291. this.addPrePlugin( this.shadowMapPlugin );
  15292. this.addPostPlugin( new THREE.SpritePlugin() );
  15293. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15294. };
  15295. /**
  15296. * @author szimek / https://github.com/szimek/
  15297. * @author alteredq / http://alteredqualia.com/
  15298. */
  15299. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15300. this.width = width;
  15301. this.height = height;
  15302. options = options || {};
  15303. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15304. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15305. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15306. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15307. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15308. this.offset = new THREE.Vector2( 0, 0 );
  15309. this.repeat = new THREE.Vector2( 1, 1 );
  15310. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15311. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15312. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15313. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15314. this.generateMipmaps = true;
  15315. this.shareDepthFrom = null;
  15316. };
  15317. THREE.WebGLRenderTarget.prototype = {
  15318. constructor: THREE.WebGLRenderTarget,
  15319. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  15320. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  15321. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  15322. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  15323. clone: function () {
  15324. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15325. tmp.wrapS = this.wrapS;
  15326. tmp.wrapT = this.wrapT;
  15327. tmp.magFilter = this.magFilter;
  15328. tmp.minFilter = this.minFilter;
  15329. tmp.anisotropy = this.anisotropy;
  15330. tmp.offset.copy( this.offset );
  15331. tmp.repeat.copy( this.repeat );
  15332. tmp.format = this.format;
  15333. tmp.type = this.type;
  15334. tmp.depthBuffer = this.depthBuffer;
  15335. tmp.stencilBuffer = this.stencilBuffer;
  15336. tmp.generateMipmaps = this.generateMipmaps;
  15337. tmp.shareDepthFrom = this.shareDepthFrom;
  15338. return tmp;
  15339. },
  15340. dispose: function () {
  15341. this.dispatchEvent( { type: 'dispose' } );
  15342. }
  15343. };
  15344. /**
  15345. * @author alteredq / http://alteredqualia.com
  15346. */
  15347. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15348. THREE.WebGLRenderTarget.call( this, width, height, options );
  15349. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15350. };
  15351. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15352. /**
  15353. * @author mrdoob / http://mrdoob.com/
  15354. */
  15355. THREE.RenderableVertex = function () {
  15356. this.positionWorld = new THREE.Vector3();
  15357. this.positionScreen = new THREE.Vector4();
  15358. this.visible = true;
  15359. };
  15360. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15361. this.positionWorld.copy( vertex.positionWorld );
  15362. this.positionScreen.copy( vertex.positionScreen );
  15363. };
  15364. /**
  15365. * @author mrdoob / http://mrdoob.com/
  15366. */
  15367. THREE.RenderableFace3 = function () {
  15368. this.v1 = new THREE.RenderableVertex();
  15369. this.v2 = new THREE.RenderableVertex();
  15370. this.v3 = new THREE.RenderableVertex();
  15371. this.centroidModel = new THREE.Vector3();
  15372. this.normalModel = new THREE.Vector3();
  15373. this.normalModelView = new THREE.Vector3();
  15374. this.vertexNormalsLength = 0;
  15375. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15376. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15377. this.color = null;
  15378. this.material = null;
  15379. this.uvs = [[]];
  15380. this.z = null;
  15381. };
  15382. /**
  15383. * @author mrdoob / http://mrdoob.com/
  15384. */
  15385. THREE.RenderableFace4 = function () {
  15386. this.v1 = new THREE.RenderableVertex();
  15387. this.v2 = new THREE.RenderableVertex();
  15388. this.v3 = new THREE.RenderableVertex();
  15389. this.v4 = new THREE.RenderableVertex();
  15390. this.centroidModel = new THREE.Vector3();
  15391. this.normalModel = new THREE.Vector3();
  15392. this.normalModelView = new THREE.Vector3();
  15393. this.vertexNormalsLength = 0;
  15394. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15395. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15396. this.color = null;
  15397. this.material = null;
  15398. this.uvs = [[]];
  15399. this.z = null;
  15400. };
  15401. /**
  15402. * @author mrdoob / http://mrdoob.com/
  15403. */
  15404. THREE.RenderableObject = function () {
  15405. this.object = null;
  15406. this.z = null;
  15407. };
  15408. /**
  15409. * @author mrdoob / http://mrdoob.com/
  15410. */
  15411. THREE.RenderableParticle = function () {
  15412. this.object = null;
  15413. this.x = null;
  15414. this.y = null;
  15415. this.z = null;
  15416. this.rotation = null;
  15417. this.scale = new THREE.Vector2();
  15418. this.material = null;
  15419. };
  15420. /**
  15421. * @author mrdoob / http://mrdoob.com/
  15422. */
  15423. THREE.RenderableLine = function () {
  15424. this.z = null;
  15425. this.v1 = new THREE.RenderableVertex();
  15426. this.v2 = new THREE.RenderableVertex();
  15427. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15428. this.material = null;
  15429. };
  15430. /**
  15431. * @author mrdoob / http://mrdoob.com/
  15432. * @author alteredq / http://alteredqualia.com/
  15433. */
  15434. THREE.GeometryUtils = {
  15435. // Merge two geometries or geometry and geometry from object (using object's transform)
  15436. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15437. var matrix, normalMatrix,
  15438. vertexOffset = geometry1.vertices.length,
  15439. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15440. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15441. vertices1 = geometry1.vertices,
  15442. vertices2 = geometry2.vertices,
  15443. faces1 = geometry1.faces,
  15444. faces2 = geometry2.faces,
  15445. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15446. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15447. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15448. if ( object2 instanceof THREE.Mesh ) {
  15449. object2.matrixAutoUpdate && object2.updateMatrix();
  15450. matrix = object2.matrix;
  15451. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15452. }
  15453. // vertices
  15454. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15455. var vertex = vertices2[ i ];
  15456. var vertexCopy = vertex.clone();
  15457. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15458. vertices1.push( vertexCopy );
  15459. }
  15460. // faces
  15461. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15462. var face = faces2[ i ], faceCopy, normal, color,
  15463. faceVertexNormals = face.vertexNormals,
  15464. faceVertexColors = face.vertexColors;
  15465. if ( face instanceof THREE.Face3 ) {
  15466. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15467. } else if ( face instanceof THREE.Face4 ) {
  15468. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15469. }
  15470. faceCopy.normal.copy( face.normal );
  15471. if ( normalMatrix ) {
  15472. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15473. }
  15474. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15475. normal = faceVertexNormals[ j ].clone();
  15476. if ( normalMatrix ) {
  15477. normal.applyMatrix3( normalMatrix ).normalize();
  15478. }
  15479. faceCopy.vertexNormals.push( normal );
  15480. }
  15481. faceCopy.color.copy( face.color );
  15482. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15483. color = faceVertexColors[ j ];
  15484. faceCopy.vertexColors.push( color.clone() );
  15485. }
  15486. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15487. faceCopy.centroid.copy( face.centroid );
  15488. if ( matrix ) {
  15489. faceCopy.centroid.applyMatrix4( matrix );
  15490. }
  15491. faces1.push( faceCopy );
  15492. }
  15493. // uvs
  15494. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15495. var uv = uvs2[ i ], uvCopy = [];
  15496. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15497. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15498. }
  15499. uvs1.push( uvCopy );
  15500. }
  15501. },
  15502. removeMaterials: function ( geometry, materialIndexArray ) {
  15503. var materialIndexMap = {};
  15504. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15505. materialIndexMap[ materialIndexArray[i] ] = true;
  15506. }
  15507. var face, newFaces = [];
  15508. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15509. face = geometry.faces[ i ];
  15510. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15511. }
  15512. geometry.faces = newFaces;
  15513. },
  15514. // Get random point in triangle (via barycentric coordinates)
  15515. // (uniform distribution)
  15516. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15517. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15518. var a, b, c,
  15519. point = new THREE.Vector3(),
  15520. tmp = THREE.GeometryUtils.__v1;
  15521. a = THREE.GeometryUtils.random();
  15522. b = THREE.GeometryUtils.random();
  15523. if ( ( a + b ) > 1 ) {
  15524. a = 1 - a;
  15525. b = 1 - b;
  15526. }
  15527. c = 1 - a - b;
  15528. point.copy( vectorA );
  15529. point.multiplyScalar( a );
  15530. tmp.copy( vectorB );
  15531. tmp.multiplyScalar( b );
  15532. point.add( tmp );
  15533. tmp.copy( vectorC );
  15534. tmp.multiplyScalar( c );
  15535. point.add( tmp );
  15536. return point;
  15537. },
  15538. // Get random point in face (triangle / quad)
  15539. // (uniform distribution)
  15540. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15541. var vA, vB, vC, vD;
  15542. if ( face instanceof THREE.Face3 ) {
  15543. vA = geometry.vertices[ face.a ];
  15544. vB = geometry.vertices[ face.b ];
  15545. vC = geometry.vertices[ face.c ];
  15546. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15547. } else if ( face instanceof THREE.Face4 ) {
  15548. vA = geometry.vertices[ face.a ];
  15549. vB = geometry.vertices[ face.b ];
  15550. vC = geometry.vertices[ face.c ];
  15551. vD = geometry.vertices[ face.d ];
  15552. var area1, area2;
  15553. if ( useCachedAreas ) {
  15554. if ( face._area1 && face._area2 ) {
  15555. area1 = face._area1;
  15556. area2 = face._area2;
  15557. } else {
  15558. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15559. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15560. face._area1 = area1;
  15561. face._area2 = area2;
  15562. }
  15563. } else {
  15564. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15565. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15566. }
  15567. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15568. if ( r < area1 ) {
  15569. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15570. } else {
  15571. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15572. }
  15573. }
  15574. },
  15575. // Get uniformly distributed random points in mesh
  15576. // - create array with cumulative sums of face areas
  15577. // - pick random number from 0 to total area
  15578. // - find corresponding place in area array by binary search
  15579. // - get random point in face
  15580. randomPointsInGeometry: function ( geometry, n ) {
  15581. var face, i,
  15582. faces = geometry.faces,
  15583. vertices = geometry.vertices,
  15584. il = faces.length,
  15585. totalArea = 0,
  15586. cumulativeAreas = [],
  15587. vA, vB, vC, vD;
  15588. // precompute face areas
  15589. for ( i = 0; i < il; i ++ ) {
  15590. face = faces[ i ];
  15591. if ( face instanceof THREE.Face3 ) {
  15592. vA = vertices[ face.a ];
  15593. vB = vertices[ face.b ];
  15594. vC = vertices[ face.c ];
  15595. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15596. } else if ( face instanceof THREE.Face4 ) {
  15597. vA = vertices[ face.a ];
  15598. vB = vertices[ face.b ];
  15599. vC = vertices[ face.c ];
  15600. vD = vertices[ face.d ];
  15601. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15602. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15603. face._area = face._area1 + face._area2;
  15604. }
  15605. totalArea += face._area;
  15606. cumulativeAreas[ i ] = totalArea;
  15607. }
  15608. // binary search cumulative areas array
  15609. function binarySearchIndices( value ) {
  15610. function binarySearch( start, end ) {
  15611. // return closest larger index
  15612. // if exact number is not found
  15613. if ( end < start )
  15614. return start;
  15615. var mid = start + Math.floor( ( end - start ) / 2 );
  15616. if ( cumulativeAreas[ mid ] > value ) {
  15617. return binarySearch( start, mid - 1 );
  15618. } else if ( cumulativeAreas[ mid ] < value ) {
  15619. return binarySearch( mid + 1, end );
  15620. } else {
  15621. return mid;
  15622. }
  15623. }
  15624. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15625. return result;
  15626. }
  15627. // pick random face weighted by face area
  15628. var r, index,
  15629. result = [];
  15630. var stats = {};
  15631. for ( i = 0; i < n; i ++ ) {
  15632. r = THREE.GeometryUtils.random() * totalArea;
  15633. index = binarySearchIndices( r );
  15634. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15635. if ( ! stats[ index ] ) {
  15636. stats[ index ] = 1;
  15637. } else {
  15638. stats[ index ] += 1;
  15639. }
  15640. }
  15641. return result;
  15642. },
  15643. // Get triangle area (half of parallelogram)
  15644. // http://mathworld.wolfram.com/TriangleArea.html
  15645. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15646. var tmp1 = THREE.GeometryUtils.__v1,
  15647. tmp2 = THREE.GeometryUtils.__v2;
  15648. tmp1.subVectors( vectorB, vectorA );
  15649. tmp2.subVectors( vectorC, vectorA );
  15650. tmp1.cross( tmp2 );
  15651. return 0.5 * tmp1.length();
  15652. },
  15653. // Center geometry so that 0,0,0 is in center of bounding box
  15654. center: function ( geometry ) {
  15655. geometry.computeBoundingBox();
  15656. var bb = geometry.boundingBox;
  15657. var offset = new THREE.Vector3();
  15658. offset.addVectors( bb.min, bb.max );
  15659. offset.multiplyScalar( -0.5 );
  15660. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15661. geometry.computeBoundingBox();
  15662. return offset;
  15663. },
  15664. // Normalize UVs to be from <0,1>
  15665. // (for now just the first set of UVs)
  15666. normalizeUVs: function ( geometry ) {
  15667. var uvSet = geometry.faceVertexUvs[ 0 ];
  15668. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15669. var uvs = uvSet[ i ];
  15670. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15671. // texture repeat
  15672. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15673. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15674. }
  15675. }
  15676. },
  15677. triangulateQuads: function ( geometry ) {
  15678. var i, il, j, jl;
  15679. var faces = [];
  15680. var faceUvs = [];
  15681. var faceVertexUvs = [];
  15682. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15683. faceUvs[ i ] = [];
  15684. }
  15685. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15686. faceVertexUvs[ i ] = [];
  15687. }
  15688. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15689. var face = geometry.faces[ i ];
  15690. if ( face instanceof THREE.Face4 ) {
  15691. var a = face.a;
  15692. var b = face.b;
  15693. var c = face.c;
  15694. var d = face.d;
  15695. var triA = new THREE.Face3();
  15696. var triB = new THREE.Face3();
  15697. triA.color.copy( face.color );
  15698. triB.color.copy( face.color );
  15699. triA.materialIndex = face.materialIndex;
  15700. triB.materialIndex = face.materialIndex;
  15701. triA.a = a;
  15702. triA.b = b;
  15703. triA.c = d;
  15704. triB.a = b;
  15705. triB.b = c;
  15706. triB.c = d;
  15707. if ( face.vertexColors.length === 4 ) {
  15708. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  15709. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  15710. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15711. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  15712. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  15713. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15714. }
  15715. faces.push( triA, triB );
  15716. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15717. if ( geometry.faceVertexUvs[ j ].length ) {
  15718. var uvs = geometry.faceVertexUvs[ j ][ i ];
  15719. var uvA = uvs[ 0 ];
  15720. var uvB = uvs[ 1 ];
  15721. var uvC = uvs[ 2 ];
  15722. var uvD = uvs[ 3 ];
  15723. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  15724. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  15725. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15726. }
  15727. }
  15728. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15729. if ( geometry.faceUvs[ j ].length ) {
  15730. var faceUv = geometry.faceUvs[ j ][ i ];
  15731. faceUvs[ j ].push( faceUv, faceUv );
  15732. }
  15733. }
  15734. } else {
  15735. faces.push( face );
  15736. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15737. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15738. }
  15739. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15740. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15741. }
  15742. }
  15743. }
  15744. geometry.faces = faces;
  15745. geometry.faceUvs = faceUvs;
  15746. geometry.faceVertexUvs = faceVertexUvs;
  15747. geometry.computeCentroids();
  15748. geometry.computeFaceNormals();
  15749. geometry.computeVertexNormals();
  15750. if ( geometry.hasTangents ) geometry.computeTangents();
  15751. },
  15752. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15753. var faces = geometry.faces;
  15754. var start = startFace || 0;
  15755. var end = endFace || faces.length - 1;
  15756. for ( var i = start; i <= end; i ++ ) {
  15757. faces[i].materialIndex = index;
  15758. }
  15759. }
  15760. };
  15761. THREE.GeometryUtils.random = THREE.Math.random16;
  15762. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15763. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15764. /**
  15765. * @author alteredq / http://alteredqualia.com/
  15766. * @author mrdoob / http://mrdoob.com/
  15767. */
  15768. THREE.ImageUtils = {
  15769. crossOrigin: 'anonymous',
  15770. loadTexture: function ( url, mapping, onLoad, onError ) {
  15771. var image = new Image();
  15772. var texture = new THREE.Texture( image, mapping );
  15773. var loader = new THREE.ImageLoader();
  15774. loader.addEventListener( 'load', function ( event ) {
  15775. texture.image = event.content;
  15776. texture.needsUpdate = true;
  15777. if ( onLoad ) onLoad( texture );
  15778. } );
  15779. loader.addEventListener( 'error', function ( event ) {
  15780. if ( onError ) onError( event.message );
  15781. } );
  15782. loader.crossOrigin = this.crossOrigin;
  15783. loader.load( url, image );
  15784. texture.sourceFile = url;
  15785. return texture;
  15786. },
  15787. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15788. var texture = new THREE.CompressedTexture();
  15789. texture.mapping = mapping;
  15790. var request = new XMLHttpRequest();
  15791. request.onload = function () {
  15792. var buffer = request.response;
  15793. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15794. texture.format = dds.format;
  15795. texture.mipmaps = dds.mipmaps;
  15796. texture.image.width = dds.width;
  15797. texture.image.height = dds.height;
  15798. // gl.generateMipmap fails for compressed textures
  15799. // mipmaps must be embedded in the DDS file
  15800. // or texture filters must not use mipmapping
  15801. texture.generateMipmaps = false;
  15802. texture.needsUpdate = true;
  15803. if ( onLoad ) onLoad( texture );
  15804. }
  15805. request.onerror = onError;
  15806. request.open( 'GET', url, true );
  15807. request.responseType = "arraybuffer";
  15808. request.send( null );
  15809. return texture;
  15810. },
  15811. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15812. var images = [];
  15813. images.loadCount = 0;
  15814. var texture = new THREE.Texture();
  15815. texture.image = images;
  15816. if ( mapping !== undefined ) texture.mapping = mapping;
  15817. // no flipping needed for cube textures
  15818. texture.flipY = false;
  15819. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15820. var cubeImage = new Image();
  15821. images[ i ] = cubeImage;
  15822. cubeImage.onload = function () {
  15823. images.loadCount += 1;
  15824. if ( images.loadCount === 6 ) {
  15825. texture.needsUpdate = true;
  15826. if ( onLoad ) onLoad( texture );
  15827. }
  15828. };
  15829. cubeImage.onerror = onError;
  15830. cubeImage.crossOrigin = this.crossOrigin;
  15831. cubeImage.src = array[ i ];
  15832. }
  15833. return texture;
  15834. },
  15835. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15836. var images = [];
  15837. images.loadCount = 0;
  15838. var texture = new THREE.CompressedTexture();
  15839. texture.image = images;
  15840. if ( mapping !== undefined ) texture.mapping = mapping;
  15841. // no flipping for cube textures
  15842. // (also flipping doesn't work for compressed textures )
  15843. texture.flipY = false;
  15844. // can't generate mipmaps for compressed textures
  15845. // mips must be embedded in DDS files
  15846. texture.generateMipmaps = false;
  15847. var generateCubeFaceCallback = function ( rq, img ) {
  15848. return function () {
  15849. var buffer = rq.response;
  15850. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15851. img.format = dds.format;
  15852. img.mipmaps = dds.mipmaps;
  15853. img.width = dds.width;
  15854. img.height = dds.height;
  15855. images.loadCount += 1;
  15856. if ( images.loadCount === 6 ) {
  15857. texture.format = dds.format;
  15858. texture.needsUpdate = true;
  15859. if ( onLoad ) onLoad( texture );
  15860. }
  15861. }
  15862. }
  15863. // compressed cubemap textures as 6 separate DDS files
  15864. if ( array instanceof Array ) {
  15865. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15866. var cubeImage = {};
  15867. images[ i ] = cubeImage;
  15868. var request = new XMLHttpRequest();
  15869. request.onload = generateCubeFaceCallback( request, cubeImage );
  15870. request.onerror = onError;
  15871. var url = array[ i ];
  15872. request.open( 'GET', url, true );
  15873. request.responseType = "arraybuffer";
  15874. request.send( null );
  15875. }
  15876. // compressed cubemap texture stored in a single DDS file
  15877. } else {
  15878. var url = array;
  15879. var request = new XMLHttpRequest();
  15880. request.onload = function( ) {
  15881. var buffer = request.response;
  15882. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15883. if ( dds.isCubemap ) {
  15884. var faces = dds.mipmaps.length / dds.mipmapCount;
  15885. for ( var f = 0; f < faces; f ++ ) {
  15886. images[ f ] = { mipmaps : [] };
  15887. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15888. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15889. images[ f ].format = dds.format;
  15890. images[ f ].width = dds.width;
  15891. images[ f ].height = dds.height;
  15892. }
  15893. }
  15894. texture.format = dds.format;
  15895. texture.needsUpdate = true;
  15896. if ( onLoad ) onLoad( texture );
  15897. }
  15898. }
  15899. request.onerror = onError;
  15900. request.open( 'GET', url, true );
  15901. request.responseType = "arraybuffer";
  15902. request.send( null );
  15903. }
  15904. return texture;
  15905. },
  15906. parseDDS: function ( buffer, loadMipmaps ) {
  15907. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15908. // Adapted from @toji's DDS utils
  15909. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15910. // All values and structures referenced from:
  15911. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15912. var DDS_MAGIC = 0x20534444;
  15913. var DDSD_CAPS = 0x1,
  15914. DDSD_HEIGHT = 0x2,
  15915. DDSD_WIDTH = 0x4,
  15916. DDSD_PITCH = 0x8,
  15917. DDSD_PIXELFORMAT = 0x1000,
  15918. DDSD_MIPMAPCOUNT = 0x20000,
  15919. DDSD_LINEARSIZE = 0x80000,
  15920. DDSD_DEPTH = 0x800000;
  15921. var DDSCAPS_COMPLEX = 0x8,
  15922. DDSCAPS_MIPMAP = 0x400000,
  15923. DDSCAPS_TEXTURE = 0x1000;
  15924. var DDSCAPS2_CUBEMAP = 0x200,
  15925. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15926. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15927. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15928. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15929. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15930. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15931. DDSCAPS2_VOLUME = 0x200000;
  15932. var DDPF_ALPHAPIXELS = 0x1,
  15933. DDPF_ALPHA = 0x2,
  15934. DDPF_FOURCC = 0x4,
  15935. DDPF_RGB = 0x40,
  15936. DDPF_YUV = 0x200,
  15937. DDPF_LUMINANCE = 0x20000;
  15938. function fourCCToInt32( value ) {
  15939. return value.charCodeAt(0) +
  15940. (value.charCodeAt(1) << 8) +
  15941. (value.charCodeAt(2) << 16) +
  15942. (value.charCodeAt(3) << 24);
  15943. }
  15944. function int32ToFourCC( value ) {
  15945. return String.fromCharCode(
  15946. value & 0xff,
  15947. (value >> 8) & 0xff,
  15948. (value >> 16) & 0xff,
  15949. (value >> 24) & 0xff
  15950. );
  15951. }
  15952. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15953. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15954. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15955. var headerLengthInt = 31; // The header length in 32 bit ints
  15956. // Offsets into the header array
  15957. var off_magic = 0;
  15958. var off_size = 1;
  15959. var off_flags = 2;
  15960. var off_height = 3;
  15961. var off_width = 4;
  15962. var off_mipmapCount = 7;
  15963. var off_pfFlags = 20;
  15964. var off_pfFourCC = 21;
  15965. var off_caps = 27;
  15966. var off_caps2 = 28;
  15967. var off_caps3 = 29;
  15968. var off_caps4 = 30;
  15969. // Parse header
  15970. var header = new Int32Array( buffer, 0, headerLengthInt );
  15971. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15972. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15973. return dds;
  15974. }
  15975. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15976. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15977. return dds;
  15978. }
  15979. var blockBytes;
  15980. var fourCC = header[ off_pfFourCC ];
  15981. switch ( fourCC ) {
  15982. case FOURCC_DXT1:
  15983. blockBytes = 8;
  15984. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15985. break;
  15986. case FOURCC_DXT3:
  15987. blockBytes = 16;
  15988. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15989. break;
  15990. case FOURCC_DXT5:
  15991. blockBytes = 16;
  15992. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15993. break;
  15994. default:
  15995. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15996. return dds;
  15997. }
  15998. dds.mipmapCount = 1;
  15999. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16000. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16001. }
  16002. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16003. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16004. dds.width = header[ off_width ];
  16005. dds.height = header[ off_height ];
  16006. var dataOffset = header[ off_size ] + 4;
  16007. // Extract mipmaps buffers
  16008. var width = dds.width;
  16009. var height = dds.height;
  16010. var faces = dds.isCubemap ? 6 : 1;
  16011. for ( var face = 0; face < faces; face ++ ) {
  16012. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16013. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16014. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16015. var mipmap = { "data": byteArray, "width": width, "height": height };
  16016. dds.mipmaps.push( mipmap );
  16017. dataOffset += dataLength;
  16018. width = Math.max( width * 0.5, 1 );
  16019. height = Math.max( height * 0.5, 1 );
  16020. }
  16021. width = dds.width;
  16022. height = dds.height;
  16023. }
  16024. return dds;
  16025. },
  16026. getNormalMap: function ( image, depth ) {
  16027. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16028. var cross = function ( a, b ) {
  16029. return [ a[ 1 ] * b[ 2 ] - a[ 2 ] * b[ 1 ], a[ 2 ] * b[ 0 ] - a[ 0 ] * b[ 2 ], a[ 0 ] * b[ 1 ] - a[ 1 ] * b[ 0 ] ];
  16030. }
  16031. var subtract = function ( a, b ) {
  16032. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16033. }
  16034. var normalize = function ( a ) {
  16035. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16036. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16037. }
  16038. depth = depth | 1;
  16039. var width = image.width;
  16040. var height = image.height;
  16041. var canvas = document.createElement( 'canvas' );
  16042. canvas.width = width;
  16043. canvas.height = height;
  16044. var context = canvas.getContext( '2d' );
  16045. context.drawImage( image, 0, 0 );
  16046. var data = context.getImageData( 0, 0, width, height ).data;
  16047. var imageData = context.createImageData( width, height );
  16048. var output = imageData.data;
  16049. for ( var x = 0; x < width; x ++ ) {
  16050. for ( var y = 0; y < height; y ++ ) {
  16051. var ly = y - 1 < 0 ? 0 : y - 1;
  16052. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16053. var lx = x - 1 < 0 ? 0 : x - 1;
  16054. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16055. var points = [];
  16056. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16057. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16058. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16059. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16060. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16061. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16062. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16063. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16064. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16065. var normals = [];
  16066. var num_points = points.length;
  16067. for ( var i = 0; i < num_points; i ++ ) {
  16068. var v1 = points[ i ];
  16069. var v2 = points[ ( i + 1 ) % num_points ];
  16070. v1 = subtract( v1, origin );
  16071. v2 = subtract( v2, origin );
  16072. normals.push( normalize( cross( v1, v2 ) ) );
  16073. }
  16074. var normal = [ 0, 0, 0 ];
  16075. for ( var i = 0; i < normals.length; i ++ ) {
  16076. normal[ 0 ] += normals[ i ][ 0 ];
  16077. normal[ 1 ] += normals[ i ][ 1 ];
  16078. normal[ 2 ] += normals[ i ][ 2 ];
  16079. }
  16080. normal[ 0 ] /= normals.length;
  16081. normal[ 1 ] /= normals.length;
  16082. normal[ 2 ] /= normals.length;
  16083. var idx = ( y * width + x ) * 4;
  16084. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16085. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16086. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16087. output[ idx + 3 ] = 255;
  16088. }
  16089. }
  16090. context.putImageData( imageData, 0, 0 );
  16091. return canvas;
  16092. },
  16093. generateDataTexture: function ( width, height, color ) {
  16094. var size = width * height;
  16095. var data = new Uint8Array( 3 * size );
  16096. var r = Math.floor( color.r * 255 );
  16097. var g = Math.floor( color.g * 255 );
  16098. var b = Math.floor( color.b * 255 );
  16099. for ( var i = 0; i < size; i ++ ) {
  16100. data[ i * 3 ] = r;
  16101. data[ i * 3 + 1 ] = g;
  16102. data[ i * 3 + 2 ] = b;
  16103. }
  16104. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16105. texture.needsUpdate = true;
  16106. return texture;
  16107. }
  16108. };
  16109. /**
  16110. * @author alteredq / http://alteredqualia.com/
  16111. */
  16112. THREE.SceneUtils = {
  16113. createMultiMaterialObject: function ( geometry, materials ) {
  16114. var group = new THREE.Object3D();
  16115. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16116. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16117. }
  16118. return group;
  16119. },
  16120. detach : function ( child, parent, scene ) {
  16121. child.applyMatrix( parent.matrixWorld );
  16122. parent.remove( child );
  16123. scene.add( child );
  16124. },
  16125. attach: function ( child, scene, parent ) {
  16126. var matrixWorldInverse = new THREE.Matrix4();
  16127. matrixWorldInverse.getInverse( parent.matrixWorld );
  16128. child.applyMatrix( matrixWorldInverse );
  16129. scene.remove( child );
  16130. parent.add( child );
  16131. }
  16132. };
  16133. /**
  16134. * @author zz85 / http://www.lab4games.net/zz85/blog
  16135. * @author alteredq / http://alteredqualia.com/
  16136. *
  16137. * For Text operations in three.js (See TextGeometry)
  16138. *
  16139. * It uses techniques used in:
  16140. *
  16141. * typeface.js and canvastext
  16142. * For converting fonts and rendering with javascript
  16143. * http://typeface.neocracy.org
  16144. *
  16145. * Triangulation ported from AS3
  16146. * Simple Polygon Triangulation
  16147. * http://actionsnippet.com/?p=1462
  16148. *
  16149. * A Method to triangulate shapes with holes
  16150. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16151. *
  16152. */
  16153. THREE.FontUtils = {
  16154. faces : {},
  16155. // Just for now. face[weight][style]
  16156. face : "helvetiker",
  16157. weight: "normal",
  16158. style : "normal",
  16159. size : 150,
  16160. divisions : 10,
  16161. getFace : function() {
  16162. return this.faces[ this.face ][ this.weight ][ this.style ];
  16163. },
  16164. loadFace : function( data ) {
  16165. var family = data.familyName.toLowerCase();
  16166. var ThreeFont = this;
  16167. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16168. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16169. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16170. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16171. return data;
  16172. },
  16173. drawText : function( text ) {
  16174. var characterPts = [], allPts = [];
  16175. // RenderText
  16176. var i, p,
  16177. face = this.getFace(),
  16178. scale = this.size / face.resolution,
  16179. offset = 0,
  16180. chars = String( text ).split( '' ),
  16181. length = chars.length;
  16182. var fontPaths = [];
  16183. for ( i = 0; i < length; i ++ ) {
  16184. var path = new THREE.Path();
  16185. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16186. offset += ret.offset;
  16187. fontPaths.push( ret.path );
  16188. }
  16189. // get the width
  16190. var width = offset / 2;
  16191. //
  16192. // for ( p = 0; p < allPts.length; p++ ) {
  16193. //
  16194. // allPts[ p ].x -= width;
  16195. //
  16196. // }
  16197. //var extract = this.extractPoints( allPts, characterPts );
  16198. //extract.contour = allPts;
  16199. //extract.paths = fontPaths;
  16200. //extract.offset = width;
  16201. return { paths : fontPaths, offset : width };
  16202. },
  16203. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16204. var pts = [];
  16205. var i, i2, divisions,
  16206. outline, action, length,
  16207. scaleX, scaleY,
  16208. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16209. laste,
  16210. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16211. if ( !glyph ) return;
  16212. if ( glyph.o ) {
  16213. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16214. length = outline.length;
  16215. scaleX = scale;
  16216. scaleY = scale;
  16217. for ( i = 0; i < length; ) {
  16218. action = outline[ i ++ ];
  16219. //console.log( action );
  16220. switch( action ) {
  16221. case 'm':
  16222. // Move To
  16223. x = outline[ i++ ] * scaleX + offset;
  16224. y = outline[ i++ ] * scaleY;
  16225. path.moveTo( x, y );
  16226. break;
  16227. case 'l':
  16228. // Line To
  16229. x = outline[ i++ ] * scaleX + offset;
  16230. y = outline[ i++ ] * scaleY;
  16231. path.lineTo(x,y);
  16232. break;
  16233. case 'q':
  16234. // QuadraticCurveTo
  16235. cpx = outline[ i++ ] * scaleX + offset;
  16236. cpy = outline[ i++ ] * scaleY;
  16237. cpx1 = outline[ i++ ] * scaleX + offset;
  16238. cpy1 = outline[ i++ ] * scaleY;
  16239. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16240. laste = pts[ pts.length - 1 ];
  16241. if ( laste ) {
  16242. cpx0 = laste.x;
  16243. cpy0 = laste.y;
  16244. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16245. var t = i2 / divisions;
  16246. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16247. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16248. }
  16249. }
  16250. break;
  16251. case 'b':
  16252. // Cubic Bezier Curve
  16253. cpx = outline[ i++ ] * scaleX + offset;
  16254. cpy = outline[ i++ ] * scaleY;
  16255. cpx1 = outline[ i++ ] * scaleX + offset;
  16256. cpy1 = outline[ i++ ] * -scaleY;
  16257. cpx2 = outline[ i++ ] * scaleX + offset;
  16258. cpy2 = outline[ i++ ] * -scaleY;
  16259. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16260. laste = pts[ pts.length - 1 ];
  16261. if ( laste ) {
  16262. cpx0 = laste.x;
  16263. cpy0 = laste.y;
  16264. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16265. var t = i2 / divisions;
  16266. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16267. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16268. }
  16269. }
  16270. break;
  16271. }
  16272. }
  16273. }
  16274. return { offset: glyph.ha*scale, path:path};
  16275. }
  16276. };
  16277. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16278. // Parameters
  16279. parameters = parameters || {};
  16280. var size = parameters.size !== undefined ? parameters.size : 100;
  16281. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16282. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16283. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16284. var style = parameters.style !== undefined ? parameters.style : "normal";
  16285. THREE.FontUtils.size = size;
  16286. THREE.FontUtils.divisions = curveSegments;
  16287. THREE.FontUtils.face = font;
  16288. THREE.FontUtils.weight = weight;
  16289. THREE.FontUtils.style = style;
  16290. // Get a Font data json object
  16291. var data = THREE.FontUtils.drawText( text );
  16292. var paths = data.paths;
  16293. var shapes = [];
  16294. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16295. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16296. }
  16297. return shapes;
  16298. };
  16299. /**
  16300. * This code is a quick port of code written in C++ which was submitted to
  16301. * flipcode.com by John W. Ratcliff // July 22, 2000
  16302. * See original code and more information here:
  16303. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16304. *
  16305. * ported to actionscript by Zevan Rosser
  16306. * www.actionsnippet.com
  16307. *
  16308. * ported to javascript by Joshua Koo
  16309. * http://www.lab4games.net/zz85/blog
  16310. *
  16311. */
  16312. ( function( namespace ) {
  16313. var EPSILON = 0.0000000001;
  16314. // takes in an contour array and returns
  16315. var process = function( contour, indices ) {
  16316. var n = contour.length;
  16317. if ( n < 3 ) return null;
  16318. var result = [],
  16319. verts = [],
  16320. vertIndices = [];
  16321. /* we want a counter-clockwise polygon in verts */
  16322. var u, v, w;
  16323. if ( area( contour ) > 0.0 ) {
  16324. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16325. } else {
  16326. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16327. }
  16328. var nv = n;
  16329. /* remove nv - 2 vertices, creating 1 triangle every time */
  16330. var count = 2 * nv; /* error detection */
  16331. for( v = nv - 1; nv > 2; ) {
  16332. /* if we loop, it is probably a non-simple polygon */
  16333. if ( ( count-- ) <= 0 ) {
  16334. //** Triangulate: ERROR - probable bad polygon!
  16335. //throw ( "Warning, unable to triangulate polygon!" );
  16336. //return null;
  16337. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16338. console.log( "Warning, unable to triangulate polygon!" );
  16339. if ( indices ) return vertIndices;
  16340. return result;
  16341. }
  16342. /* three consecutive vertices in current polygon, <u,v,w> */
  16343. u = v; if ( nv <= u ) u = 0; /* previous */
  16344. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16345. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16346. if ( snip( contour, u, v, w, nv, verts ) ) {
  16347. var a, b, c, s, t;
  16348. /* true names of the vertices */
  16349. a = verts[ u ];
  16350. b = verts[ v ];
  16351. c = verts[ w ];
  16352. /* output Triangle */
  16353. result.push( [ contour[ a ],
  16354. contour[ b ],
  16355. contour[ c ] ] );
  16356. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16357. /* remove v from the remaining polygon */
  16358. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16359. verts[ s ] = verts[ t ];
  16360. }
  16361. nv--;
  16362. /* reset error detection counter */
  16363. count = 2 * nv;
  16364. }
  16365. }
  16366. if ( indices ) return vertIndices;
  16367. return result;
  16368. };
  16369. // calculate area of the contour polygon
  16370. var area = function ( contour ) {
  16371. var n = contour.length;
  16372. var a = 0.0;
  16373. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16374. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16375. }
  16376. return a * 0.5;
  16377. };
  16378. var snip = function ( contour, u, v, w, n, verts ) {
  16379. var p;
  16380. var ax, ay, bx, by;
  16381. var cx, cy, px, py;
  16382. ax = contour[ verts[ u ] ].x;
  16383. ay = contour[ verts[ u ] ].y;
  16384. bx = contour[ verts[ v ] ].x;
  16385. by = contour[ verts[ v ] ].y;
  16386. cx = contour[ verts[ w ] ].x;
  16387. cy = contour[ verts[ w ] ].y;
  16388. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16389. var aX, aY, bX, bY, cX, cY;
  16390. var apx, apy, bpx, bpy, cpx, cpy;
  16391. var cCROSSap, bCROSScp, aCROSSbp;
  16392. aX = cx - bx; aY = cy - by;
  16393. bX = ax - cx; bY = ay - cy;
  16394. cX = bx - ax; cY = by - ay;
  16395. for ( p = 0; p < n; p++ ) {
  16396. if( (p === u) || (p === v) || (p === w) ) continue;
  16397. px = contour[ verts[ p ] ].x
  16398. py = contour[ verts[ p ] ].y
  16399. apx = px - ax; apy = py - ay;
  16400. bpx = px - bx; bpy = py - by;
  16401. cpx = px - cx; cpy = py - cy;
  16402. // see if p is inside triangle abc
  16403. aCROSSbp = aX*bpy - aY*bpx;
  16404. cCROSSap = cX*apy - cY*apx;
  16405. bCROSScp = bX*cpy - bY*cpx;
  16406. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16407. }
  16408. return true;
  16409. };
  16410. namespace.Triangulate = process;
  16411. namespace.Triangulate.area = area;
  16412. return namespace;
  16413. })(THREE.FontUtils);
  16414. // To use the typeface.js face files, hook up the API
  16415. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16416. THREE.typeface_js = self._typeface_js;
  16417. /**
  16418. * @author zz85 / http://www.lab4games.net/zz85/blog
  16419. * Extensible curve object
  16420. *
  16421. * Some common of Curve methods
  16422. * .getPoint(t), getTangent(t)
  16423. * .getPointAt(u), getTagentAt(u)
  16424. * .getPoints(), .getSpacedPoints()
  16425. * .getLength()
  16426. * .updateArcLengths()
  16427. *
  16428. * This file contains following classes:
  16429. *
  16430. * -- 2d classes --
  16431. * THREE.Curve
  16432. * THREE.LineCurve
  16433. * THREE.QuadraticBezierCurve
  16434. * THREE.CubicBezierCurve
  16435. * THREE.SplineCurve
  16436. * THREE.ArcCurve
  16437. * THREE.EllipseCurve
  16438. *
  16439. * -- 3d classes --
  16440. * THREE.LineCurve3
  16441. * THREE.QuadraticBezierCurve3
  16442. * THREE.CubicBezierCurve3
  16443. * THREE.SplineCurve3
  16444. * THREE.ClosedSplineCurve3
  16445. *
  16446. * A series of curves can be represented as a THREE.CurvePath
  16447. *
  16448. **/
  16449. /**************************************************************
  16450. * Abstract Curve base class
  16451. **************************************************************/
  16452. THREE.Curve = function () {
  16453. };
  16454. // Virtual base class method to overwrite and implement in subclasses
  16455. // - t [0 .. 1]
  16456. THREE.Curve.prototype.getPoint = function ( t ) {
  16457. console.log( "Warning, getPoint() not implemented!" );
  16458. return null;
  16459. };
  16460. // Get point at relative position in curve according to arc length
  16461. // - u [0 .. 1]
  16462. THREE.Curve.prototype.getPointAt = function ( u ) {
  16463. var t = this.getUtoTmapping( u );
  16464. return this.getPoint( t );
  16465. };
  16466. // Get sequence of points using getPoint( t )
  16467. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16468. if ( !divisions ) divisions = 5;
  16469. var d, pts = [];
  16470. for ( d = 0; d <= divisions; d ++ ) {
  16471. pts.push( this.getPoint( d / divisions ) );
  16472. }
  16473. return pts;
  16474. };
  16475. // Get sequence of points using getPointAt( u )
  16476. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16477. if ( !divisions ) divisions = 5;
  16478. var d, pts = [];
  16479. for ( d = 0; d <= divisions; d ++ ) {
  16480. pts.push( this.getPointAt( d / divisions ) );
  16481. }
  16482. return pts;
  16483. };
  16484. // Get total curve arc length
  16485. THREE.Curve.prototype.getLength = function () {
  16486. var lengths = this.getLengths();
  16487. return lengths[ lengths.length - 1 ];
  16488. };
  16489. // Get list of cumulative segment lengths
  16490. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16491. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16492. if ( this.cacheArcLengths
  16493. && ( this.cacheArcLengths.length == divisions + 1 )
  16494. && !this.needsUpdate) {
  16495. //console.log( "cached", this.cacheArcLengths );
  16496. return this.cacheArcLengths;
  16497. }
  16498. this.needsUpdate = false;
  16499. var cache = [];
  16500. var current, last = this.getPoint( 0 );
  16501. var p, sum = 0;
  16502. cache.push( 0 );
  16503. for ( p = 1; p <= divisions; p ++ ) {
  16504. current = this.getPoint ( p / divisions );
  16505. sum += current.distanceTo( last );
  16506. cache.push( sum );
  16507. last = current;
  16508. }
  16509. this.cacheArcLengths = cache;
  16510. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16511. };
  16512. THREE.Curve.prototype.updateArcLengths = function() {
  16513. this.needsUpdate = true;
  16514. this.getLengths();
  16515. };
  16516. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16517. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16518. var arcLengths = this.getLengths();
  16519. var i = 0, il = arcLengths.length;
  16520. var targetArcLength; // The targeted u distance value to get
  16521. if ( distance ) {
  16522. targetArcLength = distance;
  16523. } else {
  16524. targetArcLength = u * arcLengths[ il - 1 ];
  16525. }
  16526. //var time = Date.now();
  16527. // binary search for the index with largest value smaller than target u distance
  16528. var low = 0, high = il - 1, comparison;
  16529. while ( low <= high ) {
  16530. 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
  16531. comparison = arcLengths[ i ] - targetArcLength;
  16532. if ( comparison < 0 ) {
  16533. low = i + 1;
  16534. continue;
  16535. } else if ( comparison > 0 ) {
  16536. high = i - 1;
  16537. continue;
  16538. } else {
  16539. high = i;
  16540. break;
  16541. // DONE
  16542. }
  16543. }
  16544. i = high;
  16545. //console.log('b' , i, low, high, Date.now()- time);
  16546. if ( arcLengths[ i ] == targetArcLength ) {
  16547. var t = i / ( il - 1 );
  16548. return t;
  16549. }
  16550. // we could get finer grain at lengths, or use simple interpolatation between two points
  16551. var lengthBefore = arcLengths[ i ];
  16552. var lengthAfter = arcLengths[ i + 1 ];
  16553. var segmentLength = lengthAfter - lengthBefore;
  16554. // determine where we are between the 'before' and 'after' points
  16555. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16556. // add that fractional amount to t
  16557. var t = ( i + segmentFraction ) / ( il -1 );
  16558. return t;
  16559. };
  16560. // Returns a unit vector tangent at t
  16561. // In case any sub curve does not implement its tangent derivation,
  16562. // 2 points a small delta apart will be used to find its gradient
  16563. // which seems to give a reasonable approximation
  16564. THREE.Curve.prototype.getTangent = function( t ) {
  16565. var delta = 0.0001;
  16566. var t1 = t - delta;
  16567. var t2 = t + delta;
  16568. // Capping in case of danger
  16569. if ( t1 < 0 ) t1 = 0;
  16570. if ( t2 > 1 ) t2 = 1;
  16571. var pt1 = this.getPoint( t1 );
  16572. var pt2 = this.getPoint( t2 );
  16573. var vec = pt2.clone().sub(pt1);
  16574. return vec.normalize();
  16575. };
  16576. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16577. var t = this.getUtoTmapping( u );
  16578. return this.getTangent( t );
  16579. };
  16580. /**************************************************************
  16581. * Line
  16582. **************************************************************/
  16583. THREE.LineCurve = function ( v1, v2 ) {
  16584. this.v1 = v1;
  16585. this.v2 = v2;
  16586. };
  16587. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16588. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16589. var point = this.v2.clone().sub(this.v1);
  16590. point.multiplyScalar( t ).add( this.v1 );
  16591. return point;
  16592. };
  16593. // Line curve is linear, so we can overwrite default getPointAt
  16594. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16595. return this.getPoint( u );
  16596. };
  16597. THREE.LineCurve.prototype.getTangent = function( t ) {
  16598. var tangent = this.v2.clone().sub(this.v1);
  16599. return tangent.normalize();
  16600. };
  16601. /**************************************************************
  16602. * Quadratic Bezier curve
  16603. **************************************************************/
  16604. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16605. this.v0 = v0;
  16606. this.v1 = v1;
  16607. this.v2 = v2;
  16608. };
  16609. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16610. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16611. var tx, ty;
  16612. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16613. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16614. return new THREE.Vector2( tx, ty );
  16615. };
  16616. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16617. var tx, ty;
  16618. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16619. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16620. // returns unit vector
  16621. var tangent = new THREE.Vector2( tx, ty );
  16622. tangent.normalize();
  16623. return tangent;
  16624. };
  16625. /**************************************************************
  16626. * Cubic Bezier curve
  16627. **************************************************************/
  16628. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16629. this.v0 = v0;
  16630. this.v1 = v1;
  16631. this.v2 = v2;
  16632. this.v3 = v3;
  16633. };
  16634. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16635. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16636. var tx, ty;
  16637. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16638. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16639. return new THREE.Vector2( tx, ty );
  16640. };
  16641. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16642. var tx, ty;
  16643. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16644. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16645. var tangent = new THREE.Vector2( tx, ty );
  16646. tangent.normalize();
  16647. return tangent;
  16648. };
  16649. /**************************************************************
  16650. * Spline curve
  16651. **************************************************************/
  16652. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16653. this.points = (points == undefined) ? [] : points;
  16654. };
  16655. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16656. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16657. var v = new THREE.Vector2();
  16658. var c = [];
  16659. var points = this.points, point, intPoint, weight;
  16660. point = ( points.length - 1 ) * t;
  16661. intPoint = Math.floor( point );
  16662. weight = point - intPoint;
  16663. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16664. c[ 1 ] = intPoint;
  16665. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16666. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16667. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16668. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16669. return v;
  16670. };
  16671. /**************************************************************
  16672. * Ellipse curve
  16673. **************************************************************/
  16674. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16675. aStartAngle, aEndAngle,
  16676. aClockwise ) {
  16677. this.aX = aX;
  16678. this.aY = aY;
  16679. this.xRadius = xRadius;
  16680. this.yRadius = yRadius;
  16681. this.aStartAngle = aStartAngle;
  16682. this.aEndAngle = aEndAngle;
  16683. this.aClockwise = aClockwise;
  16684. };
  16685. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16686. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16687. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16688. if ( !this.aClockwise ) {
  16689. t = 1 - t;
  16690. }
  16691. var angle = this.aStartAngle + t * deltaAngle;
  16692. var tx = this.aX + this.xRadius * Math.cos( angle );
  16693. var ty = this.aY + this.yRadius * Math.sin( angle );
  16694. return new THREE.Vector2( tx, ty );
  16695. };
  16696. /**************************************************************
  16697. * Arc curve
  16698. **************************************************************/
  16699. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16700. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16701. };
  16702. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16703. /**************************************************************
  16704. * Utils
  16705. **************************************************************/
  16706. THREE.Curve.Utils = {
  16707. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16708. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16709. },
  16710. // Puay Bing, thanks for helping with this derivative!
  16711. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16712. return -3 * p0 * (1 - t) * (1 - t) +
  16713. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16714. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16715. 3 * t * t * p3;
  16716. },
  16717. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16718. // To check if my formulas are correct
  16719. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16720. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16721. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16722. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16723. return h00 + h10 + h01 + h11;
  16724. },
  16725. // Catmull-Rom
  16726. interpolate: function( p0, p1, p2, p3, t ) {
  16727. var v0 = ( p2 - p0 ) * 0.5;
  16728. var v1 = ( p3 - p1 ) * 0.5;
  16729. var t2 = t * t;
  16730. var t3 = t * t2;
  16731. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16732. }
  16733. };
  16734. // TODO: Transformation for Curves?
  16735. /**************************************************************
  16736. * 3D Curves
  16737. **************************************************************/
  16738. // A Factory method for creating new curve subclasses
  16739. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16740. constructor.prototype = Object.create( THREE.Curve.prototype );
  16741. constructor.prototype.getPoint = getPointFunc;
  16742. return constructor;
  16743. };
  16744. /**************************************************************
  16745. * Line3D
  16746. **************************************************************/
  16747. THREE.LineCurve3 = THREE.Curve.create(
  16748. function ( v1, v2 ) {
  16749. this.v1 = v1;
  16750. this.v2 = v2;
  16751. },
  16752. function ( t ) {
  16753. var r = new THREE.Vector3();
  16754. r.subVectors( this.v2, this.v1 ); // diff
  16755. r.multiplyScalar( t );
  16756. r.add( this.v1 );
  16757. return r;
  16758. }
  16759. );
  16760. /**************************************************************
  16761. * Quadratic Bezier 3D curve
  16762. **************************************************************/
  16763. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16764. function ( v0, v1, v2 ) {
  16765. this.v0 = v0;
  16766. this.v1 = v1;
  16767. this.v2 = v2;
  16768. },
  16769. function ( t ) {
  16770. var tx, ty, tz;
  16771. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16772. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16773. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16774. return new THREE.Vector3( tx, ty, tz );
  16775. }
  16776. );
  16777. /**************************************************************
  16778. * Cubic Bezier 3D curve
  16779. **************************************************************/
  16780. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16781. function ( v0, v1, v2, v3 ) {
  16782. this.v0 = v0;
  16783. this.v1 = v1;
  16784. this.v2 = v2;
  16785. this.v3 = v3;
  16786. },
  16787. function ( t ) {
  16788. var tx, ty, tz;
  16789. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16790. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16791. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16792. return new THREE.Vector3( tx, ty, tz );
  16793. }
  16794. );
  16795. /**************************************************************
  16796. * Spline 3D curve
  16797. **************************************************************/
  16798. THREE.SplineCurve3 = THREE.Curve.create(
  16799. function ( points /* array of Vector3 */) {
  16800. this.points = (points == undefined) ? [] : points;
  16801. },
  16802. function ( t ) {
  16803. var v = new THREE.Vector3();
  16804. var c = [];
  16805. var points = this.points, point, intPoint, weight;
  16806. point = ( points.length - 1 ) * t;
  16807. intPoint = Math.floor( point );
  16808. weight = point - intPoint;
  16809. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16810. c[ 1 ] = intPoint;
  16811. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16812. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16813. var pt0 = points[ c[0] ],
  16814. pt1 = points[ c[1] ],
  16815. pt2 = points[ c[2] ],
  16816. pt3 = points[ c[3] ];
  16817. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16818. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16819. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16820. return v;
  16821. }
  16822. );
  16823. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16824. // var v = new THREE.Vector3();
  16825. // var c = [];
  16826. // var points = this.points, point, intPoint, weight;
  16827. // point = ( points.length - 1 ) * t;
  16828. // intPoint = Math.floor( point );
  16829. // weight = point - intPoint;
  16830. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16831. // c[ 1 ] = intPoint;
  16832. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16833. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16834. // var pt0 = points[ c[0] ],
  16835. // pt1 = points[ c[1] ],
  16836. // pt2 = points[ c[2] ],
  16837. // pt3 = points[ c[3] ];
  16838. // // t = weight;
  16839. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16840. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16841. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16842. // return v;
  16843. // }
  16844. /**************************************************************
  16845. * Closed Spline 3D curve
  16846. **************************************************************/
  16847. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16848. function ( points /* array of Vector3 */) {
  16849. this.points = (points == undefined) ? [] : points;
  16850. },
  16851. function ( t ) {
  16852. var v = new THREE.Vector3();
  16853. var c = [];
  16854. var points = this.points, point, intPoint, weight;
  16855. point = ( points.length - 0 ) * t;
  16856. // This needs to be from 0-length +1
  16857. intPoint = Math.floor( point );
  16858. weight = point - intPoint;
  16859. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16860. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16861. c[ 1 ] = ( intPoint ) % points.length;
  16862. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16863. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16864. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16865. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16866. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16867. return v;
  16868. }
  16869. );
  16870. /**
  16871. * @author zz85 / http://www.lab4games.net/zz85/blog
  16872. *
  16873. **/
  16874. /**************************************************************
  16875. * Curved Path - a curve path is simply a array of connected
  16876. * curves, but retains the api of a curve
  16877. **************************************************************/
  16878. THREE.CurvePath = function () {
  16879. this.curves = [];
  16880. this.bends = [];
  16881. this.autoClose = false; // Automatically closes the path
  16882. };
  16883. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16884. THREE.CurvePath.prototype.add = function ( curve ) {
  16885. this.curves.push( curve );
  16886. };
  16887. THREE.CurvePath.prototype.checkConnection = function() {
  16888. // TODO
  16889. // If the ending of curve is not connected to the starting
  16890. // or the next curve, then, this is not a real path
  16891. };
  16892. THREE.CurvePath.prototype.closePath = function() {
  16893. // TODO Test
  16894. // and verify for vector3 (needs to implement equals)
  16895. // Add a line curve if start and end of lines are not connected
  16896. var startPoint = this.curves[0].getPoint(0);
  16897. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16898. if (!startPoint.equals(endPoint)) {
  16899. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16900. }
  16901. };
  16902. // To get accurate point with reference to
  16903. // entire path distance at time t,
  16904. // following has to be done:
  16905. // 1. Length of each sub path have to be known
  16906. // 2. Locate and identify type of curve
  16907. // 3. Get t for the curve
  16908. // 4. Return curve.getPointAt(t')
  16909. THREE.CurvePath.prototype.getPoint = function( t ) {
  16910. var d = t * this.getLength();
  16911. var curveLengths = this.getCurveLengths();
  16912. var i = 0, diff, curve;
  16913. // To think about boundaries points.
  16914. while ( i < curveLengths.length ) {
  16915. if ( curveLengths[ i ] >= d ) {
  16916. diff = curveLengths[ i ] - d;
  16917. curve = this.curves[ i ];
  16918. var u = 1 - diff / curve.getLength();
  16919. return curve.getPointAt( u );
  16920. break;
  16921. }
  16922. i ++;
  16923. }
  16924. return null;
  16925. // loop where sum != 0, sum > d , sum+1 <d
  16926. };
  16927. /*
  16928. THREE.CurvePath.prototype.getTangent = function( t ) {
  16929. };*/
  16930. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16931. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16932. // getPoint() depends on getLength
  16933. THREE.CurvePath.prototype.getLength = function() {
  16934. var lens = this.getCurveLengths();
  16935. return lens[ lens.length - 1 ];
  16936. };
  16937. // Compute lengths and cache them
  16938. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16939. THREE.CurvePath.prototype.getCurveLengths = function() {
  16940. // We use cache values if curves and cache array are same length
  16941. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16942. return this.cacheLengths;
  16943. };
  16944. // Get length of subsurve
  16945. // Push sums into cached array
  16946. var lengths = [], sums = 0;
  16947. var i, il = this.curves.length;
  16948. for ( i = 0; i < il; i ++ ) {
  16949. sums += this.curves[ i ].getLength();
  16950. lengths.push( sums );
  16951. }
  16952. this.cacheLengths = lengths;
  16953. return lengths;
  16954. };
  16955. // Returns min and max coordinates, as well as centroid
  16956. THREE.CurvePath.prototype.getBoundingBox = function () {
  16957. var points = this.getPoints();
  16958. var maxX, maxY, maxZ;
  16959. var minX, minY, minZ;
  16960. maxX = maxY = Number.NEGATIVE_INFINITY;
  16961. minX = minY = Number.POSITIVE_INFINITY;
  16962. var p, i, il, sum;
  16963. var v3 = points[0] instanceof THREE.Vector3;
  16964. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16965. for ( i = 0, il = points.length; i < il; i ++ ) {
  16966. p = points[ i ];
  16967. if ( p.x > maxX ) maxX = p.x;
  16968. else if ( p.x < minX ) minX = p.x;
  16969. if ( p.y > maxY ) maxY = p.y;
  16970. else if ( p.y < minY ) minY = p.y;
  16971. if ( v3 ) {
  16972. if ( p.z > maxZ ) maxZ = p.z;
  16973. else if ( p.z < minZ ) minZ = p.z;
  16974. }
  16975. sum.add( p );
  16976. }
  16977. var ret = {
  16978. minX: minX,
  16979. minY: minY,
  16980. maxX: maxX,
  16981. maxY: maxY,
  16982. centroid: sum.divideScalar( il )
  16983. };
  16984. if ( v3 ) {
  16985. ret.maxZ = maxZ;
  16986. ret.minZ = minZ;
  16987. }
  16988. return ret;
  16989. };
  16990. /**************************************************************
  16991. * Create Geometries Helpers
  16992. **************************************************************/
  16993. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16994. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16995. var pts = this.getPoints( divisions, true );
  16996. return this.createGeometry( pts );
  16997. };
  16998. // Generate geometry from equidistance sampling along the path
  16999. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17000. var pts = this.getSpacedPoints( divisions, true );
  17001. return this.createGeometry( pts );
  17002. };
  17003. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17004. var geometry = new THREE.Geometry();
  17005. for ( var i = 0; i < points.length; i ++ ) {
  17006. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17007. }
  17008. return geometry;
  17009. };
  17010. /**************************************************************
  17011. * Bend / Wrap Helper Methods
  17012. **************************************************************/
  17013. // Wrap path / Bend modifiers?
  17014. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17015. this.bends.push( bendpath );
  17016. };
  17017. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17018. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17019. var i, il;
  17020. if ( !bends ) {
  17021. bends = this.bends;
  17022. }
  17023. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17024. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17025. }
  17026. return oldPts;
  17027. };
  17028. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17029. var oldPts = this.getSpacedPoints( segments );
  17030. var i, il;
  17031. if ( !bends ) {
  17032. bends = this.bends;
  17033. }
  17034. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17035. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17036. }
  17037. return oldPts;
  17038. };
  17039. // This returns getPoints() bend/wrapped around the contour of a path.
  17040. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17041. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17042. var bounds = this.getBoundingBox();
  17043. var i, il, p, oldX, oldY, xNorm;
  17044. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17045. p = oldPts[ i ];
  17046. oldX = p.x;
  17047. oldY = p.y;
  17048. xNorm = oldX / bounds.maxX;
  17049. // If using actual distance, for length > path, requires line extrusions
  17050. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17051. xNorm = path.getUtoTmapping( xNorm, oldX );
  17052. // check for out of bounds?
  17053. var pathPt = path.getPoint( xNorm );
  17054. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17055. p.x = pathPt.x + normal.x;
  17056. p.y = pathPt.y + normal.y;
  17057. }
  17058. return oldPts;
  17059. };
  17060. /**
  17061. * @author alteredq / http://alteredqualia.com/
  17062. */
  17063. THREE.Gyroscope = function () {
  17064. THREE.Object3D.call( this );
  17065. };
  17066. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17067. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17068. this.matrixAutoUpdate && this.updateMatrix();
  17069. // update matrixWorld
  17070. if ( this.matrixWorldNeedsUpdate || force ) {
  17071. if ( this.parent ) {
  17072. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17073. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  17074. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  17075. this.matrixWorld.makeFromPositionQuaternionScale( this.translationWorld, this.rotationObject, this.scaleWorld );
  17076. } else {
  17077. this.matrixWorld.copy( this.matrix );
  17078. }
  17079. this.matrixWorldNeedsUpdate = false;
  17080. force = true;
  17081. }
  17082. // update children
  17083. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17084. this.children[ i ].updateMatrixWorld( force );
  17085. }
  17086. };
  17087. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17088. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17089. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  17090. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  17091. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17092. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17093. /**
  17094. * @author zz85 / http://www.lab4games.net/zz85/blog
  17095. * Creates free form 2d path using series of points, lines or curves.
  17096. *
  17097. **/
  17098. THREE.Path = function ( points ) {
  17099. THREE.CurvePath.call(this);
  17100. this.actions = [];
  17101. if ( points ) {
  17102. this.fromPoints( points );
  17103. }
  17104. };
  17105. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17106. THREE.PathActions = {
  17107. MOVE_TO: 'moveTo',
  17108. LINE_TO: 'lineTo',
  17109. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17110. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17111. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17112. ARC: 'arc', // Circle
  17113. ELLIPSE: 'ellipse'
  17114. };
  17115. // TODO Clean up PATH API
  17116. // Create path using straight lines to connect all points
  17117. // - vectors: array of Vector2
  17118. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17119. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17120. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17121. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17122. };
  17123. };
  17124. // startPath() endPath()?
  17125. THREE.Path.prototype.moveTo = function ( x, y ) {
  17126. var args = Array.prototype.slice.call( arguments );
  17127. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17128. };
  17129. THREE.Path.prototype.lineTo = function ( x, y ) {
  17130. var args = Array.prototype.slice.call( arguments );
  17131. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17132. var x0 = lastargs[ lastargs.length - 2 ];
  17133. var y0 = lastargs[ lastargs.length - 1 ];
  17134. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17135. this.curves.push( curve );
  17136. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17137. };
  17138. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17139. var args = Array.prototype.slice.call( arguments );
  17140. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17141. var x0 = lastargs[ lastargs.length - 2 ];
  17142. var y0 = lastargs[ lastargs.length - 1 ];
  17143. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17144. new THREE.Vector2( aCPx, aCPy ),
  17145. new THREE.Vector2( aX, aY ) );
  17146. this.curves.push( curve );
  17147. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17148. };
  17149. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17150. aCP2x, aCP2y,
  17151. aX, aY ) {
  17152. var args = Array.prototype.slice.call( arguments );
  17153. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17154. var x0 = lastargs[ lastargs.length - 2 ];
  17155. var y0 = lastargs[ lastargs.length - 1 ];
  17156. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17157. new THREE.Vector2( aCP1x, aCP1y ),
  17158. new THREE.Vector2( aCP2x, aCP2y ),
  17159. new THREE.Vector2( aX, aY ) );
  17160. this.curves.push( curve );
  17161. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17162. };
  17163. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17164. var args = Array.prototype.slice.call( arguments );
  17165. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17166. var x0 = lastargs[ lastargs.length - 2 ];
  17167. var y0 = lastargs[ lastargs.length - 1 ];
  17168. //---
  17169. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17170. Array.prototype.push.apply( npts, pts );
  17171. var curve = new THREE.SplineCurve( npts );
  17172. this.curves.push( curve );
  17173. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17174. };
  17175. // FUTURE: Change the API or follow canvas API?
  17176. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17177. aStartAngle, aEndAngle, aClockwise ) {
  17178. var lastargs = this.actions[ this.actions.length - 1].args;
  17179. var x0 = lastargs[ lastargs.length - 2 ];
  17180. var y0 = lastargs[ lastargs.length - 1 ];
  17181. this.absarc(aX + x0, aY + y0, aRadius,
  17182. aStartAngle, aEndAngle, aClockwise );
  17183. };
  17184. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17185. aStartAngle, aEndAngle, aClockwise ) {
  17186. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17187. };
  17188. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17189. aStartAngle, aEndAngle, aClockwise ) {
  17190. var lastargs = this.actions[ this.actions.length - 1].args;
  17191. var x0 = lastargs[ lastargs.length - 2 ];
  17192. var y0 = lastargs[ lastargs.length - 1 ];
  17193. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17194. aStartAngle, aEndAngle, aClockwise );
  17195. };
  17196. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17197. aStartAngle, aEndAngle, aClockwise ) {
  17198. var args = Array.prototype.slice.call( arguments );
  17199. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17200. aStartAngle, aEndAngle, aClockwise );
  17201. this.curves.push( curve );
  17202. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17203. args.push(lastPoint.x);
  17204. args.push(lastPoint.y);
  17205. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17206. };
  17207. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17208. if ( ! divisions ) divisions = 40;
  17209. var points = [];
  17210. for ( var i = 0; i < divisions; i ++ ) {
  17211. points.push( this.getPoint( i / divisions ) );
  17212. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17213. }
  17214. // if ( closedPath ) {
  17215. //
  17216. // points.push( points[ 0 ] );
  17217. //
  17218. // }
  17219. return points;
  17220. };
  17221. /* Return an array of vectors based on contour of the path */
  17222. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17223. if (this.useSpacedPoints) {
  17224. console.log('tata');
  17225. return this.getSpacedPoints( divisions, closedPath );
  17226. }
  17227. divisions = divisions || 12;
  17228. var points = [];
  17229. var i, il, item, action, args;
  17230. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17231. laste, j,
  17232. t, tx, ty;
  17233. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17234. item = this.actions[ i ];
  17235. action = item.action;
  17236. args = item.args;
  17237. switch( action ) {
  17238. case THREE.PathActions.MOVE_TO:
  17239. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17240. break;
  17241. case THREE.PathActions.LINE_TO:
  17242. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17243. break;
  17244. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17245. cpx = args[ 2 ];
  17246. cpy = args[ 3 ];
  17247. cpx1 = args[ 0 ];
  17248. cpy1 = args[ 1 ];
  17249. if ( points.length > 0 ) {
  17250. laste = points[ points.length - 1 ];
  17251. cpx0 = laste.x;
  17252. cpy0 = laste.y;
  17253. } else {
  17254. laste = this.actions[ i - 1 ].args;
  17255. cpx0 = laste[ laste.length - 2 ];
  17256. cpy0 = laste[ laste.length - 1 ];
  17257. }
  17258. for ( j = 1; j <= divisions; j ++ ) {
  17259. t = j / divisions;
  17260. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17261. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17262. points.push( new THREE.Vector2( tx, ty ) );
  17263. }
  17264. break;
  17265. case THREE.PathActions.BEZIER_CURVE_TO:
  17266. cpx = args[ 4 ];
  17267. cpy = args[ 5 ];
  17268. cpx1 = args[ 0 ];
  17269. cpy1 = args[ 1 ];
  17270. cpx2 = args[ 2 ];
  17271. cpy2 = args[ 3 ];
  17272. if ( points.length > 0 ) {
  17273. laste = points[ points.length - 1 ];
  17274. cpx0 = laste.x;
  17275. cpy0 = laste.y;
  17276. } else {
  17277. laste = this.actions[ i - 1 ].args;
  17278. cpx0 = laste[ laste.length - 2 ];
  17279. cpy0 = laste[ laste.length - 1 ];
  17280. }
  17281. for ( j = 1; j <= divisions; j ++ ) {
  17282. t = j / divisions;
  17283. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17284. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17285. points.push( new THREE.Vector2( tx, ty ) );
  17286. }
  17287. break;
  17288. case THREE.PathActions.CSPLINE_THRU:
  17289. laste = this.actions[ i - 1 ].args;
  17290. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17291. var spts = [ last ];
  17292. var n = divisions * args[ 0 ].length;
  17293. spts = spts.concat( args[ 0 ] );
  17294. var spline = new THREE.SplineCurve( spts );
  17295. for ( j = 1; j <= n; j ++ ) {
  17296. points.push( spline.getPointAt( j / n ) ) ;
  17297. }
  17298. break;
  17299. case THREE.PathActions.ARC:
  17300. var aX = args[ 0 ], aY = args[ 1 ],
  17301. aRadius = args[ 2 ],
  17302. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17303. aClockwise = !!args[ 5 ];
  17304. var deltaAngle = aEndAngle - aStartAngle;
  17305. var angle;
  17306. var tdivisions = divisions * 2;
  17307. for ( j = 1; j <= tdivisions; j ++ ) {
  17308. t = j / tdivisions;
  17309. if ( ! aClockwise ) {
  17310. t = 1 - t;
  17311. }
  17312. angle = aStartAngle + t * deltaAngle;
  17313. tx = aX + aRadius * Math.cos( angle );
  17314. ty = aY + aRadius * Math.sin( angle );
  17315. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17316. points.push( new THREE.Vector2( tx, ty ) );
  17317. }
  17318. //console.log(points);
  17319. break;
  17320. case THREE.PathActions.ELLIPSE:
  17321. var aX = args[ 0 ], aY = args[ 1 ],
  17322. xRadius = args[ 2 ],
  17323. yRadius = args[ 3 ],
  17324. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17325. aClockwise = !!args[ 6 ];
  17326. var deltaAngle = aEndAngle - aStartAngle;
  17327. var angle;
  17328. var tdivisions = divisions * 2;
  17329. for ( j = 1; j <= tdivisions; j ++ ) {
  17330. t = j / tdivisions;
  17331. if ( ! aClockwise ) {
  17332. t = 1 - t;
  17333. }
  17334. angle = aStartAngle + t * deltaAngle;
  17335. tx = aX + xRadius * Math.cos( angle );
  17336. ty = aY + yRadius * Math.sin( angle );
  17337. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17338. points.push( new THREE.Vector2( tx, ty ) );
  17339. }
  17340. //console.log(points);
  17341. break;
  17342. } // end switch
  17343. }
  17344. // Normalize to remove the closing point by default.
  17345. var lastPoint = points[ points.length - 1];
  17346. var EPSILON = 0.0000000001;
  17347. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17348. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17349. points.splice( points.length - 1, 1);
  17350. if ( closedPath ) {
  17351. points.push( points[ 0 ] );
  17352. }
  17353. return points;
  17354. };
  17355. // Breaks path into shapes
  17356. THREE.Path.prototype.toShapes = function() {
  17357. var i, il, item, action, args;
  17358. var subPaths = [], lastPath = new THREE.Path();
  17359. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17360. item = this.actions[ i ];
  17361. args = item.args;
  17362. action = item.action;
  17363. if ( action == THREE.PathActions.MOVE_TO ) {
  17364. if ( lastPath.actions.length != 0 ) {
  17365. subPaths.push( lastPath );
  17366. lastPath = new THREE.Path();
  17367. }
  17368. }
  17369. lastPath[ action ].apply( lastPath, args );
  17370. }
  17371. if ( lastPath.actions.length != 0 ) {
  17372. subPaths.push( lastPath );
  17373. }
  17374. // console.log(subPaths);
  17375. if ( subPaths.length == 0 ) return [];
  17376. var tmpPath, tmpShape, shapes = [];
  17377. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17378. // console.log("Holes first", holesFirst);
  17379. if ( subPaths.length == 1) {
  17380. tmpPath = subPaths[0];
  17381. tmpShape = new THREE.Shape();
  17382. tmpShape.actions = tmpPath.actions;
  17383. tmpShape.curves = tmpPath.curves;
  17384. shapes.push( tmpShape );
  17385. return shapes;
  17386. };
  17387. if ( holesFirst ) {
  17388. tmpShape = new THREE.Shape();
  17389. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17390. tmpPath = subPaths[ i ];
  17391. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17392. tmpShape.actions = tmpPath.actions;
  17393. tmpShape.curves = tmpPath.curves;
  17394. shapes.push( tmpShape );
  17395. tmpShape = new THREE.Shape();
  17396. //console.log('cw', i);
  17397. } else {
  17398. tmpShape.holes.push( tmpPath );
  17399. //console.log('ccw', i);
  17400. }
  17401. }
  17402. } else {
  17403. // Shapes first
  17404. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17405. tmpPath = subPaths[ i ];
  17406. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17407. if ( tmpShape ) shapes.push( tmpShape );
  17408. tmpShape = new THREE.Shape();
  17409. tmpShape.actions = tmpPath.actions;
  17410. tmpShape.curves = tmpPath.curves;
  17411. } else {
  17412. tmpShape.holes.push( tmpPath );
  17413. }
  17414. }
  17415. shapes.push( tmpShape );
  17416. }
  17417. //console.log("shape", shapes);
  17418. return shapes;
  17419. };
  17420. /**
  17421. * @author zz85 / http://www.lab4games.net/zz85/blog
  17422. * Defines a 2d shape plane using paths.
  17423. **/
  17424. // STEP 1 Create a path.
  17425. // STEP 2 Turn path into shape.
  17426. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17427. // STEP 3a - Extract points from each shape, turn to vertices
  17428. // STEP 3b - Triangulate each shape, add faces.
  17429. THREE.Shape = function () {
  17430. THREE.Path.apply( this, arguments );
  17431. this.holes = [];
  17432. };
  17433. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17434. // Convenience method to return ExtrudeGeometry
  17435. THREE.Shape.prototype.extrude = function ( options ) {
  17436. var extruded = new THREE.ExtrudeGeometry( this, options );
  17437. return extruded;
  17438. };
  17439. // Convenience method to return ShapeGeometry
  17440. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17441. var geometry = new THREE.ShapeGeometry( this, options );
  17442. return geometry;
  17443. };
  17444. // Get points of holes
  17445. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17446. var i, il = this.holes.length, holesPts = [];
  17447. for ( i = 0; i < il; i ++ ) {
  17448. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17449. }
  17450. return holesPts;
  17451. };
  17452. // Get points of holes (spaced by regular distance)
  17453. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17454. var i, il = this.holes.length, holesPts = [];
  17455. for ( i = 0; i < il; i ++ ) {
  17456. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17457. }
  17458. return holesPts;
  17459. };
  17460. // Get points of shape and holes (keypoints based on segments parameter)
  17461. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17462. return {
  17463. shape: this.getTransformedPoints( divisions ),
  17464. holes: this.getPointsHoles( divisions )
  17465. };
  17466. };
  17467. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17468. if (this.useSpacedPoints) {
  17469. return this.extractAllSpacedPoints(divisions);
  17470. }
  17471. return this.extractAllPoints(divisions);
  17472. };
  17473. //
  17474. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17475. //
  17476. // return {
  17477. //
  17478. // shape: this.transform( bend, divisions ),
  17479. // holes: this.getPointsHoles( divisions, bend )
  17480. //
  17481. // };
  17482. //
  17483. // };
  17484. // Get points of shape and holes (spaced by regular distance)
  17485. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17486. return {
  17487. shape: this.getTransformedSpacedPoints( divisions ),
  17488. holes: this.getSpacedPointsHoles( divisions )
  17489. };
  17490. };
  17491. /**************************************************************
  17492. * Utils
  17493. **************************************************************/
  17494. THREE.Shape.Utils = {
  17495. /*
  17496. contour - array of vector2 for contour
  17497. holes - array of array of vector2
  17498. */
  17499. removeHoles: function ( contour, holes ) {
  17500. var shape = contour.concat(); // work on this shape
  17501. var allpoints = shape.concat();
  17502. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17503. var prevShapeVert, nextShapeVert,
  17504. prevHoleVert, nextHoleVert,
  17505. holeIndex, shapeIndex,
  17506. shapeId, shapeGroup,
  17507. h, h2,
  17508. hole, shortest, d,
  17509. p, pts1, pts2,
  17510. tmpShape1, tmpShape2,
  17511. tmpHole1, tmpHole2,
  17512. verts = [];
  17513. for ( h = 0; h < holes.length; h ++ ) {
  17514. hole = holes[ h ];
  17515. /*
  17516. shapeholes[ h ].concat(); // preserves original
  17517. holes.push( hole );
  17518. */
  17519. Array.prototype.push.apply( allpoints, hole );
  17520. shortest = Number.POSITIVE_INFINITY;
  17521. // Find the shortest pair of pts between shape and hole
  17522. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17523. // Using distanceToSquared() intead of distanceTo() should speed a little
  17524. // since running square roots operations are reduced.
  17525. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17526. pts1 = hole[ h2 ];
  17527. var dist = [];
  17528. for ( p = 0; p < shape.length; p++ ) {
  17529. pts2 = shape[ p ];
  17530. d = pts1.distanceToSquared( pts2 );
  17531. dist.push( d );
  17532. if ( d < shortest ) {
  17533. shortest = d;
  17534. holeIndex = h2;
  17535. shapeIndex = p;
  17536. }
  17537. }
  17538. }
  17539. //console.log("shortest", shortest, dist);
  17540. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17541. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17542. var areaapts = [
  17543. hole[ holeIndex ],
  17544. shape[ shapeIndex ],
  17545. shape[ prevShapeVert ]
  17546. ];
  17547. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17548. var areabpts = [
  17549. hole[ holeIndex ],
  17550. hole[ prevHoleVert ],
  17551. shape[ shapeIndex ]
  17552. ];
  17553. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17554. var shapeOffset = 1;
  17555. var holeOffset = -1;
  17556. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17557. shapeIndex += shapeOffset;
  17558. holeIndex += holeOffset;
  17559. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17560. shapeIndex %= shape.length;
  17561. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17562. holeIndex %= hole.length;
  17563. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17564. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17565. areaapts = [
  17566. hole[ holeIndex ],
  17567. shape[ shapeIndex ],
  17568. shape[ prevShapeVert ]
  17569. ];
  17570. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17571. areabpts = [
  17572. hole[ holeIndex ],
  17573. hole[ prevHoleVert ],
  17574. shape[ shapeIndex ]
  17575. ];
  17576. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17577. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17578. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17579. // In case areas are not correct.
  17580. //console.log("USE THIS");
  17581. shapeIndex = oldShapeIndex;
  17582. holeIndex = oldHoleIndex ;
  17583. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17584. shapeIndex %= shape.length;
  17585. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17586. holeIndex %= hole.length;
  17587. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17588. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17589. } else {
  17590. //console.log("USE THAT ")
  17591. }
  17592. tmpShape1 = shape.slice( 0, shapeIndex );
  17593. tmpShape2 = shape.slice( shapeIndex );
  17594. tmpHole1 = hole.slice( holeIndex );
  17595. tmpHole2 = hole.slice( 0, holeIndex );
  17596. // Should check orders here again?
  17597. var trianglea = [
  17598. hole[ holeIndex ],
  17599. shape[ shapeIndex ],
  17600. shape[ prevShapeVert ]
  17601. ];
  17602. var triangleb = [
  17603. hole[ holeIndex ] ,
  17604. hole[ prevHoleVert ],
  17605. shape[ shapeIndex ]
  17606. ];
  17607. verts.push( trianglea );
  17608. verts.push( triangleb );
  17609. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17610. }
  17611. return {
  17612. shape:shape, /* shape with no holes */
  17613. isolatedPts: verts, /* isolated faces */
  17614. allpoints: allpoints
  17615. }
  17616. },
  17617. triangulateShape: function ( contour, holes ) {
  17618. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17619. var shape = shapeWithoutHoles.shape,
  17620. allpoints = shapeWithoutHoles.allpoints,
  17621. isolatedPts = shapeWithoutHoles.isolatedPts;
  17622. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17623. // 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.
  17624. //console.log( "triangles",triangles, triangles.length );
  17625. //console.log( "allpoints",allpoints, allpoints.length );
  17626. var i, il, f, face,
  17627. key, index,
  17628. allPointsMap = {},
  17629. isolatedPointsMap = {};
  17630. // prepare all points map
  17631. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17632. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17633. if ( allPointsMap[ key ] !== undefined ) {
  17634. console.log( "Duplicate point", key );
  17635. }
  17636. allPointsMap[ key ] = i;
  17637. }
  17638. // check all face vertices against all points map
  17639. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17640. face = triangles[ i ];
  17641. for ( f = 0; f < 3; f ++ ) {
  17642. key = face[ f ].x + ":" + face[ f ].y;
  17643. index = allPointsMap[ key ];
  17644. if ( index !== undefined ) {
  17645. face[ f ] = index;
  17646. }
  17647. }
  17648. }
  17649. // check isolated points vertices against all points map
  17650. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17651. face = isolatedPts[ i ];
  17652. for ( f = 0; f < 3; f ++ ) {
  17653. key = face[ f ].x + ":" + face[ f ].y;
  17654. index = allPointsMap[ key ];
  17655. if ( index !== undefined ) {
  17656. face[ f ] = index;
  17657. }
  17658. }
  17659. }
  17660. return triangles.concat( isolatedPts );
  17661. }, // end triangulate shapes
  17662. /*
  17663. triangulate2 : function( pts, holes ) {
  17664. // For use with Poly2Tri.js
  17665. var allpts = pts.concat();
  17666. var shape = [];
  17667. for (var p in pts) {
  17668. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17669. }
  17670. var swctx = new js.poly2tri.SweepContext(shape);
  17671. for (var h in holes) {
  17672. var aHole = holes[h];
  17673. var newHole = []
  17674. for (i in aHole) {
  17675. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17676. allpts.push(aHole[i]);
  17677. }
  17678. swctx.AddHole(newHole);
  17679. }
  17680. var find;
  17681. var findIndexForPt = function (pt) {
  17682. find = new THREE.Vector2(pt.x, pt.y);
  17683. var p;
  17684. for (p=0, pl = allpts.length; p<pl; p++) {
  17685. if (allpts[p].equals(find)) return p;
  17686. }
  17687. return -1;
  17688. };
  17689. // triangulate
  17690. js.poly2tri.sweep.Triangulate(swctx);
  17691. var triangles = swctx.GetTriangles();
  17692. var tr ;
  17693. var facesPts = [];
  17694. for (var t in triangles) {
  17695. tr = triangles[t];
  17696. facesPts.push([
  17697. findIndexForPt(tr.GetPoint(0)),
  17698. findIndexForPt(tr.GetPoint(1)),
  17699. findIndexForPt(tr.GetPoint(2))
  17700. ]);
  17701. }
  17702. // console.log(facesPts);
  17703. // console.log("triangles", triangles.length, triangles);
  17704. // Returns array of faces with 3 element each
  17705. return facesPts;
  17706. },
  17707. */
  17708. isClockWise: function ( pts ) {
  17709. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17710. },
  17711. // Bezier Curves formulas obtained from
  17712. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17713. // Quad Bezier Functions
  17714. b2p0: function ( t, p ) {
  17715. var k = 1 - t;
  17716. return k * k * p;
  17717. },
  17718. b2p1: function ( t, p ) {
  17719. return 2 * ( 1 - t ) * t * p;
  17720. },
  17721. b2p2: function ( t, p ) {
  17722. return t * t * p;
  17723. },
  17724. b2: function ( t, p0, p1, p2 ) {
  17725. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17726. },
  17727. // Cubic Bezier Functions
  17728. b3p0: function ( t, p ) {
  17729. var k = 1 - t;
  17730. return k * k * k * p;
  17731. },
  17732. b3p1: function ( t, p ) {
  17733. var k = 1 - t;
  17734. return 3 * k * k * t * p;
  17735. },
  17736. b3p2: function ( t, p ) {
  17737. var k = 1 - t;
  17738. return 3 * k * t * t * p;
  17739. },
  17740. b3p3: function ( t, p ) {
  17741. return t * t * t * p;
  17742. },
  17743. b3: function ( t, p0, p1, p2, p3 ) {
  17744. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17745. }
  17746. };
  17747. /**
  17748. * @author mikael emtinger / http://gomo.se/
  17749. */
  17750. THREE.AnimationHandler = (function() {
  17751. var playing = [];
  17752. var library = {};
  17753. var that = {};
  17754. //--- update ---
  17755. that.update = function( deltaTimeMS ) {
  17756. for( var i = 0; i < playing.length; i ++ )
  17757. playing[ i ].update( deltaTimeMS );
  17758. };
  17759. //--- add ---
  17760. that.addToUpdate = function( animation ) {
  17761. if ( playing.indexOf( animation ) === -1 )
  17762. playing.push( animation );
  17763. };
  17764. //--- remove ---
  17765. that.removeFromUpdate = function( animation ) {
  17766. var index = playing.indexOf( animation );
  17767. if( index !== -1 )
  17768. playing.splice( index, 1 );
  17769. };
  17770. //--- add ---
  17771. that.add = function( data ) {
  17772. if ( library[ data.name ] !== undefined )
  17773. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17774. library[ data.name ] = data;
  17775. initData( data );
  17776. };
  17777. //--- get ---
  17778. that.get = function( name ) {
  17779. if ( typeof name === "string" ) {
  17780. if ( library[ name ] ) {
  17781. return library[ name ];
  17782. } else {
  17783. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17784. return null;
  17785. }
  17786. } else {
  17787. // todo: add simple tween library
  17788. }
  17789. };
  17790. //--- parse ---
  17791. that.parse = function( root ) {
  17792. // setup hierarchy
  17793. var hierarchy = [];
  17794. if ( root instanceof THREE.SkinnedMesh ) {
  17795. for( var b = 0; b < root.bones.length; b++ ) {
  17796. hierarchy.push( root.bones[ b ] );
  17797. }
  17798. } else {
  17799. parseRecurseHierarchy( root, hierarchy );
  17800. }
  17801. return hierarchy;
  17802. };
  17803. var parseRecurseHierarchy = function( root, hierarchy ) {
  17804. hierarchy.push( root );
  17805. for( var c = 0; c < root.children.length; c++ )
  17806. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17807. }
  17808. //--- init data ---
  17809. var initData = function( data ) {
  17810. if( data.initialized === true )
  17811. return;
  17812. // loop through all keys
  17813. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17814. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17815. // remove minus times
  17816. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17817. data.hierarchy[ h ].keys[ k ].time = 0;
  17818. // create quaternions
  17819. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17820. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17821. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17822. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17823. }
  17824. }
  17825. // prepare morph target keys
  17826. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17827. // get all used
  17828. var usedMorphTargets = {};
  17829. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17830. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17831. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17832. usedMorphTargets[ morphTargetName ] = -1;
  17833. }
  17834. }
  17835. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17836. // set all used on all frames
  17837. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17838. var influences = {};
  17839. for ( var morphTargetName in usedMorphTargets ) {
  17840. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17841. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17842. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17843. break;
  17844. }
  17845. }
  17846. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17847. influences[ morphTargetName ] = 0;
  17848. }
  17849. }
  17850. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17851. }
  17852. }
  17853. // remove all keys that are on the same time
  17854. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17855. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17856. data.hierarchy[ h ].keys.splice( k, 1 );
  17857. k --;
  17858. }
  17859. }
  17860. // set index
  17861. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17862. data.hierarchy[ h ].keys[ k ].index = k;
  17863. }
  17864. }
  17865. // JIT
  17866. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17867. data.JIT = {};
  17868. data.JIT.hierarchy = [];
  17869. for( var h = 0; h < data.hierarchy.length; h ++ )
  17870. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17871. // done
  17872. data.initialized = true;
  17873. };
  17874. // interpolation types
  17875. that.LINEAR = 0;
  17876. that.CATMULLROM = 1;
  17877. that.CATMULLROM_FORWARD = 2;
  17878. return that;
  17879. }());
  17880. /**
  17881. * @author mikael emtinger / http://gomo.se/
  17882. * @author mrdoob / http://mrdoob.com/
  17883. * @author alteredq / http://alteredqualia.com/
  17884. */
  17885. THREE.Animation = function ( root, name, interpolationType ) {
  17886. this.root = root;
  17887. this.data = THREE.AnimationHandler.get( name );
  17888. this.hierarchy = THREE.AnimationHandler.parse( root );
  17889. this.currentTime = 0;
  17890. this.timeScale = 1;
  17891. this.isPlaying = false;
  17892. this.isPaused = true;
  17893. this.loop = true;
  17894. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17895. this.points = [];
  17896. this.target = new THREE.Vector3();
  17897. };
  17898. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17899. if ( this.isPlaying === false ) {
  17900. this.isPlaying = true;
  17901. this.loop = loop !== undefined ? loop : true;
  17902. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17903. // reset key cache
  17904. var h, hl = this.hierarchy.length,
  17905. object;
  17906. for ( h = 0; h < hl; h ++ ) {
  17907. object = this.hierarchy[ h ];
  17908. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17909. object.useQuaternion = true;
  17910. }
  17911. object.matrixAutoUpdate = true;
  17912. if ( object.animationCache === undefined ) {
  17913. object.animationCache = {};
  17914. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17915. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17916. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17917. }
  17918. var prevKey = object.animationCache.prevKey;
  17919. var nextKey = object.animationCache.nextKey;
  17920. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17921. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17922. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17923. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17924. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17925. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17926. }
  17927. this.update( 0 );
  17928. }
  17929. this.isPaused = false;
  17930. THREE.AnimationHandler.addToUpdate( this );
  17931. };
  17932. THREE.Animation.prototype.pause = function() {
  17933. if ( this.isPaused === true ) {
  17934. THREE.AnimationHandler.addToUpdate( this );
  17935. } else {
  17936. THREE.AnimationHandler.removeFromUpdate( this );
  17937. }
  17938. this.isPaused = !this.isPaused;
  17939. };
  17940. THREE.Animation.prototype.stop = function() {
  17941. this.isPlaying = false;
  17942. this.isPaused = false;
  17943. THREE.AnimationHandler.removeFromUpdate( this );
  17944. };
  17945. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17946. // early out
  17947. if ( this.isPlaying === false ) return;
  17948. // vars
  17949. var types = [ "pos", "rot", "scl" ];
  17950. var type;
  17951. var scale;
  17952. var vector;
  17953. var prevXYZ, nextXYZ;
  17954. var prevKey, nextKey;
  17955. var object;
  17956. var animationCache;
  17957. var frame;
  17958. var JIThierarchy = this.data.JIT.hierarchy;
  17959. var currentTime, unloopedCurrentTime;
  17960. var currentPoint, forwardPoint, angle;
  17961. this.currentTime += deltaTimeMS * this.timeScale;
  17962. unloopedCurrentTime = this.currentTime;
  17963. currentTime = this.currentTime = this.currentTime % this.data.length;
  17964. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17965. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17966. object = this.hierarchy[ h ];
  17967. animationCache = object.animationCache;
  17968. // loop through pos/rot/scl
  17969. for ( var t = 0; t < 3; t ++ ) {
  17970. // get keys
  17971. type = types[ t ];
  17972. prevKey = animationCache.prevKey[ type ];
  17973. nextKey = animationCache.nextKey[ type ];
  17974. // switch keys?
  17975. if ( nextKey.time <= unloopedCurrentTime ) {
  17976. // did we loop?
  17977. if ( currentTime < unloopedCurrentTime ) {
  17978. if ( this.loop ) {
  17979. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17980. nextKey = this.getNextKeyWith( type, h, 1 );
  17981. while( nextKey.time < currentTime ) {
  17982. prevKey = nextKey;
  17983. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17984. }
  17985. } else {
  17986. this.stop();
  17987. return;
  17988. }
  17989. } else {
  17990. do {
  17991. prevKey = nextKey;
  17992. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17993. } while( nextKey.time < currentTime )
  17994. }
  17995. animationCache.prevKey[ type ] = prevKey;
  17996. animationCache.nextKey[ type ] = nextKey;
  17997. }
  17998. object.matrixAutoUpdate = true;
  17999. object.matrixWorldNeedsUpdate = true;
  18000. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18001. prevXYZ = prevKey[ type ];
  18002. nextXYZ = nextKey[ type ];
  18003. // check scale error
  18004. if ( scale < 0 || scale > 1 ) {
  18005. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18006. scale = scale < 0 ? 0 : 1;
  18007. }
  18008. // interpolate
  18009. if ( type === "pos" ) {
  18010. vector = object.position;
  18011. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18012. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18013. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18014. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18015. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18016. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18017. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18018. this.points[ 1 ] = prevXYZ;
  18019. this.points[ 2 ] = nextXYZ;
  18020. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18021. scale = scale * 0.33 + 0.33;
  18022. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18023. vector.x = currentPoint[ 0 ];
  18024. vector.y = currentPoint[ 1 ];
  18025. vector.z = currentPoint[ 2 ];
  18026. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18027. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18028. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18029. this.target.sub( vector );
  18030. this.target.y = 0;
  18031. this.target.normalize();
  18032. angle = Math.atan2( this.target.x, this.target.z );
  18033. object.rotation.set( 0, angle, 0 );
  18034. }
  18035. }
  18036. } else if ( type === "rot" ) {
  18037. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18038. } else if ( type === "scl" ) {
  18039. vector = object.scale;
  18040. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18041. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18042. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18043. }
  18044. }
  18045. }
  18046. };
  18047. // Catmull-Rom spline
  18048. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18049. var c = [], v3 = [],
  18050. point, intPoint, weight, w2, w3,
  18051. pa, pb, pc, pd;
  18052. point = ( points.length - 1 ) * scale;
  18053. intPoint = Math.floor( point );
  18054. weight = point - intPoint;
  18055. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18056. c[ 1 ] = intPoint;
  18057. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18058. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18059. pa = points[ c[ 0 ] ];
  18060. pb = points[ c[ 1 ] ];
  18061. pc = points[ c[ 2 ] ];
  18062. pd = points[ c[ 3 ] ];
  18063. w2 = weight * weight;
  18064. w3 = weight * w2;
  18065. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18066. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18067. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18068. return v3;
  18069. };
  18070. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18071. var v0 = ( p2 - p0 ) * 0.5,
  18072. v1 = ( p3 - p1 ) * 0.5;
  18073. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18074. };
  18075. // Get next key with
  18076. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18077. var keys = this.data.hierarchy[ h ].keys;
  18078. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18079. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18080. key = key < keys.length - 1 ? key : keys.length - 1;
  18081. } else {
  18082. key = key % keys.length;
  18083. }
  18084. for ( ; key < keys.length; key++ ) {
  18085. if ( keys[ key ][ type ] !== undefined ) {
  18086. return keys[ key ];
  18087. }
  18088. }
  18089. return this.data.hierarchy[ h ].keys[ 0 ];
  18090. };
  18091. // Get previous key with
  18092. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18093. var keys = this.data.hierarchy[ h ].keys;
  18094. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18095. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18096. key = key > 0 ? key : 0;
  18097. } else {
  18098. key = key >= 0 ? key : key + keys.length;
  18099. }
  18100. for ( ; key >= 0; key -- ) {
  18101. if ( keys[ key ][ type ] !== undefined ) {
  18102. return keys[ key ];
  18103. }
  18104. }
  18105. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18106. };
  18107. /**
  18108. * @author mikael emtinger / http://gomo.se/
  18109. * @author mrdoob / http://mrdoob.com/
  18110. * @author alteredq / http://alteredqualia.com/
  18111. * @author khang duong
  18112. * @author erik kitson
  18113. */
  18114. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18115. this.root = root;
  18116. this.data = THREE.AnimationHandler.get( data );
  18117. this.hierarchy = THREE.AnimationHandler.parse( root );
  18118. this.currentTime = 0;
  18119. this.timeScale = 0.001;
  18120. this.isPlaying = false;
  18121. this.isPaused = true;
  18122. this.loop = true;
  18123. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18124. // initialize to first keyframes
  18125. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18126. var keys = this.data.hierarchy[h].keys,
  18127. sids = this.data.hierarchy[h].sids,
  18128. obj = this.hierarchy[h];
  18129. if ( keys.length && sids ) {
  18130. for ( var s = 0; s < sids.length; s++ ) {
  18131. var sid = sids[ s ],
  18132. next = this.getNextKeyWith( sid, h, 0 );
  18133. if ( next ) {
  18134. next.apply( sid );
  18135. }
  18136. }
  18137. obj.matrixAutoUpdate = false;
  18138. this.data.hierarchy[h].node.updateMatrix();
  18139. obj.matrixWorldNeedsUpdate = true;
  18140. }
  18141. }
  18142. };
  18143. // Play
  18144. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18145. if( !this.isPlaying ) {
  18146. this.isPlaying = true;
  18147. this.loop = loop !== undefined ? loop : true;
  18148. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18149. this.startTimeMs = startTimeMS;
  18150. this.startTime = 10000000;
  18151. this.endTime = -this.startTime;
  18152. // reset key cache
  18153. var h, hl = this.hierarchy.length,
  18154. object,
  18155. node;
  18156. for ( h = 0; h < hl; h++ ) {
  18157. object = this.hierarchy[ h ];
  18158. node = this.data.hierarchy[ h ];
  18159. object.useQuaternion = true;
  18160. if ( node.animationCache === undefined ) {
  18161. node.animationCache = {};
  18162. node.animationCache.prevKey = null;
  18163. node.animationCache.nextKey = null;
  18164. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18165. }
  18166. var keys = this.data.hierarchy[h].keys;
  18167. if (keys.length) {
  18168. node.animationCache.prevKey = keys[ 0 ];
  18169. node.animationCache.nextKey = keys[ 1 ];
  18170. this.startTime = Math.min( keys[0].time, this.startTime );
  18171. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18172. }
  18173. }
  18174. this.update( 0 );
  18175. }
  18176. this.isPaused = false;
  18177. THREE.AnimationHandler.addToUpdate( this );
  18178. };
  18179. // Pause
  18180. THREE.KeyFrameAnimation.prototype.pause = function() {
  18181. if( this.isPaused ) {
  18182. THREE.AnimationHandler.addToUpdate( this );
  18183. } else {
  18184. THREE.AnimationHandler.removeFromUpdate( this );
  18185. }
  18186. this.isPaused = !this.isPaused;
  18187. };
  18188. // Stop
  18189. THREE.KeyFrameAnimation.prototype.stop = function() {
  18190. this.isPlaying = false;
  18191. this.isPaused = false;
  18192. THREE.AnimationHandler.removeFromUpdate( this );
  18193. // reset JIT matrix and remove cache
  18194. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18195. var obj = this.hierarchy[ h ];
  18196. var node = this.data.hierarchy[ h ];
  18197. if ( node.animationCache !== undefined ) {
  18198. var original = node.animationCache.originalMatrix;
  18199. if( obj instanceof THREE.Bone ) {
  18200. original.copy( obj.skinMatrix );
  18201. obj.skinMatrix = original;
  18202. } else {
  18203. original.copy( obj.matrix );
  18204. obj.matrix = original;
  18205. }
  18206. delete node.animationCache;
  18207. }
  18208. }
  18209. };
  18210. // Update
  18211. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18212. // early out
  18213. if( !this.isPlaying ) return;
  18214. // vars
  18215. var prevKey, nextKey;
  18216. var object;
  18217. var node;
  18218. var frame;
  18219. var JIThierarchy = this.data.JIT.hierarchy;
  18220. var currentTime, unloopedCurrentTime;
  18221. var looped;
  18222. // update
  18223. this.currentTime += deltaTimeMS * this.timeScale;
  18224. unloopedCurrentTime = this.currentTime;
  18225. currentTime = this.currentTime = this.currentTime % this.data.length;
  18226. // if looped around, the current time should be based on the startTime
  18227. if ( currentTime < this.startTimeMs ) {
  18228. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18229. }
  18230. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18231. looped = currentTime < unloopedCurrentTime;
  18232. if ( looped && !this.loop ) {
  18233. // Set the animation to the last keyframes and stop
  18234. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18235. var keys = this.data.hierarchy[h].keys,
  18236. sids = this.data.hierarchy[h].sids,
  18237. end = keys.length-1,
  18238. obj = this.hierarchy[h];
  18239. if ( keys.length ) {
  18240. for ( var s = 0; s < sids.length; s++ ) {
  18241. var sid = sids[ s ],
  18242. prev = this.getPrevKeyWith( sid, h, end );
  18243. if ( prev ) {
  18244. prev.apply( sid );
  18245. }
  18246. }
  18247. this.data.hierarchy[h].node.updateMatrix();
  18248. obj.matrixWorldNeedsUpdate = true;
  18249. }
  18250. }
  18251. this.stop();
  18252. return;
  18253. }
  18254. // check pre-infinity
  18255. if ( currentTime < this.startTime ) {
  18256. return;
  18257. }
  18258. // update
  18259. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18260. object = this.hierarchy[ h ];
  18261. node = this.data.hierarchy[ h ];
  18262. var keys = node.keys,
  18263. animationCache = node.animationCache;
  18264. // use JIT?
  18265. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18266. if( object instanceof THREE.Bone ) {
  18267. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18268. object.matrixWorldNeedsUpdate = false;
  18269. } else {
  18270. object.matrix = JIThierarchy[ h ][ frame ];
  18271. object.matrixWorldNeedsUpdate = true;
  18272. }
  18273. // use interpolation
  18274. } else if ( keys.length ) {
  18275. // make sure so original matrix and not JIT matrix is set
  18276. if ( this.JITCompile && animationCache ) {
  18277. if( object instanceof THREE.Bone ) {
  18278. object.skinMatrix = animationCache.originalMatrix;
  18279. } else {
  18280. object.matrix = animationCache.originalMatrix;
  18281. }
  18282. }
  18283. prevKey = animationCache.prevKey;
  18284. nextKey = animationCache.nextKey;
  18285. if ( prevKey && nextKey ) {
  18286. // switch keys?
  18287. if ( nextKey.time <= unloopedCurrentTime ) {
  18288. // did we loop?
  18289. if ( looped && this.loop ) {
  18290. prevKey = keys[ 0 ];
  18291. nextKey = keys[ 1 ];
  18292. while ( nextKey.time < currentTime ) {
  18293. prevKey = nextKey;
  18294. nextKey = keys[ prevKey.index + 1 ];
  18295. }
  18296. } else if ( !looped ) {
  18297. var lastIndex = keys.length - 1;
  18298. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18299. prevKey = nextKey;
  18300. nextKey = keys[ prevKey.index + 1 ];
  18301. }
  18302. }
  18303. animationCache.prevKey = prevKey;
  18304. animationCache.nextKey = nextKey;
  18305. }
  18306. if(nextKey.time >= currentTime)
  18307. prevKey.interpolate( nextKey, currentTime );
  18308. else
  18309. prevKey.interpolate( nextKey, nextKey.time);
  18310. }
  18311. this.data.hierarchy[h].node.updateMatrix();
  18312. object.matrixWorldNeedsUpdate = true;
  18313. }
  18314. }
  18315. // update JIT?
  18316. if ( this.JITCompile ) {
  18317. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18318. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18319. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18320. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18321. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18322. } else {
  18323. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18324. }
  18325. }
  18326. }
  18327. }
  18328. };
  18329. // Get next key with
  18330. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18331. var keys = this.data.hierarchy[ h ].keys;
  18332. key = key % keys.length;
  18333. for ( ; key < keys.length; key++ ) {
  18334. if ( keys[ key ].hasTarget( sid ) ) {
  18335. return keys[ key ];
  18336. }
  18337. }
  18338. return keys[ 0 ];
  18339. };
  18340. // Get previous key with
  18341. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18342. var keys = this.data.hierarchy[ h ].keys;
  18343. key = key >= 0 ? key : key + keys.length;
  18344. for ( ; key >= 0; key-- ) {
  18345. if ( keys[ key ].hasTarget( sid ) ) {
  18346. return keys[ key ];
  18347. }
  18348. }
  18349. return keys[ keys.length - 1 ];
  18350. };
  18351. /**
  18352. * Camera for rendering cube maps
  18353. * - renders scene into axis-aligned cube
  18354. *
  18355. * @author alteredq / http://alteredqualia.com/
  18356. */
  18357. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18358. THREE.Object3D.call( this );
  18359. var fov = 90, aspect = 1;
  18360. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18361. cameraPX.up.set( 0, -1, 0 );
  18362. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18363. this.add( cameraPX );
  18364. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18365. cameraNX.up.set( 0, -1, 0 );
  18366. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18367. this.add( cameraNX );
  18368. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18369. cameraPY.up.set( 0, 0, 1 );
  18370. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18371. this.add( cameraPY );
  18372. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18373. cameraNY.up.set( 0, 0, -1 );
  18374. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18375. this.add( cameraNY );
  18376. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18377. cameraPZ.up.set( 0, -1, 0 );
  18378. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18379. this.add( cameraPZ );
  18380. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18381. cameraNZ.up.set( 0, -1, 0 );
  18382. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18383. this.add( cameraNZ );
  18384. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18385. this.updateCubeMap = function ( renderer, scene ) {
  18386. var renderTarget = this.renderTarget;
  18387. var generateMipmaps = renderTarget.generateMipmaps;
  18388. renderTarget.generateMipmaps = false;
  18389. renderTarget.activeCubeFace = 0;
  18390. renderer.render( scene, cameraPX, renderTarget );
  18391. renderTarget.activeCubeFace = 1;
  18392. renderer.render( scene, cameraNX, renderTarget );
  18393. renderTarget.activeCubeFace = 2;
  18394. renderer.render( scene, cameraPY, renderTarget );
  18395. renderTarget.activeCubeFace = 3;
  18396. renderer.render( scene, cameraNY, renderTarget );
  18397. renderTarget.activeCubeFace = 4;
  18398. renderer.render( scene, cameraPZ, renderTarget );
  18399. renderTarget.generateMipmaps = generateMipmaps;
  18400. renderTarget.activeCubeFace = 5;
  18401. renderer.render( scene, cameraNZ, renderTarget );
  18402. };
  18403. };
  18404. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18405. /*
  18406. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18407. *
  18408. * A general perpose camera, for setting FOV, Lens Focal Length,
  18409. * and switching between perspective and orthographic views easily.
  18410. * Use this only if you do not wish to manage
  18411. * both a Orthographic and Perspective Camera
  18412. *
  18413. */
  18414. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18415. THREE.Camera.call( this );
  18416. this.fov = fov;
  18417. this.left = -width / 2;
  18418. this.right = width / 2
  18419. this.top = height / 2;
  18420. this.bottom = -height / 2;
  18421. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18422. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18423. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18424. this.zoom = 1;
  18425. this.toPerspective();
  18426. var aspect = width/height;
  18427. };
  18428. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18429. THREE.CombinedCamera.prototype.toPerspective = function () {
  18430. // Switches to the Perspective Camera
  18431. this.near = this.cameraP.near;
  18432. this.far = this.cameraP.far;
  18433. this.cameraP.fov = this.fov / this.zoom ;
  18434. this.cameraP.updateProjectionMatrix();
  18435. this.projectionMatrix = this.cameraP.projectionMatrix;
  18436. this.inPerspectiveMode = true;
  18437. this.inOrthographicMode = false;
  18438. };
  18439. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18440. // Switches to the Orthographic camera estimating viewport from Perspective
  18441. var fov = this.fov;
  18442. var aspect = this.cameraP.aspect;
  18443. var near = this.cameraP.near;
  18444. var far = this.cameraP.far;
  18445. // The size that we set is the mid plane of the viewing frustum
  18446. var hyperfocus = ( near + far ) / 2;
  18447. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18448. var planeHeight = 2 * halfHeight;
  18449. var planeWidth = planeHeight * aspect;
  18450. var halfWidth = planeWidth / 2;
  18451. halfHeight /= this.zoom;
  18452. halfWidth /= this.zoom;
  18453. this.cameraO.left = -halfWidth;
  18454. this.cameraO.right = halfWidth;
  18455. this.cameraO.top = halfHeight;
  18456. this.cameraO.bottom = -halfHeight;
  18457. // this.cameraO.left = -farHalfWidth;
  18458. // this.cameraO.right = farHalfWidth;
  18459. // this.cameraO.top = farHalfHeight;
  18460. // this.cameraO.bottom = -farHalfHeight;
  18461. // this.cameraO.left = this.left / this.zoom;
  18462. // this.cameraO.right = this.right / this.zoom;
  18463. // this.cameraO.top = this.top / this.zoom;
  18464. // this.cameraO.bottom = this.bottom / this.zoom;
  18465. this.cameraO.updateProjectionMatrix();
  18466. this.near = this.cameraO.near;
  18467. this.far = this.cameraO.far;
  18468. this.projectionMatrix = this.cameraO.projectionMatrix;
  18469. this.inPerspectiveMode = false;
  18470. this.inOrthographicMode = true;
  18471. };
  18472. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18473. this.cameraP.aspect = width / height;
  18474. this.left = -width / 2;
  18475. this.right = width / 2
  18476. this.top = height / 2;
  18477. this.bottom = -height / 2;
  18478. };
  18479. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18480. this.fov = fov;
  18481. if ( this.inPerspectiveMode ) {
  18482. this.toPerspective();
  18483. } else {
  18484. this.toOrthographic();
  18485. }
  18486. };
  18487. // For mantaining similar API with PerspectiveCamera
  18488. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18489. if ( this.inPerspectiveMode ) {
  18490. this.toPerspective();
  18491. } else {
  18492. this.toPerspective();
  18493. this.toOrthographic();
  18494. }
  18495. };
  18496. /*
  18497. * Uses Focal Length (in mm) to estimate and set FOV
  18498. * 35mm (fullframe) camera is used if frame size is not specified;
  18499. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18500. */
  18501. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18502. if ( frameHeight === undefined ) frameHeight = 24;
  18503. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18504. this.setFov( fov );
  18505. return fov;
  18506. };
  18507. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18508. this.zoom = zoom;
  18509. if ( this.inPerspectiveMode ) {
  18510. this.toPerspective();
  18511. } else {
  18512. this.toOrthographic();
  18513. }
  18514. };
  18515. THREE.CombinedCamera.prototype.toFrontView = function() {
  18516. this.rotation.x = 0;
  18517. this.rotation.y = 0;
  18518. this.rotation.z = 0;
  18519. // should we be modifing the matrix instead?
  18520. this.rotationAutoUpdate = false;
  18521. };
  18522. THREE.CombinedCamera.prototype.toBackView = function() {
  18523. this.rotation.x = 0;
  18524. this.rotation.y = Math.PI;
  18525. this.rotation.z = 0;
  18526. this.rotationAutoUpdate = false;
  18527. };
  18528. THREE.CombinedCamera.prototype.toLeftView = function() {
  18529. this.rotation.x = 0;
  18530. this.rotation.y = - Math.PI / 2;
  18531. this.rotation.z = 0;
  18532. this.rotationAutoUpdate = false;
  18533. };
  18534. THREE.CombinedCamera.prototype.toRightView = function() {
  18535. this.rotation.x = 0;
  18536. this.rotation.y = Math.PI / 2;
  18537. this.rotation.z = 0;
  18538. this.rotationAutoUpdate = false;
  18539. };
  18540. THREE.CombinedCamera.prototype.toTopView = function() {
  18541. this.rotation.x = - Math.PI / 2;
  18542. this.rotation.y = 0;
  18543. this.rotation.z = 0;
  18544. this.rotationAutoUpdate = false;
  18545. };
  18546. THREE.CombinedCamera.prototype.toBottomView = function() {
  18547. this.rotation.x = Math.PI / 2;
  18548. this.rotation.y = 0;
  18549. this.rotation.z = 0;
  18550. this.rotationAutoUpdate = false;
  18551. };
  18552. /**
  18553. * @author hughes
  18554. */
  18555. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18556. THREE.Geometry.call( this );
  18557. radius = radius || 50;
  18558. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18559. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18560. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18561. var i, uvs = [],
  18562. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18563. this.vertices.push(center);
  18564. uvs.push( centerUV );
  18565. for ( i = 0; i <= segments; i ++ ) {
  18566. var vertex = new THREE.Vector3();
  18567. var segment = thetaStart + i / segments * thetaLength;
  18568. vertex.x = radius * Math.cos( segment );
  18569. vertex.y = radius * Math.sin( segment );
  18570. this.vertices.push( vertex );
  18571. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18572. }
  18573. var n = new THREE.Vector3( 0, 0, 1 );
  18574. for ( i = 1; i <= segments; i ++ ) {
  18575. var v1 = i;
  18576. var v2 = i + 1 ;
  18577. var v3 = 0;
  18578. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18579. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18580. }
  18581. this.computeCentroids();
  18582. this.computeFaceNormals();
  18583. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18584. };
  18585. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18586. /**
  18587. * @author mrdoob / http://mrdoob.com/
  18588. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18589. */
  18590. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18591. THREE.Geometry.call( this );
  18592. var scope = this;
  18593. this.width = width;
  18594. this.height = height;
  18595. this.depth = depth;
  18596. this.widthSegments = widthSegments || 1;
  18597. this.heightSegments = heightSegments || 1;
  18598. this.depthSegments = depthSegments || 1;
  18599. var width_half = this.width / 2;
  18600. var height_half = this.height / 2;
  18601. var depth_half = this.depth / 2;
  18602. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18603. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18604. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18605. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18606. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18607. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18608. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18609. var w, ix, iy,
  18610. gridX = scope.widthSegments,
  18611. gridY = scope.heightSegments,
  18612. width_half = width / 2,
  18613. height_half = height / 2,
  18614. offset = scope.vertices.length;
  18615. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18616. w = 'z';
  18617. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18618. w = 'y';
  18619. gridY = scope.depthSegments;
  18620. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18621. w = 'x';
  18622. gridX = scope.depthSegments;
  18623. }
  18624. var gridX1 = gridX + 1,
  18625. gridY1 = gridY + 1,
  18626. segment_width = width / gridX,
  18627. segment_height = height / gridY,
  18628. normal = new THREE.Vector3();
  18629. normal[ w ] = depth > 0 ? 1 : - 1;
  18630. for ( iy = 0; iy < gridY1; iy ++ ) {
  18631. for ( ix = 0; ix < gridX1; ix ++ ) {
  18632. var vector = new THREE.Vector3();
  18633. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18634. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18635. vector[ w ] = depth;
  18636. scope.vertices.push( vector );
  18637. }
  18638. }
  18639. for ( iy = 0; iy < gridY; iy++ ) {
  18640. for ( ix = 0; ix < gridX; ix++ ) {
  18641. var a = ix + gridX1 * iy;
  18642. var b = ix + gridX1 * ( iy + 1 );
  18643. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18644. var d = ( ix + 1 ) + gridX1 * iy;
  18645. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18646. face.normal.copy( normal );
  18647. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18648. face.materialIndex = materialIndex;
  18649. scope.faces.push( face );
  18650. scope.faceVertexUvs[ 0 ].push( [
  18651. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18652. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18653. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18654. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18655. ] );
  18656. }
  18657. }
  18658. }
  18659. this.computeCentroids();
  18660. this.mergeVertices();
  18661. };
  18662. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18663. /**
  18664. * @author mrdoob / http://mrdoob.com/
  18665. */
  18666. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18667. THREE.Geometry.call( this );
  18668. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18669. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18670. this.height = height = height !== undefined ? height : 100;
  18671. this.radiusSegments = radiusSegments = radiusSegments || 8;
  18672. this.heightSegments = heightSegments = heightSegments || 1;
  18673. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18674. var heightHalf = height / 2;
  18675. var x, y, vertices = [], uvs = [];
  18676. for ( y = 0; y <= heightSegments; y ++ ) {
  18677. var verticesRow = [];
  18678. var uvsRow = [];
  18679. var v = y / heightSegments;
  18680. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18681. for ( x = 0; x <= radiusSegments; x ++ ) {
  18682. var u = x / radiusSegments;
  18683. var vertex = new THREE.Vector3();
  18684. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18685. vertex.y = - v * height + heightHalf;
  18686. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18687. this.vertices.push( vertex );
  18688. verticesRow.push( this.vertices.length - 1 );
  18689. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18690. }
  18691. vertices.push( verticesRow );
  18692. uvs.push( uvsRow );
  18693. }
  18694. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18695. var na, nb;
  18696. for ( x = 0; x < radiusSegments; x ++ ) {
  18697. if ( radiusTop !== 0 ) {
  18698. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18699. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18700. } else {
  18701. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18702. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18703. }
  18704. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18705. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18706. for ( y = 0; y < heightSegments; y ++ ) {
  18707. var v1 = vertices[ y ][ x ];
  18708. var v2 = vertices[ y + 1 ][ x ];
  18709. var v3 = vertices[ y + 1 ][ x + 1 ];
  18710. var v4 = vertices[ y ][ x + 1 ];
  18711. var n1 = na.clone();
  18712. var n2 = na.clone();
  18713. var n3 = nb.clone();
  18714. var n4 = nb.clone();
  18715. var uv1 = uvs[ y ][ x ].clone();
  18716. var uv2 = uvs[ y + 1 ][ x ].clone();
  18717. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18718. var uv4 = uvs[ y ][ x + 1 ].clone();
  18719. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18720. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18721. }
  18722. }
  18723. // top cap
  18724. if ( openEnded === false && radiusTop > 0 ) {
  18725. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18726. for ( x = 0; x < radiusSegments; x ++ ) {
  18727. var v1 = vertices[ 0 ][ x ];
  18728. var v2 = vertices[ 0 ][ x + 1 ];
  18729. var v3 = this.vertices.length - 1;
  18730. var n1 = new THREE.Vector3( 0, 1, 0 );
  18731. var n2 = new THREE.Vector3( 0, 1, 0 );
  18732. var n3 = new THREE.Vector3( 0, 1, 0 );
  18733. var uv1 = uvs[ 0 ][ x ].clone();
  18734. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18735. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18736. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18737. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18738. }
  18739. }
  18740. // bottom cap
  18741. if ( openEnded === false && radiusBottom > 0 ) {
  18742. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18743. for ( x = 0; x < radiusSegments; x ++ ) {
  18744. var v1 = vertices[ y ][ x + 1 ];
  18745. var v2 = vertices[ y ][ x ];
  18746. var v3 = this.vertices.length - 1;
  18747. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18748. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18749. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18750. var uv1 = uvs[ y ][ x + 1 ].clone();
  18751. var uv2 = uvs[ y ][ x ].clone();
  18752. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18753. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18754. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18755. }
  18756. }
  18757. this.computeCentroids();
  18758. this.computeFaceNormals();
  18759. }
  18760. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18761. /**
  18762. * @author zz85 / http://www.lab4games.net/zz85/blog
  18763. *
  18764. * Creates extruded geometry from a path shape.
  18765. *
  18766. * parameters = {
  18767. *
  18768. * size: <float>, // size of the text
  18769. * height: <float>, // thickness to extrude text
  18770. * curveSegments: <int>, // number of points on the curves
  18771. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18772. * amount: <int>, // Amount
  18773. *
  18774. * bevelEnabled: <bool>, // turn on bevel
  18775. * bevelThickness: <float>, // how deep into text bevel goes
  18776. * bevelSize: <float>, // how far from text outline is bevel
  18777. * bevelSegments: <int>, // number of bevel layers
  18778. *
  18779. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18780. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18781. *
  18782. * material: <int> // material index for front and back faces
  18783. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18784. * uvGenerator: <Object> // object that provides UV generator functions
  18785. *
  18786. * }
  18787. **/
  18788. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18789. if ( typeof( shapes ) === "undefined" ) {
  18790. shapes = [];
  18791. return;
  18792. }
  18793. THREE.Geometry.call( this );
  18794. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18795. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18796. this.addShapeList( shapes, options );
  18797. this.computeCentroids();
  18798. this.computeFaceNormals();
  18799. // can't really use automatic vertex normals
  18800. // as then front and back sides get smoothed too
  18801. // should do separate smoothing just for sides
  18802. //this.computeVertexNormals();
  18803. //console.log( "took", ( Date.now() - startTime ) );
  18804. };
  18805. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18806. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18807. var sl = shapes.length;
  18808. for ( var s = 0; s < sl; s ++ ) {
  18809. var shape = shapes[ s ];
  18810. this.addShape( shape, options );
  18811. }
  18812. };
  18813. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18814. var amount = options.amount !== undefined ? options.amount : 100;
  18815. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18816. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18817. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18818. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18819. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18820. var steps = options.steps !== undefined ? options.steps : 1;
  18821. var extrudePath = options.extrudePath;
  18822. var extrudePts, extrudeByPath = false;
  18823. var material = options.material;
  18824. var extrudeMaterial = options.extrudeMaterial;
  18825. // Use default WorldUVGenerator if no UV generators are specified.
  18826. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18827. var shapebb = this.shapebb;
  18828. //shapebb = shape.getBoundingBox();
  18829. var splineTube, binormal, normal, position2;
  18830. if ( extrudePath ) {
  18831. extrudePts = extrudePath.getSpacedPoints( steps );
  18832. extrudeByPath = true;
  18833. bevelEnabled = false; // bevels not supported for path extrusion
  18834. // SETUP TNB variables
  18835. // Reuse TNB from TubeGeomtry for now.
  18836. // TODO1 - have a .isClosed in spline?
  18837. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18838. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18839. binormal = new THREE.Vector3();
  18840. normal = new THREE.Vector3();
  18841. position2 = new THREE.Vector3();
  18842. }
  18843. // Safeguards if bevels are not enabled
  18844. if ( ! bevelEnabled ) {
  18845. bevelSegments = 0;
  18846. bevelThickness = 0;
  18847. bevelSize = 0;
  18848. }
  18849. // Variables initalization
  18850. var ahole, h, hl; // looping of holes
  18851. var scope = this;
  18852. var bevelPoints = [];
  18853. var shapesOffset = this.vertices.length;
  18854. var shapePoints = shape.extractPoints( curveSegments );
  18855. var vertices = shapePoints.shape;
  18856. var holes = shapePoints.holes;
  18857. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18858. if ( reverse ) {
  18859. vertices = vertices.reverse();
  18860. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18861. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18862. ahole = holes[ h ];
  18863. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18864. holes[ h ] = ahole.reverse();
  18865. }
  18866. }
  18867. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18868. }
  18869. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18870. /* Vertices */
  18871. var contour = vertices; // vertices has all points but contour has only points of circumference
  18872. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18873. ahole = holes[ h ];
  18874. vertices = vertices.concat( ahole );
  18875. }
  18876. function scalePt2 ( pt, vec, size ) {
  18877. if ( !vec ) console.log( "die" );
  18878. return vec.clone().multiplyScalar( size ).add( pt );
  18879. }
  18880. var b, bs, t, z,
  18881. vert, vlen = vertices.length,
  18882. face, flen = faces.length,
  18883. cont, clen = contour.length;
  18884. // Find directions for point movement
  18885. var RAD_TO_DEGREES = 180 / Math.PI;
  18886. function getBevelVec( pt_i, pt_j, pt_k ) {
  18887. // Algorithm 2
  18888. return getBevelVec2( pt_i, pt_j, pt_k );
  18889. }
  18890. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18891. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18892. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18893. if ( anglea > angleb ) {
  18894. angleb += Math.PI * 2;
  18895. }
  18896. var anglec = ( anglea + angleb ) / 2;
  18897. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18898. var x = - Math.cos( anglec );
  18899. var y = - Math.sin( anglec );
  18900. var vec = new THREE.Vector2( x, y ); //.normalize();
  18901. return vec;
  18902. }
  18903. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18904. var a = THREE.ExtrudeGeometry.__v1,
  18905. b = THREE.ExtrudeGeometry.__v2,
  18906. v_hat = THREE.ExtrudeGeometry.__v3,
  18907. w_hat = THREE.ExtrudeGeometry.__v4,
  18908. p = THREE.ExtrudeGeometry.__v5,
  18909. q = THREE.ExtrudeGeometry.__v6,
  18910. v, w,
  18911. v_dot_w_hat, q_sub_p_dot_w_hat,
  18912. s, intersection;
  18913. // good reading for line-line intersection
  18914. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18915. // define a as vector j->i
  18916. // define b as vectot k->i
  18917. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18918. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18919. // get unit vectors
  18920. v = a.normalize();
  18921. w = b.normalize();
  18922. // normals from pt i
  18923. v_hat.set( -v.y, v.x );
  18924. w_hat.set( w.y, -w.x );
  18925. // pts from i
  18926. p.copy( pt_i ).add( v_hat );
  18927. q.copy( pt_i ).add( w_hat );
  18928. if ( p.equals( q ) ) {
  18929. //console.log("Warning: lines are straight");
  18930. return w_hat.clone();
  18931. }
  18932. // Points from j, k. helps prevents points cross overover most of the time
  18933. p.copy( pt_j ).add( v_hat );
  18934. q.copy( pt_k ).add( w_hat );
  18935. v_dot_w_hat = v.dot( w_hat );
  18936. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18937. // We should not reach these conditions
  18938. if ( v_dot_w_hat === 0 ) {
  18939. console.log( "Either infinite or no solutions!" );
  18940. if ( q_sub_p_dot_w_hat === 0 ) {
  18941. console.log( "Its finite solutions." );
  18942. } else {
  18943. console.log( "Too bad, no solutions." );
  18944. }
  18945. }
  18946. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18947. if ( s < 0 ) {
  18948. // in case of emergecy, revert to algorithm 1.
  18949. return getBevelVec1( pt_i, pt_j, pt_k );
  18950. }
  18951. intersection = v.multiplyScalar( s ).add( p );
  18952. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18953. }
  18954. var contourMovements = [];
  18955. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18956. if ( j === il ) j = 0;
  18957. if ( k === il ) k = 0;
  18958. // (j)---(i)---(k)
  18959. // console.log('i,j,k', i, j , k)
  18960. var pt_i = contour[ i ];
  18961. var pt_j = contour[ j ];
  18962. var pt_k = contour[ k ];
  18963. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18964. }
  18965. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18966. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18967. ahole = holes[ h ];
  18968. oneHoleMovements = [];
  18969. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18970. if ( j === il ) j = 0;
  18971. if ( k === il ) k = 0;
  18972. // (j)---(i)---(k)
  18973. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18974. }
  18975. holesMovements.push( oneHoleMovements );
  18976. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18977. }
  18978. // Loop bevelSegments, 1 for the front, 1 for the back
  18979. for ( b = 0; b < bevelSegments; b ++ ) {
  18980. //for ( b = bevelSegments; b > 0; b -- ) {
  18981. t = b / bevelSegments;
  18982. z = bevelThickness * ( 1 - t );
  18983. //z = bevelThickness * t;
  18984. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18985. //bs = bevelSize * t ; // linear
  18986. // contract shape
  18987. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18988. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18989. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18990. v( vert.x, vert.y, - z );
  18991. }
  18992. // expand holes
  18993. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18994. ahole = holes[ h ];
  18995. oneHoleMovements = holesMovements[ h ];
  18996. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18997. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18998. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18999. v( vert.x, vert.y, -z );
  19000. }
  19001. }
  19002. }
  19003. bs = bevelSize;
  19004. // Back facing vertices
  19005. for ( i = 0; i < vlen; i ++ ) {
  19006. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19007. if ( !extrudeByPath ) {
  19008. v( vert.x, vert.y, 0 );
  19009. } else {
  19010. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19011. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19012. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19013. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19014. v( position2.x, position2.y, position2.z );
  19015. }
  19016. }
  19017. // Add stepped vertices...
  19018. // Including front facing vertices
  19019. var s;
  19020. for ( s = 1; s <= steps; s ++ ) {
  19021. for ( i = 0; i < vlen; i ++ ) {
  19022. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19023. if ( !extrudeByPath ) {
  19024. v( vert.x, vert.y, amount / steps * s );
  19025. } else {
  19026. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19027. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19028. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19029. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19030. v( position2.x, position2.y, position2.z );
  19031. }
  19032. }
  19033. }
  19034. // Add bevel segments planes
  19035. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19036. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19037. t = b / bevelSegments;
  19038. z = bevelThickness * ( 1 - t );
  19039. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19040. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19041. // contract shape
  19042. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19043. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19044. v( vert.x, vert.y, amount + z );
  19045. }
  19046. // expand holes
  19047. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19048. ahole = holes[ h ];
  19049. oneHoleMovements = holesMovements[ h ];
  19050. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19051. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19052. if ( !extrudeByPath ) {
  19053. v( vert.x, vert.y, amount + z );
  19054. } else {
  19055. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19056. }
  19057. }
  19058. }
  19059. }
  19060. /* Faces */
  19061. // Top and bottom faces
  19062. buildLidFaces();
  19063. // Sides faces
  19064. buildSideFaces();
  19065. ///// Internal functions
  19066. function buildLidFaces() {
  19067. if ( bevelEnabled ) {
  19068. var layer = 0 ; // steps + 1
  19069. var offset = vlen * layer;
  19070. // Bottom faces
  19071. for ( i = 0; i < flen; i ++ ) {
  19072. face = faces[ i ];
  19073. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19074. }
  19075. layer = steps + bevelSegments * 2;
  19076. offset = vlen * layer;
  19077. // Top faces
  19078. for ( i = 0; i < flen; i ++ ) {
  19079. face = faces[ i ];
  19080. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19081. }
  19082. } else {
  19083. // Bottom faces
  19084. for ( i = 0; i < flen; i++ ) {
  19085. face = faces[ i ];
  19086. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19087. }
  19088. // Top faces
  19089. for ( i = 0; i < flen; i ++ ) {
  19090. face = faces[ i ];
  19091. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19092. }
  19093. }
  19094. }
  19095. // Create faces for the z-sides of the shape
  19096. function buildSideFaces() {
  19097. var layeroffset = 0;
  19098. sidewalls( contour, layeroffset );
  19099. layeroffset += contour.length;
  19100. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19101. ahole = holes[ h ];
  19102. sidewalls( ahole, layeroffset );
  19103. //, true
  19104. layeroffset += ahole.length;
  19105. }
  19106. }
  19107. function sidewalls( contour, layeroffset ) {
  19108. var j, k;
  19109. i = contour.length;
  19110. while ( --i >= 0 ) {
  19111. j = i;
  19112. k = i - 1;
  19113. if ( k < 0 ) k = contour.length - 1;
  19114. //console.log('b', i,j, i-1, k,vertices.length);
  19115. var s = 0, sl = steps + bevelSegments * 2;
  19116. for ( s = 0; s < sl; s ++ ) {
  19117. var slen1 = vlen * s;
  19118. var slen2 = vlen * ( s + 1 );
  19119. var a = layeroffset + j + slen1,
  19120. b = layeroffset + k + slen1,
  19121. c = layeroffset + k + slen2,
  19122. d = layeroffset + j + slen2;
  19123. f4( a, b, c, d, contour, s, sl, j, k );
  19124. }
  19125. }
  19126. }
  19127. function v( x, y, z ) {
  19128. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19129. }
  19130. function f3( a, b, c, isBottom ) {
  19131. a += shapesOffset;
  19132. b += shapesOffset;
  19133. c += shapesOffset;
  19134. // normal, color, material
  19135. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19136. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19137. scope.faceVertexUvs[ 0 ].push( uvs );
  19138. }
  19139. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19140. a += shapesOffset;
  19141. b += shapesOffset;
  19142. c += shapesOffset;
  19143. d += shapesOffset;
  19144. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19145. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19146. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19147. scope.faceVertexUvs[ 0 ].push( uvs );
  19148. }
  19149. };
  19150. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19151. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19152. var ax = geometry.vertices[ indexA ].x,
  19153. ay = geometry.vertices[ indexA ].y,
  19154. bx = geometry.vertices[ indexB ].x,
  19155. by = geometry.vertices[ indexB ].y,
  19156. cx = geometry.vertices[ indexC ].x,
  19157. cy = geometry.vertices[ indexC ].y;
  19158. return [
  19159. new THREE.Vector2( ax, ay ),
  19160. new THREE.Vector2( bx, by ),
  19161. new THREE.Vector2( cx, cy )
  19162. ];
  19163. },
  19164. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19165. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19166. },
  19167. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19168. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19169. contourIndex1, contourIndex2 ) {
  19170. var ax = geometry.vertices[ indexA ].x,
  19171. ay = geometry.vertices[ indexA ].y,
  19172. az = geometry.vertices[ indexA ].z,
  19173. bx = geometry.vertices[ indexB ].x,
  19174. by = geometry.vertices[ indexB ].y,
  19175. bz = geometry.vertices[ indexB ].z,
  19176. cx = geometry.vertices[ indexC ].x,
  19177. cy = geometry.vertices[ indexC ].y,
  19178. cz = geometry.vertices[ indexC ].z,
  19179. dx = geometry.vertices[ indexD ].x,
  19180. dy = geometry.vertices[ indexD ].y,
  19181. dz = geometry.vertices[ indexD ].z;
  19182. if ( Math.abs( ay - by ) < 0.01 ) {
  19183. return [
  19184. new THREE.Vector2( ax, 1 - az ),
  19185. new THREE.Vector2( bx, 1 - bz ),
  19186. new THREE.Vector2( cx, 1 - cz ),
  19187. new THREE.Vector2( dx, 1 - dz )
  19188. ];
  19189. } else {
  19190. return [
  19191. new THREE.Vector2( ay, 1 - az ),
  19192. new THREE.Vector2( by, 1 - bz ),
  19193. new THREE.Vector2( cy, 1 - cz ),
  19194. new THREE.Vector2( dy, 1 - dz )
  19195. ];
  19196. }
  19197. }
  19198. };
  19199. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19200. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19201. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19202. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19203. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19204. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19205. /**
  19206. * @author jonobr1 / http://jonobr1.com
  19207. *
  19208. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19209. * ExtrudeGeometry.
  19210. *
  19211. * parameters = {
  19212. *
  19213. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19214. *
  19215. * material: <int> // material index for front and back faces
  19216. * uvGenerator: <Object> // object that provides UV generator functions
  19217. *
  19218. * }
  19219. **/
  19220. THREE.ShapeGeometry = function ( shapes, options ) {
  19221. THREE.Geometry.call( this );
  19222. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19223. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19224. this.addShapeList( shapes, options );
  19225. this.computeCentroids();
  19226. this.computeFaceNormals();
  19227. };
  19228. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19229. /**
  19230. * Add an array of shapes to THREE.ShapeGeometry.
  19231. */
  19232. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19233. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19234. this.addShape( shapes[ i ], options );
  19235. }
  19236. return this;
  19237. };
  19238. /**
  19239. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19240. */
  19241. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19242. if ( options === undefined ) options = {};
  19243. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19244. var material = options.material;
  19245. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19246. var shapebb = this.shapebb;
  19247. //
  19248. var i, l, hole, s;
  19249. var shapesOffset = this.vertices.length;
  19250. var shapePoints = shape.extractPoints( curveSegments );
  19251. var vertices = shapePoints.shape;
  19252. var holes = shapePoints.holes;
  19253. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19254. if ( reverse ) {
  19255. vertices = vertices.reverse();
  19256. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19257. for ( i = 0, l = holes.length; i < l; i++ ) {
  19258. hole = holes[ i ];
  19259. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19260. holes[ i ] = hole.reverse();
  19261. }
  19262. }
  19263. reverse = false;
  19264. }
  19265. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19266. // Vertices
  19267. var contour = vertices;
  19268. for ( i = 0, l = holes.length; i < l; i++ ) {
  19269. hole = holes[ i ];
  19270. vertices = vertices.concat( hole );
  19271. }
  19272. //
  19273. var vert, vlen = vertices.length;
  19274. var face, flen = faces.length;
  19275. var cont, clen = contour.length;
  19276. for ( i = 0; i < vlen; i++ ) {
  19277. vert = vertices[ i ];
  19278. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19279. }
  19280. for ( i = 0; i < flen; i++ ) {
  19281. face = faces[ i ];
  19282. var a = face[ 0 ] + shapesOffset;
  19283. var b = face[ 1 ] + shapesOffset;
  19284. var c = face[ 2 ] + shapesOffset;
  19285. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19286. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19287. }
  19288. };
  19289. /**
  19290. * @author astrodud / http://astrodud.isgreat.org/
  19291. * @author zz85 / https://github.com/zz85
  19292. * @author bhouston / http://exocortex.com
  19293. */
  19294. // points - to create a closed torus, one must use a set of points
  19295. // like so: [ a, b, c, d, a ], see first is the same as last.
  19296. // segments - the number of circumference segments to create
  19297. // phiStart - the starting radian
  19298. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19299. // 2*pi is a closed lathe, less than 2PI is a portion.
  19300. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19301. THREE.Geometry.call( this );
  19302. segments = segments || 12;
  19303. phiStart = phiStart || 0;
  19304. phiLength = phiLength || 2 * Math.PI;
  19305. var inversePointLength = 1.0 / ( points.length - 1 );
  19306. var inverseSegments = 1.0 / segments;
  19307. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19308. var phi = phiStart + i * inverseSegments * phiLength;
  19309. var c = Math.cos( phi ),
  19310. s = Math.sin( phi );
  19311. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19312. var pt = points[ j ];
  19313. var vertex = new THREE.Vector3();
  19314. vertex.x = c * pt.x - s * pt.y;
  19315. vertex.y = s * pt.x + c * pt.y;
  19316. vertex.z = pt.z;
  19317. this.vertices.push( vertex );
  19318. }
  19319. }
  19320. var np = points.length;
  19321. for ( var i = 0, il = segments; i < il; i ++ ) {
  19322. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19323. var base = j + np * i;
  19324. var a = base;
  19325. var b = base + np;
  19326. var c = base + 1 + np;
  19327. var d = base + 1;
  19328. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19329. var u0 = i * inverseSegments;
  19330. var v0 = j * inversePointLength;
  19331. var u1 = u0 + inverseSegments;
  19332. var v1 = v0 + inversePointLength;
  19333. this.faceVertexUvs[ 0 ].push( [
  19334. new THREE.Vector2( u0, v0 ),
  19335. new THREE.Vector2( u1, v0 ),
  19336. new THREE.Vector2( u1, v1 ),
  19337. new THREE.Vector2( u0, v1 )
  19338. ] );
  19339. }
  19340. }
  19341. this.mergeVertices();
  19342. this.computeCentroids();
  19343. this.computeFaceNormals();
  19344. this.computeVertexNormals();
  19345. };
  19346. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19347. /**
  19348. * @author mrdoob / http://mrdoob.com/
  19349. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19350. */
  19351. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19352. THREE.Geometry.call( this );
  19353. this.width = width;
  19354. this.height = height;
  19355. this.widthSegments = widthSegments || 1;
  19356. this.heightSegments = heightSegments || 1;
  19357. var ix, iz;
  19358. var width_half = width / 2;
  19359. var height_half = height / 2;
  19360. var gridX = this.widthSegments;
  19361. var gridZ = this.heightSegments;
  19362. var gridX1 = gridX + 1;
  19363. var gridZ1 = gridZ + 1;
  19364. var segment_width = this.width / gridX;
  19365. var segment_height = this.height / gridZ;
  19366. var normal = new THREE.Vector3( 0, 0, 1 );
  19367. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19368. for ( ix = 0; ix < gridX1; ix ++ ) {
  19369. var x = ix * segment_width - width_half;
  19370. var y = iz * segment_height - height_half;
  19371. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19372. }
  19373. }
  19374. for ( iz = 0; iz < gridZ; iz ++ ) {
  19375. for ( ix = 0; ix < gridX; ix ++ ) {
  19376. var a = ix + gridX1 * iz;
  19377. var b = ix + gridX1 * ( iz + 1 );
  19378. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19379. var d = ( ix + 1 ) + gridX1 * iz;
  19380. var face = new THREE.Face4( a, b, c, d );
  19381. face.normal.copy( normal );
  19382. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19383. this.faces.push( face );
  19384. this.faceVertexUvs[ 0 ].push( [
  19385. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19386. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19387. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19388. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19389. ] );
  19390. }
  19391. }
  19392. this.computeCentroids();
  19393. };
  19394. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19395. /**
  19396. * @author Kaleb Murphy
  19397. */
  19398. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19399. THREE.Geometry.call( this );
  19400. innerRadius = innerRadius || 0;
  19401. outerRadius = outerRadius || 50;
  19402. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19403. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19404. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19405. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19406. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19407. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19408. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19409. var vertex = new THREE.Vector3();
  19410. var segment = thetaStart + o / thetaSegments * thetaLength;
  19411. vertex.x = radius * Math.cos( segment );
  19412. vertex.y = radius * Math.sin( segment );
  19413. this.vertices.push( vertex );
  19414. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19415. }
  19416. radius += radiusStep;
  19417. }
  19418. var n = new THREE.Vector3( 0, 0, 1 );
  19419. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19420. var thetaSegment = i * thetaSegments;
  19421. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19422. var segment = o + thetaSegment;
  19423. var v1 = segment + i;
  19424. var v2 = segment + thetaSegments + i;
  19425. var v3 = segment + thetaSegments + 1 + i;
  19426. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19427. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19428. v1 = segment + i;
  19429. v2 = segment + thetaSegments + 1 + i;
  19430. v3 = segment + 1 + i;
  19431. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19432. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19433. }
  19434. }
  19435. this.computeCentroids();
  19436. this.computeFaceNormals();
  19437. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19438. };
  19439. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19440. /**
  19441. * @author mrdoob / http://mrdoob.com/
  19442. */
  19443. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19444. THREE.Geometry.call( this );
  19445. this.radius = radius = radius || 50;
  19446. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19447. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19448. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19449. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19450. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19451. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19452. var x, y, vertices = [], uvs = [];
  19453. for ( y = 0; y <= heightSegments; y ++ ) {
  19454. var verticesRow = [];
  19455. var uvsRow = [];
  19456. for ( x = 0; x <= widthSegments; x ++ ) {
  19457. var u = x / widthSegments;
  19458. var v = y / heightSegments;
  19459. var vertex = new THREE.Vector3();
  19460. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19461. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19462. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19463. this.vertices.push( vertex );
  19464. verticesRow.push( this.vertices.length - 1 );
  19465. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19466. }
  19467. vertices.push( verticesRow );
  19468. uvs.push( uvsRow );
  19469. }
  19470. for ( y = 0; y < this.heightSegments; y ++ ) {
  19471. for ( x = 0; x < this.widthSegments; x ++ ) {
  19472. var v1 = vertices[ y ][ x + 1 ];
  19473. var v2 = vertices[ y ][ x ];
  19474. var v3 = vertices[ y + 1 ][ x ];
  19475. var v4 = vertices[ y + 1 ][ x + 1 ];
  19476. var n1 = this.vertices[ v1 ].clone().normalize();
  19477. var n2 = this.vertices[ v2 ].clone().normalize();
  19478. var n3 = this.vertices[ v3 ].clone().normalize();
  19479. var n4 = this.vertices[ v4 ].clone().normalize();
  19480. var uv1 = uvs[ y ][ x + 1 ].clone();
  19481. var uv2 = uvs[ y ][ x ].clone();
  19482. var uv3 = uvs[ y + 1 ][ x ].clone();
  19483. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19484. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19485. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19486. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19487. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19488. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19489. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19490. } else {
  19491. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19492. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19493. }
  19494. }
  19495. }
  19496. this.computeCentroids();
  19497. this.computeFaceNormals();
  19498. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19499. };
  19500. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19501. /**
  19502. * @author zz85 / http://www.lab4games.net/zz85/blog
  19503. * @author alteredq / http://alteredqualia.com/
  19504. *
  19505. * For creating 3D text geometry in three.js
  19506. *
  19507. * Text = 3D Text
  19508. *
  19509. * parameters = {
  19510. * size: <float>, // size of the text
  19511. * height: <float>, // thickness to extrude text
  19512. * curveSegments: <int>, // number of points on the curves
  19513. *
  19514. * font: <string>, // font name
  19515. * weight: <string>, // font weight (normal, bold)
  19516. * style: <string>, // font style (normal, italics)
  19517. *
  19518. * bevelEnabled: <bool>, // turn on bevel
  19519. * bevelThickness: <float>, // how deep into text bevel goes
  19520. * bevelSize: <float>, // how far from text outline is bevel
  19521. * }
  19522. *
  19523. */
  19524. /* Usage Examples
  19525. // TextGeometry wrapper
  19526. var text3d = new TextGeometry( text, options );
  19527. // Complete manner
  19528. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19529. var text3d = new ExtrudeGeometry( textShapes, options );
  19530. */
  19531. THREE.TextGeometry = function ( text, parameters ) {
  19532. parameters = parameters || {};
  19533. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19534. // translate parameters to ExtrudeGeometry API
  19535. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19536. // defaults
  19537. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19538. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19539. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19540. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19541. };
  19542. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19543. /**
  19544. * @author oosmoxiecode
  19545. * @author mrdoob / http://mrdoob.com/
  19546. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19547. */
  19548. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19549. THREE.Geometry.call( this );
  19550. var scope = this;
  19551. this.radius = radius || 100;
  19552. this.tube = tube || 40;
  19553. this.radialSegments = radialSegments || 8;
  19554. this.tubularSegments = tubularSegments || 6;
  19555. this.arc = arc || Math.PI * 2;
  19556. var center = new THREE.Vector3(), uvs = [], normals = [];
  19557. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19558. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19559. var u = i / this.tubularSegments * this.arc;
  19560. var v = j / this.radialSegments * Math.PI * 2;
  19561. center.x = this.radius * Math.cos( u );
  19562. center.y = this.radius * Math.sin( u );
  19563. var vertex = new THREE.Vector3();
  19564. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19565. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19566. vertex.z = this.tube * Math.sin( v );
  19567. this.vertices.push( vertex );
  19568. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19569. normals.push( vertex.clone().sub( center ).normalize() );
  19570. }
  19571. }
  19572. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19573. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19574. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19575. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19576. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19577. var d = ( this.tubularSegments + 1 ) * j + i;
  19578. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19579. face.normal.add( normals[ a ] );
  19580. face.normal.add( normals[ b ] );
  19581. face.normal.add( normals[ c ] );
  19582. face.normal.add( normals[ d ] );
  19583. face.normal.normalize();
  19584. this.faces.push( face );
  19585. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19586. }
  19587. }
  19588. this.computeCentroids();
  19589. };
  19590. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19591. /**
  19592. * @author oosmoxiecode
  19593. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19594. */
  19595. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19596. THREE.Geometry.call( this );
  19597. var scope = this;
  19598. this.radius = radius || 100;
  19599. this.tube = tube || 40;
  19600. this.radialSegments = radialSegments || 64;
  19601. this.tubularSegments = tubularSegments || 8;
  19602. this.p = p || 2;
  19603. this.q = q || 3;
  19604. this.heightScale = heightScale || 1;
  19605. this.grid = new Array( this.radialSegments );
  19606. var tang = new THREE.Vector3();
  19607. var n = new THREE.Vector3();
  19608. var bitan = new THREE.Vector3();
  19609. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19610. this.grid[ i ] = new Array( this.tubularSegments );
  19611. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19612. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19613. var v = j / this.tubularSegments * 2 * Math.PI;
  19614. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19615. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19616. var cx, cy;
  19617. tang.subVectors( p2, p1 );
  19618. n.addVectors( p2, p1 );
  19619. bitan.crossVectors( tang, n );
  19620. n.crossVectors( bitan, tang );
  19621. bitan.normalize();
  19622. n.normalize();
  19623. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19624. cy = this.tube * Math.sin( v );
  19625. p1.x += cx * n.x + cy * bitan.x;
  19626. p1.y += cx * n.y + cy * bitan.y;
  19627. p1.z += cx * n.z + cy * bitan.z;
  19628. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19629. }
  19630. }
  19631. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19632. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19633. var ip = ( i + 1 ) % this.radialSegments;
  19634. var jp = ( j + 1 ) % this.tubularSegments;
  19635. var a = this.grid[ i ][ j ];
  19636. var b = this.grid[ ip ][ j ];
  19637. var c = this.grid[ ip ][ jp ];
  19638. var d = this.grid[ i ][ jp ];
  19639. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19640. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19641. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19642. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19643. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19644. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19645. }
  19646. }
  19647. this.computeCentroids();
  19648. this.computeFaceNormals();
  19649. this.computeVertexNormals();
  19650. function vert( x, y, z ) {
  19651. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19652. }
  19653. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19654. var cu = Math.cos( u );
  19655. var cv = Math.cos( v );
  19656. var su = Math.sin( u );
  19657. var quOverP = in_q / in_p * u;
  19658. var cs = Math.cos( quOverP );
  19659. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19660. var ty = radius * ( 2 + cs ) * su * 0.5;
  19661. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19662. return new THREE.Vector3( tx, ty, tz );
  19663. }
  19664. };
  19665. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19666. /**
  19667. * @author WestLangley / https://github.com/WestLangley
  19668. * @author zz85 / https://github.com/zz85
  19669. * @author miningold / https://github.com/miningold
  19670. *
  19671. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19672. *
  19673. * Creates a tube which extrudes along a 3d spline
  19674. *
  19675. * Uses parallel transport frames as described in
  19676. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19677. */
  19678. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19679. THREE.Geometry.call( this );
  19680. this.path = path;
  19681. this.segments = segments || 64;
  19682. this.radius = radius || 1;
  19683. this.radiusSegments = radiusSegments || 8;
  19684. this.closed = closed || false;
  19685. if ( debug ) this.debug = new THREE.Object3D();
  19686. this.grid = [];
  19687. var scope = this,
  19688. tangent,
  19689. normal,
  19690. binormal,
  19691. numpoints = this.segments + 1,
  19692. x, y, z,
  19693. tx, ty, tz,
  19694. u, v,
  19695. cx, cy,
  19696. pos, pos2 = new THREE.Vector3(),
  19697. i, j,
  19698. ip, jp,
  19699. a, b, c, d,
  19700. uva, uvb, uvc, uvd;
  19701. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19702. tangents = frames.tangents,
  19703. normals = frames.normals,
  19704. binormals = frames.binormals;
  19705. // proxy internals
  19706. this.tangents = tangents;
  19707. this.normals = normals;
  19708. this.binormals = binormals;
  19709. function vert( x, y, z ) {
  19710. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19711. }
  19712. // consruct the grid
  19713. for ( i = 0; i < numpoints; i++ ) {
  19714. this.grid[ i ] = [];
  19715. u = i / ( numpoints - 1 );
  19716. pos = path.getPointAt( u );
  19717. tangent = tangents[ i ];
  19718. normal = normals[ i ];
  19719. binormal = binormals[ i ];
  19720. if ( this.debug ) {
  19721. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19722. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19723. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19724. }
  19725. for ( j = 0; j < this.radiusSegments; j++ ) {
  19726. v = j / this.radiusSegments * 2 * Math.PI;
  19727. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19728. cy = this.radius * Math.sin( v );
  19729. pos2.copy( pos );
  19730. pos2.x += cx * normal.x + cy * binormal.x;
  19731. pos2.y += cx * normal.y + cy * binormal.y;
  19732. pos2.z += cx * normal.z + cy * binormal.z;
  19733. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19734. }
  19735. }
  19736. // construct the mesh
  19737. for ( i = 0; i < this.segments; i++ ) {
  19738. for ( j = 0; j < this.radiusSegments; j++ ) {
  19739. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19740. jp = (j + 1) % this.radiusSegments;
  19741. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19742. b = this.grid[ ip ][ j ];
  19743. c = this.grid[ ip ][ jp ];
  19744. d = this.grid[ i ][ jp ];
  19745. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19746. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19747. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19748. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19749. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19750. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19751. }
  19752. }
  19753. this.computeCentroids();
  19754. this.computeFaceNormals();
  19755. this.computeVertexNormals();
  19756. };
  19757. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19758. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19759. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19760. var tangent = new THREE.Vector3(),
  19761. normal = new THREE.Vector3(),
  19762. binormal = new THREE.Vector3(),
  19763. tangents = [],
  19764. normals = [],
  19765. binormals = [],
  19766. vec = new THREE.Vector3(),
  19767. mat = new THREE.Matrix4(),
  19768. numpoints = segments + 1,
  19769. theta,
  19770. epsilon = 0.0001,
  19771. smallest,
  19772. tx, ty, tz,
  19773. i, u, v;
  19774. // expose internals
  19775. this.tangents = tangents;
  19776. this.normals = normals;
  19777. this.binormals = binormals;
  19778. // compute the tangent vectors for each segment on the path
  19779. for ( i = 0; i < numpoints; i++ ) {
  19780. u = i / ( numpoints - 1 );
  19781. tangents[ i ] = path.getTangentAt( u );
  19782. tangents[ i ].normalize();
  19783. }
  19784. initialNormal3();
  19785. function initialNormal1(lastBinormal) {
  19786. // fixed start binormal. Has dangers of 0 vectors
  19787. normals[ 0 ] = new THREE.Vector3();
  19788. binormals[ 0 ] = new THREE.Vector3();
  19789. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19790. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19791. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19792. }
  19793. function initialNormal2() {
  19794. // This uses the Frenet-Serret formula for deriving binormal
  19795. var t2 = path.getTangentAt( epsilon );
  19796. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19797. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19798. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19799. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19800. }
  19801. function initialNormal3() {
  19802. // select an initial normal vector perpenicular to the first tangent vector,
  19803. // and in the direction of the smallest tangent xyz component
  19804. normals[ 0 ] = new THREE.Vector3();
  19805. binormals[ 0 ] = new THREE.Vector3();
  19806. smallest = Number.MAX_VALUE;
  19807. tx = Math.abs( tangents[ 0 ].x );
  19808. ty = Math.abs( tangents[ 0 ].y );
  19809. tz = Math.abs( tangents[ 0 ].z );
  19810. if ( tx <= smallest ) {
  19811. smallest = tx;
  19812. normal.set( 1, 0, 0 );
  19813. }
  19814. if ( ty <= smallest ) {
  19815. smallest = ty;
  19816. normal.set( 0, 1, 0 );
  19817. }
  19818. if ( tz <= smallest ) {
  19819. normal.set( 0, 0, 1 );
  19820. }
  19821. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19822. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19823. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19824. }
  19825. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19826. for ( i = 1; i < numpoints; i++ ) {
  19827. normals[ i ] = normals[ i-1 ].clone();
  19828. binormals[ i ] = binormals[ i-1 ].clone();
  19829. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19830. if ( vec.length() > epsilon ) {
  19831. vec.normalize();
  19832. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19833. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19834. }
  19835. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19836. }
  19837. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19838. if ( closed ) {
  19839. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19840. theta /= ( numpoints - 1 );
  19841. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19842. theta = -theta;
  19843. }
  19844. for ( i = 1; i < numpoints; i++ ) {
  19845. // twist a little...
  19846. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19847. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19848. }
  19849. }
  19850. };
  19851. /**
  19852. * @author clockworkgeek / https://github.com/clockworkgeek
  19853. * @author timothypratley / https://github.com/timothypratley
  19854. * @author WestLangley / http://github.com/WestLangley
  19855. */
  19856. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19857. THREE.Geometry.call( this );
  19858. radius = radius || 1;
  19859. detail = detail || 0;
  19860. var that = this;
  19861. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19862. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19863. }
  19864. var midpoints = [], p = this.vertices;
  19865. var f = [];
  19866. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19867. var v1 = p[ faces[ i ][ 0 ] ];
  19868. var v2 = p[ faces[ i ][ 1 ] ];
  19869. var v3 = p[ faces[ i ][ 2 ] ];
  19870. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19871. }
  19872. for ( var i = 0, l = f.length; i < l; i ++ ) {
  19873. subdivide(f[ i ], detail);
  19874. }
  19875. // Handle case when face straddles the seam
  19876. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  19877. var uvs = this.faceVertexUvs[ 0 ][ i ];
  19878. var x0 = uvs[ 0 ].x;
  19879. var x1 = uvs[ 1 ].x;
  19880. var x2 = uvs[ 2 ].x;
  19881. var max = Math.max( x0, Math.max( x1, x2 ) );
  19882. var min = Math.min( x0, Math.min( x1, x2 ) );
  19883. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  19884. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  19885. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  19886. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  19887. }
  19888. }
  19889. // Merge vertices
  19890. this.mergeVertices();
  19891. // Apply radius
  19892. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19893. this.vertices[ i ].multiplyScalar( radius );
  19894. }
  19895. // Project vector onto sphere's surface
  19896. function prepare( vector ) {
  19897. var vertex = vector.normalize().clone();
  19898. vertex.index = that.vertices.push( vertex ) - 1;
  19899. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19900. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19901. var v = inclination( vector ) / Math.PI + 0.5;
  19902. vertex.uv = new THREE.Vector2( u, 1 - v );
  19903. return vertex;
  19904. }
  19905. // Approximate a curved face with recursively sub-divided triangles.
  19906. function make( v1, v2, v3 ) {
  19907. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19908. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19909. face.normal.copy( face.centroid ).normalize();
  19910. that.faces.push( face );
  19911. var azi = azimuth( face.centroid );
  19912. that.faceVertexUvs[ 0 ].push( [
  19913. correctUV( v1.uv, v1, azi ),
  19914. correctUV( v2.uv, v2, azi ),
  19915. correctUV( v3.uv, v3, azi )
  19916. ] );
  19917. }
  19918. // Analytically subdivide a face to the required detail level.
  19919. function subdivide(face, detail ) {
  19920. var cols = Math.pow(2, detail);
  19921. var cells = Math.pow(4, detail);
  19922. var a = prepare( that.vertices[ face.a ] );
  19923. var b = prepare( that.vertices[ face.b ] );
  19924. var c = prepare( that.vertices[ face.c ] );
  19925. var v = [];
  19926. // Construct all of the vertices for this subdivision.
  19927. for ( var i = 0 ; i <= cols; i ++ ) {
  19928. v[ i ] = [];
  19929. var aj = prepare( a.clone().lerp( c, i / cols ) );
  19930. var bj = prepare( b.clone().lerp( c, i / cols ) );
  19931. var rows = cols - i;
  19932. for ( var j = 0; j <= rows; j ++) {
  19933. if ( j == 0 && i == cols ) {
  19934. v[ i ][ j ] = aj;
  19935. } else {
  19936. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  19937. }
  19938. }
  19939. }
  19940. // Construct all of the faces.
  19941. for ( var i = 0; i < cols ; i ++ ) {
  19942. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  19943. var k = Math.floor( j / 2 );
  19944. if ( j % 2 == 0 ) {
  19945. make(
  19946. v[ i ][ k + 1],
  19947. v[ i + 1 ][ k ],
  19948. v[ i ][ k ]
  19949. );
  19950. } else {
  19951. make(
  19952. v[ i ][ k + 1 ],
  19953. v[ i + 1][ k + 1],
  19954. v[ i + 1 ][ k ]
  19955. );
  19956. }
  19957. }
  19958. }
  19959. }
  19960. // Angle around the Y axis, counter-clockwise when looking from above.
  19961. function azimuth( vector ) {
  19962. return Math.atan2( vector.z, -vector.x );
  19963. }
  19964. // Angle above the XZ plane.
  19965. function inclination( vector ) {
  19966. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19967. }
  19968. // Texture fixing helper. Spheres have some odd behaviours.
  19969. function correctUV( uv, vector, azimuth ) {
  19970. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19971. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19972. return uv.clone();
  19973. }
  19974. this.computeCentroids();
  19975. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19976. };
  19977. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19978. /**
  19979. * @author timothypratley / https://github.com/timothypratley
  19980. */
  19981. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19982. this.radius = radius;
  19983. this.detail = detail;
  19984. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19985. var vertices = [
  19986. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19987. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19988. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19989. ];
  19990. var faces = [
  19991. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19992. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19993. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19994. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19995. ];
  19996. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19997. };
  19998. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19999. /**
  20000. * @author timothypratley / https://github.com/timothypratley
  20001. */
  20002. THREE.OctahedronGeometry = function ( radius, detail ) {
  20003. var vertices = [
  20004. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20005. ];
  20006. var faces = [
  20007. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20008. ];
  20009. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20010. };
  20011. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20012. /**
  20013. * @author timothypratley / https://github.com/timothypratley
  20014. */
  20015. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20016. var vertices = [
  20017. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20018. ];
  20019. var faces = [
  20020. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20021. ];
  20022. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20023. };
  20024. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20025. /**
  20026. * @author zz85 / https://github.com/zz85
  20027. * Parametric Surfaces Geometry
  20028. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20029. *
  20030. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  20031. *
  20032. */
  20033. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  20034. THREE.Geometry.call( this );
  20035. var verts = this.vertices;
  20036. var faces = this.faces;
  20037. var uvs = this.faceVertexUvs[ 0 ];
  20038. useTris = (useTris === undefined) ? false : useTris;
  20039. var i, il, j, p;
  20040. var u, v;
  20041. var stackCount = stacks + 1;
  20042. var sliceCount = slices + 1;
  20043. for ( i = 0; i <= stacks; i ++ ) {
  20044. v = i / stacks;
  20045. for ( j = 0; j <= slices; j ++ ) {
  20046. u = j / slices;
  20047. p = func( u, v );
  20048. verts.push( p );
  20049. }
  20050. }
  20051. var a, b, c, d;
  20052. var uva, uvb, uvc, uvd;
  20053. for ( i = 0; i < stacks; i ++ ) {
  20054. for ( j = 0; j < slices; j ++ ) {
  20055. a = i * sliceCount + j;
  20056. b = i * sliceCount + j + 1;
  20057. c = (i + 1) * sliceCount + j;
  20058. d = (i + 1) * sliceCount + j + 1;
  20059. uva = new THREE.Vector2( j / slices, i / stacks );
  20060. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20061. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20062. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20063. if ( useTris ) {
  20064. faces.push( new THREE.Face3( a, b, c ) );
  20065. faces.push( new THREE.Face3( b, d, c ) );
  20066. uvs.push( [ uva, uvb, uvc ] );
  20067. uvs.push( [ uvb, uvd, uvc ] );
  20068. } else {
  20069. faces.push( new THREE.Face4( a, b, d, c ) );
  20070. uvs.push( [ uva, uvb, uvd, uvc ] );
  20071. }
  20072. }
  20073. }
  20074. // console.log(this);
  20075. // magic bullet
  20076. // var diff = this.mergeVertices();
  20077. // console.log('removed ', diff, ' vertices by merging');
  20078. this.computeCentroids();
  20079. this.computeFaceNormals();
  20080. this.computeVertexNormals();
  20081. };
  20082. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20083. /**
  20084. * @author qiao / https://github.com/qiao
  20085. * @fileoverview This is a convex hull generator using the incremental method.
  20086. * The complexity is O(n^2) where n is the number of vertices.
  20087. * O(nlogn) algorithms do exist, but they are much more complicated.
  20088. *
  20089. * Benchmark:
  20090. *
  20091. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20092. *
  20093. * Num Vertices Time(ms)
  20094. *
  20095. * 10 1
  20096. * 20 3
  20097. * 30 19
  20098. * 40 48
  20099. * 50 107
  20100. */
  20101. THREE.ConvexGeometry = function( vertices ) {
  20102. THREE.Geometry.call( this );
  20103. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20104. for ( var i = 3; i < vertices.length; i++ ) {
  20105. addPoint( i );
  20106. }
  20107. function addPoint( vertexId ) {
  20108. var vertex = vertices[ vertexId ].clone();
  20109. var mag = vertex.length();
  20110. vertex.x += mag * randomOffset();
  20111. vertex.y += mag * randomOffset();
  20112. vertex.z += mag * randomOffset();
  20113. var hole = [];
  20114. for ( var f = 0; f < faces.length; ) {
  20115. var face = faces[ f ];
  20116. // for each face, if the vertex can see it,
  20117. // then we try to add the face's edges into the hole.
  20118. if ( visible( face, vertex ) ) {
  20119. for ( var e = 0; e < 3; e++ ) {
  20120. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20121. var boundary = true;
  20122. // remove duplicated edges.
  20123. for ( var h = 0; h < hole.length; h++ ) {
  20124. if ( equalEdge( hole[ h ], edge ) ) {
  20125. hole[ h ] = hole[ hole.length - 1 ];
  20126. hole.pop();
  20127. boundary = false;
  20128. break;
  20129. }
  20130. }
  20131. if ( boundary ) {
  20132. hole.push( edge );
  20133. }
  20134. }
  20135. // remove faces[ f ]
  20136. faces[ f ] = faces[ faces.length - 1 ];
  20137. faces.pop();
  20138. } else { // not visible
  20139. f++;
  20140. }
  20141. }
  20142. // construct the new faces formed by the edges of the hole and the vertex
  20143. for ( var h = 0; h < hole.length; h++ ) {
  20144. faces.push( [
  20145. hole[ h ][ 0 ],
  20146. hole[ h ][ 1 ],
  20147. vertexId
  20148. ] );
  20149. }
  20150. }
  20151. /**
  20152. * Whether the face is visible from the vertex
  20153. */
  20154. function visible( face, vertex ) {
  20155. var va = vertices[ face[ 0 ] ];
  20156. var vb = vertices[ face[ 1 ] ];
  20157. var vc = vertices[ face[ 2 ] ];
  20158. var n = normal( va, vb, vc );
  20159. // distance from face to origin
  20160. var dist = n.dot( va );
  20161. return n.dot( vertex ) >= dist;
  20162. }
  20163. /**
  20164. * Face normal
  20165. */
  20166. function normal( va, vb, vc ) {
  20167. var cb = new THREE.Vector3();
  20168. var ab = new THREE.Vector3();
  20169. cb.subVectors( vc, vb );
  20170. ab.subVectors( va, vb );
  20171. cb.cross( ab );
  20172. cb.normalize();
  20173. return cb;
  20174. }
  20175. /**
  20176. * Detect whether two edges are equal.
  20177. * Note that when constructing the convex hull, two same edges can only
  20178. * be of the negative direction.
  20179. */
  20180. function equalEdge( ea, eb ) {
  20181. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20182. }
  20183. /**
  20184. * Create a random offset between -1e-6 and 1e-6.
  20185. */
  20186. function randomOffset() {
  20187. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20188. }
  20189. /**
  20190. * XXX: Not sure if this is the correct approach. Need someone to review.
  20191. */
  20192. function vertexUv( vertex ) {
  20193. var mag = vertex.length();
  20194. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20195. }
  20196. // Push vertices into `this.vertices`, skipping those inside the hull
  20197. var id = 0;
  20198. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20199. for ( var i = 0; i < faces.length; i++ ) {
  20200. var face = faces[ i ];
  20201. for ( var j = 0; j < 3; j++ ) {
  20202. if ( newId[ face[ j ] ] === undefined ) {
  20203. newId[ face[ j ] ] = id++;
  20204. this.vertices.push( vertices[ face[ j ] ] );
  20205. }
  20206. face[ j ] = newId[ face[ j ] ];
  20207. }
  20208. }
  20209. // Convert faces into instances of THREE.Face3
  20210. for ( var i = 0; i < faces.length; i++ ) {
  20211. this.faces.push( new THREE.Face3(
  20212. faces[ i ][ 0 ],
  20213. faces[ i ][ 1 ],
  20214. faces[ i ][ 2 ]
  20215. ) );
  20216. }
  20217. // Compute UVs
  20218. for ( var i = 0; i < this.faces.length; i++ ) {
  20219. var face = this.faces[ i ];
  20220. this.faceVertexUvs[ 0 ].push( [
  20221. vertexUv( this.vertices[ face.a ] ),
  20222. vertexUv( this.vertices[ face.b ] ),
  20223. vertexUv( this.vertices[ face.c ])
  20224. ] );
  20225. }
  20226. this.computeCentroids();
  20227. this.computeFaceNormals();
  20228. this.computeVertexNormals();
  20229. };
  20230. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20231. /**
  20232. * @author sroucheray / http://sroucheray.org/
  20233. * @author mrdoob / http://mrdoob.com/
  20234. */
  20235. THREE.AxisHelper = function ( size ) {
  20236. size = size || 1;
  20237. var geometry = new THREE.Geometry();
  20238. geometry.vertices.push(
  20239. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20240. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20241. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20242. );
  20243. geometry.colors.push(
  20244. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20245. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20246. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20247. );
  20248. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20249. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20250. };
  20251. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20252. /**
  20253. * @author WestLangley / http://github.com/WestLangley
  20254. * @author zz85 / http://github.com/zz85
  20255. * @author bhouston / http://exocortex.com
  20256. *
  20257. * Creates an arrow for visualizing directions
  20258. *
  20259. * Parameters:
  20260. * dir - Vector3
  20261. * origin - Vector3
  20262. * length - Number
  20263. * hex - color in hex value
  20264. */
  20265. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20266. // dir is assumed to be normalized
  20267. THREE.Object3D.call( this );
  20268. if ( hex === undefined ) hex = 0xffff00;
  20269. if ( length === undefined ) length = 1;
  20270. this.position = origin;
  20271. this.useQuaternion = true;
  20272. var lineGeometry = new THREE.Geometry();
  20273. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20274. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20275. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20276. this.line.matrixAutoUpdate = false;
  20277. this.add( this.line );
  20278. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20279. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20280. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20281. this.cone.matrixAutoUpdate = false;
  20282. this.add( this.cone );
  20283. this.setDirection( dir );
  20284. this.setLength( length );
  20285. };
  20286. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20287. THREE.ArrowHelper.prototype.setDirection = function () {
  20288. var axis = new THREE.Vector3();
  20289. var radians;
  20290. return function ( dir ) {
  20291. // dir is assumed to be normalized
  20292. if ( dir.y > 0.999 ) {
  20293. this.quaternion.set( 0, 0, 0, 1 );
  20294. } else if ( dir.y < - 0.999 ) {
  20295. this.quaternion.set( 1, 0, 0, 0 );
  20296. } else {
  20297. axis.set( dir.z, 0, - dir.x ).normalize();
  20298. radians = Math.acos( dir.y );
  20299. this.quaternion.setFromAxisAngle( axis, radians );
  20300. }
  20301. };
  20302. }();
  20303. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20304. this.scale.set( length, length, length );
  20305. };
  20306. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20307. this.line.material.color.setHex( hex );
  20308. this.cone.material.color.setHex( hex );
  20309. };
  20310. /**
  20311. * @author mrdoob / http://mrdoob.com/
  20312. */
  20313. THREE.BoxHelper = function ( size ) {
  20314. size = size || 1;
  20315. var geometry = new THREE.Geometry();
  20316. // 5____4
  20317. // 1/___0/|
  20318. // | 6__|_7
  20319. // 2/___3/
  20320. var vertices = [
  20321. new THREE.Vector3( size, size, size ),
  20322. new THREE.Vector3( - size, size, size ),
  20323. new THREE.Vector3( - size, - size, size ),
  20324. new THREE.Vector3( size, - size, size ),
  20325. new THREE.Vector3( size, size, - size ),
  20326. new THREE.Vector3( - size, size, - size ),
  20327. new THREE.Vector3( - size, - size, - size ),
  20328. new THREE.Vector3( size, - size, - size )
  20329. ];
  20330. // TODO: Wouldn't be nice if Line had .segments?
  20331. geometry.vertices.push(
  20332. vertices[ 0 ], vertices[ 1 ],
  20333. vertices[ 1 ], vertices[ 2 ],
  20334. vertices[ 2 ], vertices[ 3 ],
  20335. vertices[ 3 ], vertices[ 0 ],
  20336. vertices[ 4 ], vertices[ 5 ],
  20337. vertices[ 5 ], vertices[ 6 ],
  20338. vertices[ 6 ], vertices[ 7 ],
  20339. vertices[ 7 ], vertices[ 4 ],
  20340. vertices[ 0 ], vertices[ 4 ],
  20341. vertices[ 1 ], vertices[ 5 ],
  20342. vertices[ 2 ], vertices[ 6 ],
  20343. vertices[ 3 ], vertices[ 7 ]
  20344. );
  20345. this.vertices = vertices;
  20346. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial(), THREE.LinePieces );
  20347. };
  20348. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20349. THREE.BoxHelper.prototype.update = function ( object ) {
  20350. var geometry = object.geometry;
  20351. if ( geometry.boundingBox === null ) {
  20352. geometry.computeBoundingBox();
  20353. }
  20354. var min = geometry.boundingBox.min;
  20355. var max = geometry.boundingBox.max;
  20356. var vertices = this.vertices;
  20357. vertices[ 0 ].set( max.x, max.y, max.z );
  20358. vertices[ 1 ].set( min.x, max.y, max.z );
  20359. vertices[ 2 ].set( min.x, min.y, max.z );
  20360. vertices[ 3 ].set( max.x, min.y, max.z );
  20361. vertices[ 4 ].set( max.x, max.y, min.z );
  20362. vertices[ 5 ].set( min.x, max.y, min.z );
  20363. vertices[ 6 ].set( min.x, min.y, min.z );
  20364. vertices[ 7 ].set( max.x, min.y, min.z );
  20365. this.geometry.computeBoundingSphere();
  20366. this.geometry.verticesNeedUpdate = true;
  20367. this.matrixAutoUpdate = false;
  20368. this.matrixWorld = object.matrixWorld;
  20369. };
  20370. /**
  20371. * @author alteredq / http://alteredqualia.com/
  20372. *
  20373. * - shows frustum, line of sight and up of the camera
  20374. * - suitable for fast updates
  20375. * - based on frustum visualization in lightgl.js shadowmap example
  20376. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20377. */
  20378. THREE.CameraHelper = function ( camera ) {
  20379. THREE.Line.call( this );
  20380. var geometry = new THREE.Geometry();
  20381. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20382. var pointMap = {};
  20383. // colors
  20384. var hexFrustum = 0xffaa00;
  20385. var hexCone = 0xff0000;
  20386. var hexUp = 0x00aaff;
  20387. var hexTarget = 0xffffff;
  20388. var hexCross = 0x333333;
  20389. // near
  20390. addLine( "n1", "n2", hexFrustum );
  20391. addLine( "n2", "n4", hexFrustum );
  20392. addLine( "n4", "n3", hexFrustum );
  20393. addLine( "n3", "n1", hexFrustum );
  20394. // far
  20395. addLine( "f1", "f2", hexFrustum );
  20396. addLine( "f2", "f4", hexFrustum );
  20397. addLine( "f4", "f3", hexFrustum );
  20398. addLine( "f3", "f1", hexFrustum );
  20399. // sides
  20400. addLine( "n1", "f1", hexFrustum );
  20401. addLine( "n2", "f2", hexFrustum );
  20402. addLine( "n3", "f3", hexFrustum );
  20403. addLine( "n4", "f4", hexFrustum );
  20404. // cone
  20405. addLine( "p", "n1", hexCone );
  20406. addLine( "p", "n2", hexCone );
  20407. addLine( "p", "n3", hexCone );
  20408. addLine( "p", "n4", hexCone );
  20409. // up
  20410. addLine( "u1", "u2", hexUp );
  20411. addLine( "u2", "u3", hexUp );
  20412. addLine( "u3", "u1", hexUp );
  20413. // target
  20414. addLine( "c", "t", hexTarget );
  20415. addLine( "p", "c", hexCross );
  20416. // cross
  20417. addLine( "cn1", "cn2", hexCross );
  20418. addLine( "cn3", "cn4", hexCross );
  20419. addLine( "cf1", "cf2", hexCross );
  20420. addLine( "cf3", "cf4", hexCross );
  20421. function addLine( a, b, hex ) {
  20422. addPoint( a, hex );
  20423. addPoint( b, hex );
  20424. }
  20425. function addPoint( id, hex ) {
  20426. geometry.vertices.push( new THREE.Vector3() );
  20427. geometry.colors.push( new THREE.Color( hex ) );
  20428. if ( pointMap[ id ] === undefined ) {
  20429. pointMap[ id ] = [];
  20430. }
  20431. pointMap[ id ].push( geometry.vertices.length - 1 );
  20432. }
  20433. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20434. this.camera = camera;
  20435. this.matrixWorld = camera.matrixWorld;
  20436. this.matrixAutoUpdate = false;
  20437. this.pointMap = pointMap;
  20438. this.update();
  20439. };
  20440. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20441. THREE.CameraHelper.prototype.update = function () {
  20442. var vector = new THREE.Vector3();
  20443. var camera = new THREE.Camera();
  20444. var projector = new THREE.Projector();
  20445. return function () {
  20446. var scope = this;
  20447. var w = 1, h = 1;
  20448. // we need just camera projection matrix
  20449. // world matrix must be identity
  20450. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20451. // center / target
  20452. setPoint( "c", 0, 0, -1 );
  20453. setPoint( "t", 0, 0, 1 );
  20454. // near
  20455. setPoint( "n1", -w, -h, -1 );
  20456. setPoint( "n2", w, -h, -1 );
  20457. setPoint( "n3", -w, h, -1 );
  20458. setPoint( "n4", w, h, -1 );
  20459. // far
  20460. setPoint( "f1", -w, -h, 1 );
  20461. setPoint( "f2", w, -h, 1 );
  20462. setPoint( "f3", -w, h, 1 );
  20463. setPoint( "f4", w, h, 1 );
  20464. // up
  20465. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20466. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20467. setPoint( "u3", 0, h * 2, -1 );
  20468. // cross
  20469. setPoint( "cf1", -w, 0, 1 );
  20470. setPoint( "cf2", w, 0, 1 );
  20471. setPoint( "cf3", 0, -h, 1 );
  20472. setPoint( "cf4", 0, h, 1 );
  20473. setPoint( "cn1", -w, 0, -1 );
  20474. setPoint( "cn2", w, 0, -1 );
  20475. setPoint( "cn3", 0, -h, -1 );
  20476. setPoint( "cn4", 0, h, -1 );
  20477. function setPoint( point, x, y, z ) {
  20478. vector.set( x, y, z );
  20479. projector.unprojectVector( vector, camera );
  20480. var points = scope.pointMap[ point ];
  20481. if ( points !== undefined ) {
  20482. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20483. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20484. }
  20485. }
  20486. }
  20487. this.geometry.verticesNeedUpdate = true;
  20488. };
  20489. }();
  20490. /**
  20491. * @author alteredq / http://alteredqualia.com/
  20492. * @author mrdoob / http://mrdoob.com/
  20493. */
  20494. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20495. THREE.Object3D.call( this );
  20496. this.matrixAutoUpdate = false;
  20497. this.light = light;
  20498. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20499. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20500. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20501. this.lightSphere = new THREE.Mesh( geometry, material );
  20502. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20503. this.lightSphere.matrixAutoUpdate = false;
  20504. this.add( this.lightSphere );
  20505. /*
  20506. this.targetSphere = new THREE.Mesh( geometry, material );
  20507. this.targetSphere.position = this.light.target.position;
  20508. this.add( this.targetSphere );
  20509. */
  20510. geometry = new THREE.Geometry();
  20511. geometry.vertices.push( this.light.position );
  20512. geometry.vertices.push( this.light.target.position );
  20513. geometry.computeLineDistances();
  20514. material = new THREE.LineDashedMaterial( { dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20515. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20516. this.targetLine = new THREE.Line( geometry, material );
  20517. this.add( this.targetLine );
  20518. }
  20519. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20520. THREE.DirectionalLightHelper.prototype.update = function () {
  20521. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20522. this.targetLine.geometry.computeLineDistances();
  20523. this.targetLine.geometry.verticesNeedUpdate = true;
  20524. this.targetLine.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20525. };
  20526. /**
  20527. * @author mrdoob / http://mrdoob.com/
  20528. */
  20529. THREE.GridHelper = function ( size, step ) {
  20530. var geometry = new THREE.Geometry();
  20531. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20532. var color1 = new THREE.Color( 0x444444 ), color2 = new THREE.Color( 0x888888 );
  20533. for ( var i = - size; i <= size; i += step ) {
  20534. geometry.vertices.push(
  20535. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20536. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20537. );
  20538. var color = i === 0 ? color1 : color2;
  20539. geometry.colors.push( color, color, color, color );
  20540. }
  20541. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20542. };
  20543. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20544. /**
  20545. * @author alteredq / http://alteredqualia.com/
  20546. * @author mrdoob / http://mrdoob.com/
  20547. */
  20548. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20549. THREE.Object3D.call( this );
  20550. this.light = light;
  20551. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20552. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20553. for ( var i = 0, il = 8; i < il; i ++ ) {
  20554. geometry.faces[ i ].materialIndex = i < 4 ? 0 : 1;
  20555. }
  20556. var materialSky = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20557. materialSky.color.copy( light.color ).multiplyScalar( light.intensity );
  20558. var materialGround = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20559. materialGround.color.copy( light.groundColor ).multiplyScalar( light.intensity );
  20560. this.lightSphere = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ materialSky, materialGround ] ) );
  20561. this.lightSphere.position = light.position;
  20562. this.lightSphere.lookAt( new THREE.Vector3() );
  20563. this.add( this.lightSphere );
  20564. };
  20565. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20566. THREE.HemisphereLightHelper.prototype.update = function () {
  20567. this.lightSphere.lookAt( new THREE.Vector3() );
  20568. this.lightSphere.material.materials[ 0 ].color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20569. this.lightSphere.material.materials[ 1 ].color.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20570. };
  20571. /**
  20572. * @author alteredq / http://alteredqualia.com/
  20573. * @author mrdoob / http://mrdoob.com/
  20574. */
  20575. THREE.PointLightHelper = function ( light, sphereSize ) {
  20576. THREE.Object3D.call( this );
  20577. this.matrixAutoUpdate = false;
  20578. this.light = light;
  20579. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20580. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20581. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20582. this.lightSphere = new THREE.Mesh( geometry, material );
  20583. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20584. this.lightSphere.matrixAutoUpdate = false;
  20585. this.add( this.lightSphere );
  20586. /*
  20587. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20588. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20589. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20590. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20591. var d = light.distance;
  20592. if ( d === 0.0 ) {
  20593. this.lightDistance.visible = false;
  20594. } else {
  20595. this.lightDistance.scale.set( d, d, d );
  20596. }
  20597. this.add( this.lightDistance );
  20598. */
  20599. };
  20600. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20601. THREE.PointLightHelper.prototype.update = function () {
  20602. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20603. /*
  20604. this.lightDistance.material.color.copy( this.color );
  20605. var d = this.light.distance;
  20606. if ( d === 0.0 ) {
  20607. this.lightDistance.visible = false;
  20608. } else {
  20609. this.lightDistance.visible = true;
  20610. this.lightDistance.scale.set( d, d, d );
  20611. }
  20612. */
  20613. };
  20614. /**
  20615. * @author alteredq / http://alteredqualia.com/
  20616. * @author mrdoob / http://mrdoob.com/
  20617. * @author WestLangley / http://github.com/WestLangley
  20618. */
  20619. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20620. THREE.Object3D.call( this );
  20621. this.matrixAutoUpdate = false;
  20622. this.light = light;
  20623. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20624. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20625. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20626. this.lightSphere = new THREE.Mesh( geometry, material );
  20627. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20628. this.lightSphere.matrixAutoUpdate = false;
  20629. this.add( this.lightSphere );
  20630. geometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20631. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20632. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20633. material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20634. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20635. this.lightCone = new THREE.Mesh( geometry, material );
  20636. this.lightCone.position = this.light.position;
  20637. var coneLength = light.distance ? light.distance : 10000;
  20638. var coneWidth = coneLength * Math.tan( light.angle );
  20639. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20640. this.lightCone.lookAt( this.light.target.position );
  20641. this.add( this.lightCone );
  20642. };
  20643. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20644. THREE.SpotLightHelper.prototype.update = function () {
  20645. var coneLength = this.light.distance ? this.light.distance : 10000;
  20646. var coneWidth = coneLength * Math.tan( this.light.angle );
  20647. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20648. this.lightCone.lookAt( this.light.target.position );
  20649. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20650. this.lightCone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20651. };
  20652. /**
  20653. * @author alteredq / http://alteredqualia.com/
  20654. */
  20655. THREE.ImmediateRenderObject = function () {
  20656. THREE.Object3D.call( this );
  20657. this.render = function ( renderCallback ) { };
  20658. };
  20659. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20660. /**
  20661. * @author mikael emtinger / http://gomo.se/
  20662. * @author alteredq / http://alteredqualia.com/
  20663. */
  20664. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20665. THREE.Object3D.call( this );
  20666. this.lensFlares = [];
  20667. this.positionScreen = new THREE.Vector3();
  20668. this.customUpdateCallback = undefined;
  20669. if( texture !== undefined ) {
  20670. this.add( texture, size, distance, blending, color );
  20671. }
  20672. };
  20673. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20674. /*
  20675. * Add: adds another flare
  20676. */
  20677. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20678. if( size === undefined ) size = -1;
  20679. if( distance === undefined ) distance = 0;
  20680. if( opacity === undefined ) opacity = 1;
  20681. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20682. if( blending === undefined ) blending = THREE.NormalBlending;
  20683. distance = Math.min( distance, Math.max( 0, distance ) );
  20684. this.lensFlares.push( { texture: texture, // THREE.Texture
  20685. size: size, // size in pixels (-1 = use texture.width)
  20686. distance: distance, // distance (0-1) from light source (0=at light source)
  20687. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20688. scale: 1, // scale
  20689. rotation: 1, // rotation
  20690. opacity: opacity, // opacity
  20691. color: color, // color
  20692. blending: blending } ); // blending
  20693. };
  20694. /*
  20695. * Update lens flares update positions on all flares based on the screen position
  20696. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20697. */
  20698. THREE.LensFlare.prototype.updateLensFlares = function () {
  20699. var f, fl = this.lensFlares.length;
  20700. var flare;
  20701. var vecX = -this.positionScreen.x * 2;
  20702. var vecY = -this.positionScreen.y * 2;
  20703. for( f = 0; f < fl; f ++ ) {
  20704. flare = this.lensFlares[ f ];
  20705. flare.x = this.positionScreen.x + vecX * flare.distance;
  20706. flare.y = this.positionScreen.y + vecY * flare.distance;
  20707. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20708. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20709. }
  20710. };
  20711. /**
  20712. * @author alteredq / http://alteredqualia.com/
  20713. */
  20714. THREE.MorphBlendMesh = function( geometry, material ) {
  20715. THREE.Mesh.call( this, geometry, material );
  20716. this.animationsMap = {};
  20717. this.animationsList = [];
  20718. // prepare default animation
  20719. // (all frames played together in 1 second)
  20720. var numFrames = this.geometry.morphTargets.length;
  20721. var name = "__default";
  20722. var startFrame = 0;
  20723. var endFrame = numFrames - 1;
  20724. var fps = numFrames / 1;
  20725. this.createAnimation( name, startFrame, endFrame, fps );
  20726. this.setAnimationWeight( name, 1 );
  20727. };
  20728. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20729. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20730. var animation = {
  20731. startFrame: start,
  20732. endFrame: end,
  20733. length: end - start + 1,
  20734. fps: fps,
  20735. duration: ( end - start ) / fps,
  20736. lastFrame: 0,
  20737. currentFrame: 0,
  20738. active: false,
  20739. time: 0,
  20740. direction: 1,
  20741. weight: 1,
  20742. directionBackwards: false,
  20743. mirroredLoop: false
  20744. };
  20745. this.animationsMap[ name ] = animation;
  20746. this.animationsList.push( animation );
  20747. };
  20748. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20749. var pattern = /([a-z]+)(\d+)/;
  20750. var firstAnimation, frameRanges = {};
  20751. var geometry = this.geometry;
  20752. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20753. var morph = geometry.morphTargets[ i ];
  20754. var chunks = morph.name.match( pattern );
  20755. if ( chunks && chunks.length > 1 ) {
  20756. var name = chunks[ 1 ];
  20757. var num = chunks[ 2 ];
  20758. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20759. var range = frameRanges[ name ];
  20760. if ( i < range.start ) range.start = i;
  20761. if ( i > range.end ) range.end = i;
  20762. if ( ! firstAnimation ) firstAnimation = name;
  20763. }
  20764. }
  20765. for ( var name in frameRanges ) {
  20766. var range = frameRanges[ name ];
  20767. this.createAnimation( name, range.start, range.end, fps );
  20768. }
  20769. this.firstAnimation = firstAnimation;
  20770. };
  20771. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20772. var animation = this.animationsMap[ name ];
  20773. if ( animation ) {
  20774. animation.direction = 1;
  20775. animation.directionBackwards = false;
  20776. }
  20777. };
  20778. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20779. var animation = this.animationsMap[ name ];
  20780. if ( animation ) {
  20781. animation.direction = -1;
  20782. animation.directionBackwards = true;
  20783. }
  20784. };
  20785. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20786. var animation = this.animationsMap[ name ];
  20787. if ( animation ) {
  20788. animation.fps = fps;
  20789. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20790. }
  20791. };
  20792. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20793. var animation = this.animationsMap[ name ];
  20794. if ( animation ) {
  20795. animation.duration = duration;
  20796. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20797. }
  20798. };
  20799. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20800. var animation = this.animationsMap[ name ];
  20801. if ( animation ) {
  20802. animation.weight = weight;
  20803. }
  20804. };
  20805. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20806. var animation = this.animationsMap[ name ];
  20807. if ( animation ) {
  20808. animation.time = time;
  20809. }
  20810. };
  20811. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20812. var time = 0;
  20813. var animation = this.animationsMap[ name ];
  20814. if ( animation ) {
  20815. time = animation.time;
  20816. }
  20817. return time;
  20818. };
  20819. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20820. var duration = -1;
  20821. var animation = this.animationsMap[ name ];
  20822. if ( animation ) {
  20823. duration = animation.duration;
  20824. }
  20825. return duration;
  20826. };
  20827. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20828. var animation = this.animationsMap[ name ];
  20829. if ( animation ) {
  20830. animation.time = 0;
  20831. animation.active = true;
  20832. } else {
  20833. console.warn( "animation[" + name + "] undefined" );
  20834. }
  20835. };
  20836. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20837. var animation = this.animationsMap[ name ];
  20838. if ( animation ) {
  20839. animation.active = false;
  20840. }
  20841. };
  20842. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20843. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20844. var animation = this.animationsList[ i ];
  20845. if ( ! animation.active ) continue;
  20846. var frameTime = animation.duration / animation.length;
  20847. animation.time += animation.direction * delta;
  20848. if ( animation.mirroredLoop ) {
  20849. if ( animation.time > animation.duration || animation.time < 0 ) {
  20850. animation.direction *= -1;
  20851. if ( animation.time > animation.duration ) {
  20852. animation.time = animation.duration;
  20853. animation.directionBackwards = true;
  20854. }
  20855. if ( animation.time < 0 ) {
  20856. animation.time = 0;
  20857. animation.directionBackwards = false;
  20858. }
  20859. }
  20860. } else {
  20861. animation.time = animation.time % animation.duration;
  20862. if ( animation.time < 0 ) animation.time += animation.duration;
  20863. }
  20864. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20865. var weight = animation.weight;
  20866. if ( keyframe !== animation.currentFrame ) {
  20867. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20868. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20869. this.morphTargetInfluences[ keyframe ] = 0;
  20870. animation.lastFrame = animation.currentFrame;
  20871. animation.currentFrame = keyframe;
  20872. }
  20873. var mix = ( animation.time % frameTime ) / frameTime;
  20874. if ( animation.directionBackwards ) mix = 1 - mix;
  20875. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20876. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20877. }
  20878. };
  20879. /**
  20880. * @author mikael emtinger / http://gomo.se/
  20881. * @author alteredq / http://alteredqualia.com/
  20882. */
  20883. THREE.LensFlarePlugin = function () {
  20884. var _gl, _renderer, _precision, _lensFlare = {};
  20885. this.init = function ( renderer ) {
  20886. _gl = renderer.context;
  20887. _renderer = renderer;
  20888. _precision = renderer.getPrecision();
  20889. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20890. _lensFlare.faces = new Uint16Array( 6 );
  20891. var i = 0;
  20892. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20893. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20894. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20895. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20896. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20897. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20898. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20899. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20900. i = 0;
  20901. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20902. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20903. // buffers
  20904. _lensFlare.vertexBuffer = _gl.createBuffer();
  20905. _lensFlare.elementBuffer = _gl.createBuffer();
  20906. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20907. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20908. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20909. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20910. // textures
  20911. _lensFlare.tempTexture = _gl.createTexture();
  20912. _lensFlare.occlusionTexture = _gl.createTexture();
  20913. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20914. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20915. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20916. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20917. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20918. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20919. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20920. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20921. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20922. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20923. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20924. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20925. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20926. _lensFlare.hasVertexTexture = false;
  20927. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20928. } else {
  20929. _lensFlare.hasVertexTexture = true;
  20930. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20931. }
  20932. _lensFlare.attributes = {};
  20933. _lensFlare.uniforms = {};
  20934. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20935. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20936. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20937. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20938. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20939. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20940. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20941. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20942. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20943. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20944. };
  20945. /*
  20946. * Render lens flares
  20947. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20948. * reads these back and calculates occlusion.
  20949. * Then _lensFlare.update_lensFlares() is called to re-position and
  20950. * update transparency of flares. Then they are rendered.
  20951. *
  20952. */
  20953. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20954. var flares = scene.__webglFlares,
  20955. nFlares = flares.length;
  20956. if ( ! nFlares ) return;
  20957. var tempPosition = new THREE.Vector3();
  20958. var invAspect = viewportHeight / viewportWidth,
  20959. halfViewportWidth = viewportWidth * 0.5,
  20960. halfViewportHeight = viewportHeight * 0.5;
  20961. var size = 16 / viewportHeight,
  20962. scale = new THREE.Vector2( size * invAspect, size );
  20963. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20964. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20965. var uniforms = _lensFlare.uniforms,
  20966. attributes = _lensFlare.attributes;
  20967. // set _lensFlare program and reset blending
  20968. _gl.useProgram( _lensFlare.program );
  20969. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20970. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20971. // loop through all lens flares to update their occlusion and positions
  20972. // setup gl and common used attribs/unforms
  20973. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20974. _gl.uniform1i( uniforms.map, 1 );
  20975. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20976. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20977. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20978. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20979. _gl.disable( _gl.CULL_FACE );
  20980. _gl.depthMask( false );
  20981. var i, j, jl, flare, sprite;
  20982. for ( i = 0; i < nFlares; i ++ ) {
  20983. size = 16 / viewportHeight;
  20984. scale.set( size * invAspect, size );
  20985. // calc object screen position
  20986. flare = flares[ i ];
  20987. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20988. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20989. tempPosition.applyProjection( camera.projectionMatrix );
  20990. // setup arrays for gl programs
  20991. screenPosition.copy( tempPosition )
  20992. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20993. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20994. // screen cull
  20995. if ( _lensFlare.hasVertexTexture || (
  20996. screenPositionPixels.x > 0 &&
  20997. screenPositionPixels.x < viewportWidth &&
  20998. screenPositionPixels.y > 0 &&
  20999. screenPositionPixels.y < viewportHeight ) ) {
  21000. // save current RGB to temp texture
  21001. _gl.activeTexture( _gl.TEXTURE1 );
  21002. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21003. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21004. // render pink quad
  21005. _gl.uniform1i( uniforms.renderType, 0 );
  21006. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21007. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21008. _gl.disable( _gl.BLEND );
  21009. _gl.enable( _gl.DEPTH_TEST );
  21010. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21011. // copy result to occlusionMap
  21012. _gl.activeTexture( _gl.TEXTURE0 );
  21013. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21014. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21015. // restore graphics
  21016. _gl.uniform1i( uniforms.renderType, 1 );
  21017. _gl.disable( _gl.DEPTH_TEST );
  21018. _gl.activeTexture( _gl.TEXTURE1 );
  21019. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21020. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21021. // update object positions
  21022. flare.positionScreen.copy( screenPosition )
  21023. if ( flare.customUpdateCallback ) {
  21024. flare.customUpdateCallback( flare );
  21025. } else {
  21026. flare.updateLensFlares();
  21027. }
  21028. // render flares
  21029. _gl.uniform1i( uniforms.renderType, 2 );
  21030. _gl.enable( _gl.BLEND );
  21031. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21032. sprite = flare.lensFlares[ j ];
  21033. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21034. screenPosition.x = sprite.x;
  21035. screenPosition.y = sprite.y;
  21036. screenPosition.z = sprite.z;
  21037. size = sprite.size * sprite.scale / viewportHeight;
  21038. scale.x = size * invAspect;
  21039. scale.y = size;
  21040. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21041. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21042. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21043. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21044. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21045. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21046. _renderer.setTexture( sprite.texture, 1 );
  21047. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21048. }
  21049. }
  21050. }
  21051. }
  21052. // restore gl
  21053. _gl.enable( _gl.CULL_FACE );
  21054. _gl.enable( _gl.DEPTH_TEST );
  21055. _gl.depthMask( true );
  21056. };
  21057. function createProgram ( shader, precision ) {
  21058. var program = _gl.createProgram();
  21059. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21060. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21061. var prefix = "precision " + precision + " float;\n";
  21062. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21063. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21064. _gl.compileShader( fragmentShader );
  21065. _gl.compileShader( vertexShader );
  21066. _gl.attachShader( program, fragmentShader );
  21067. _gl.attachShader( program, vertexShader );
  21068. _gl.linkProgram( program );
  21069. return program;
  21070. };
  21071. };
  21072. /**
  21073. * @author alteredq / http://alteredqualia.com/
  21074. */
  21075. THREE.ShadowMapPlugin = function () {
  21076. var _gl,
  21077. _renderer,
  21078. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21079. _frustum = new THREE.Frustum(),
  21080. _projScreenMatrix = new THREE.Matrix4(),
  21081. _min = new THREE.Vector3(),
  21082. _max = new THREE.Vector3(),
  21083. _matrixPosition = new THREE.Vector3();
  21084. this.init = function ( renderer ) {
  21085. _gl = renderer.context;
  21086. _renderer = renderer;
  21087. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21088. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21089. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21090. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21091. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21092. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21093. _depthMaterial._shadowPass = true;
  21094. _depthMaterialMorph._shadowPass = true;
  21095. _depthMaterialSkin._shadowPass = true;
  21096. _depthMaterialMorphSkin._shadowPass = true;
  21097. };
  21098. this.render = function ( scene, camera ) {
  21099. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21100. this.update( scene, camera );
  21101. };
  21102. this.update = function ( scene, camera ) {
  21103. var i, il, j, jl, n,
  21104. shadowMap, shadowMatrix, shadowCamera,
  21105. program, buffer, material,
  21106. webglObject, object, light,
  21107. renderList,
  21108. lights = [],
  21109. k = 0,
  21110. fog = null;
  21111. // set GL state for depth map
  21112. _gl.clearColor( 1, 1, 1, 1 );
  21113. _gl.disable( _gl.BLEND );
  21114. _gl.enable( _gl.CULL_FACE );
  21115. _gl.frontFace( _gl.CCW );
  21116. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21117. _gl.cullFace( _gl.FRONT );
  21118. } else {
  21119. _gl.cullFace( _gl.BACK );
  21120. }
  21121. _renderer.setDepthTest( true );
  21122. // preprocess lights
  21123. // - skip lights that are not casting shadows
  21124. // - create virtual lights for cascaded shadow maps
  21125. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21126. light = scene.__lights[ i ];
  21127. if ( ! light.castShadow ) continue;
  21128. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21129. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21130. var virtualLight;
  21131. if ( ! light.shadowCascadeArray[ n ] ) {
  21132. virtualLight = createVirtualLight( light, n );
  21133. virtualLight.originalCamera = camera;
  21134. var gyro = new THREE.Gyroscope();
  21135. gyro.position = light.shadowCascadeOffset;
  21136. gyro.add( virtualLight );
  21137. gyro.add( virtualLight.target );
  21138. camera.add( gyro );
  21139. light.shadowCascadeArray[ n ] = virtualLight;
  21140. console.log( "Created virtualLight", virtualLight );
  21141. } else {
  21142. virtualLight = light.shadowCascadeArray[ n ];
  21143. }
  21144. updateVirtualLight( light, n );
  21145. lights[ k ] = virtualLight;
  21146. k ++;
  21147. }
  21148. } else {
  21149. lights[ k ] = light;
  21150. k ++;
  21151. }
  21152. }
  21153. // render depth map
  21154. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21155. light = lights[ i ];
  21156. if ( ! light.shadowMap ) {
  21157. var shadowFilter = THREE.LinearFilter;
  21158. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21159. shadowFilter = THREE.NearestFilter;
  21160. }
  21161. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21162. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21163. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21164. light.shadowMatrix = new THREE.Matrix4();
  21165. }
  21166. if ( ! light.shadowCamera ) {
  21167. if ( light instanceof THREE.SpotLight ) {
  21168. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21169. } else if ( light instanceof THREE.DirectionalLight ) {
  21170. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21171. } else {
  21172. console.error( "Unsupported light type for shadow" );
  21173. continue;
  21174. }
  21175. scene.add( light.shadowCamera );
  21176. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21177. }
  21178. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21179. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21180. light.shadowCamera.add( light.cameraHelper );
  21181. }
  21182. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21183. updateShadowCamera( camera, light );
  21184. }
  21185. shadowMap = light.shadowMap;
  21186. shadowMatrix = light.shadowMatrix;
  21187. shadowCamera = light.shadowCamera;
  21188. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21189. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21190. shadowCamera.lookAt( _matrixPosition );
  21191. shadowCamera.updateMatrixWorld();
  21192. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21193. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21194. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21195. // compute shadow matrix
  21196. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21197. 0.0, 0.5, 0.0, 0.5,
  21198. 0.0, 0.0, 0.5, 0.5,
  21199. 0.0, 0.0, 0.0, 1.0 );
  21200. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21201. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21202. // update camera matrices and frustum
  21203. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21204. _frustum.setFromMatrix( _projScreenMatrix );
  21205. // render shadow map
  21206. _renderer.setRenderTarget( shadowMap );
  21207. _renderer.clear();
  21208. // set object matrices & frustum culling
  21209. renderList = scene.__webglObjects;
  21210. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21211. webglObject = renderList[ j ];
  21212. object = webglObject.object;
  21213. webglObject.render = false;
  21214. if ( object.visible && object.castShadow ) {
  21215. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21216. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21217. webglObject.render = true;
  21218. }
  21219. }
  21220. }
  21221. // render regular objects
  21222. var objectMaterial, useMorphing, useSkinning;
  21223. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21224. webglObject = renderList[ j ];
  21225. if ( webglObject.render ) {
  21226. object = webglObject.object;
  21227. buffer = webglObject.buffer;
  21228. // culling is overriden globally for all objects
  21229. // while rendering depth map
  21230. // need to deal with MeshFaceMaterial somehow
  21231. // in that case just use the first of material.materials for now
  21232. // (proper solution would require to break objects by materials
  21233. // similarly to regular rendering and then set corresponding
  21234. // depth materials per each chunk instead of just once per object)
  21235. objectMaterial = getObjectMaterial( object );
  21236. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21237. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21238. if ( object.customDepthMaterial ) {
  21239. material = object.customDepthMaterial;
  21240. } else if ( useSkinning ) {
  21241. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21242. } else if ( useMorphing ) {
  21243. material = _depthMaterialMorph;
  21244. } else {
  21245. material = _depthMaterial;
  21246. }
  21247. if ( buffer instanceof THREE.BufferGeometry ) {
  21248. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21249. } else {
  21250. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21251. }
  21252. }
  21253. }
  21254. // set matrices and render immediate objects
  21255. renderList = scene.__webglObjectsImmediate;
  21256. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21257. webglObject = renderList[ j ];
  21258. object = webglObject.object;
  21259. if ( object.visible && object.castShadow ) {
  21260. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21261. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21262. }
  21263. }
  21264. }
  21265. // restore GL state
  21266. var clearColor = _renderer.getClearColor(),
  21267. clearAlpha = _renderer.getClearAlpha();
  21268. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21269. _gl.enable( _gl.BLEND );
  21270. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21271. _gl.cullFace( _gl.BACK );
  21272. }
  21273. };
  21274. function createVirtualLight( light, cascade ) {
  21275. var virtualLight = new THREE.DirectionalLight();
  21276. virtualLight.isVirtual = true;
  21277. virtualLight.onlyShadow = true;
  21278. virtualLight.castShadow = true;
  21279. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21280. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21281. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21282. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21283. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21284. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21285. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21286. virtualLight.shadowDarkness = light.shadowDarkness;
  21287. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21288. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21289. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21290. virtualLight.pointsWorld = [];
  21291. virtualLight.pointsFrustum = [];
  21292. var pointsWorld = virtualLight.pointsWorld,
  21293. pointsFrustum = virtualLight.pointsFrustum;
  21294. for ( var i = 0; i < 8; i ++ ) {
  21295. pointsWorld[ i ] = new THREE.Vector3();
  21296. pointsFrustum[ i ] = new THREE.Vector3();
  21297. }
  21298. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21299. var farZ = light.shadowCascadeFarZ[ cascade ];
  21300. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21301. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21302. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21303. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21304. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21305. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21306. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21307. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21308. return virtualLight;
  21309. }
  21310. // Synchronize virtual light with the original light
  21311. function updateVirtualLight( light, cascade ) {
  21312. var virtualLight = light.shadowCascadeArray[ cascade ];
  21313. virtualLight.position.copy( light.position );
  21314. virtualLight.target.position.copy( light.target.position );
  21315. virtualLight.lookAt( virtualLight.target );
  21316. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21317. virtualLight.shadowDarkness = light.shadowDarkness;
  21318. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21319. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21320. var farZ = light.shadowCascadeFarZ[ cascade ];
  21321. var pointsFrustum = virtualLight.pointsFrustum;
  21322. pointsFrustum[ 0 ].z = nearZ;
  21323. pointsFrustum[ 1 ].z = nearZ;
  21324. pointsFrustum[ 2 ].z = nearZ;
  21325. pointsFrustum[ 3 ].z = nearZ;
  21326. pointsFrustum[ 4 ].z = farZ;
  21327. pointsFrustum[ 5 ].z = farZ;
  21328. pointsFrustum[ 6 ].z = farZ;
  21329. pointsFrustum[ 7 ].z = farZ;
  21330. }
  21331. // Fit shadow camera's ortho frustum to camera frustum
  21332. function updateShadowCamera( camera, light ) {
  21333. var shadowCamera = light.shadowCamera,
  21334. pointsFrustum = light.pointsFrustum,
  21335. pointsWorld = light.pointsWorld;
  21336. _min.set( Infinity, Infinity, Infinity );
  21337. _max.set( -Infinity, -Infinity, -Infinity );
  21338. for ( var i = 0; i < 8; i ++ ) {
  21339. var p = pointsWorld[ i ];
  21340. p.copy( pointsFrustum[ i ] );
  21341. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21342. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21343. if ( p.x < _min.x ) _min.x = p.x;
  21344. if ( p.x > _max.x ) _max.x = p.x;
  21345. if ( p.y < _min.y ) _min.y = p.y;
  21346. if ( p.y > _max.y ) _max.y = p.y;
  21347. if ( p.z < _min.z ) _min.z = p.z;
  21348. if ( p.z > _max.z ) _max.z = p.z;
  21349. }
  21350. shadowCamera.left = _min.x;
  21351. shadowCamera.right = _max.x;
  21352. shadowCamera.top = _max.y;
  21353. shadowCamera.bottom = _min.y;
  21354. // can't really fit near/far
  21355. //shadowCamera.near = _min.z;
  21356. //shadowCamera.far = _max.z;
  21357. shadowCamera.updateProjectionMatrix();
  21358. }
  21359. // For the moment just ignore objects that have multiple materials with different animation methods
  21360. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21361. function getObjectMaterial( object ) {
  21362. return object.material instanceof THREE.MeshFaceMaterial
  21363. ? object.material.materials[ 0 ]
  21364. : object.material;
  21365. };
  21366. };
  21367. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21368. /**
  21369. * @author mikael emtinger / http://gomo.se/
  21370. * @author alteredq / http://alteredqualia.com/
  21371. */
  21372. THREE.SpritePlugin = function () {
  21373. var _gl, _renderer, _precision, _sprite = {};
  21374. this.init = function ( renderer ) {
  21375. _gl = renderer.context;
  21376. _renderer = renderer;
  21377. _precision = renderer.getPrecision();
  21378. _sprite.vertices = new Float32Array( 8 + 8 );
  21379. _sprite.faces = new Uint16Array( 6 );
  21380. var i = 0;
  21381. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21382. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21383. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21384. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21385. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21386. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21387. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21388. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21389. i = 0;
  21390. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21391. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21392. _sprite.vertexBuffer = _gl.createBuffer();
  21393. _sprite.elementBuffer = _gl.createBuffer();
  21394. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21395. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21396. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21397. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21398. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21399. _sprite.attributes = {};
  21400. _sprite.uniforms = {};
  21401. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21402. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21403. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21404. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21405. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21406. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21407. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21408. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21409. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21410. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21411. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21412. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21413. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21414. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21415. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21416. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21417. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21418. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21419. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21420. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21421. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21422. };
  21423. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21424. var sprites = scene.__webglSprites,
  21425. nSprites = sprites.length;
  21426. if ( ! nSprites ) return;
  21427. var attributes = _sprite.attributes,
  21428. uniforms = _sprite.uniforms;
  21429. var invAspect = viewportHeight / viewportWidth;
  21430. var halfViewportWidth = viewportWidth * 0.5,
  21431. halfViewportHeight = viewportHeight * 0.5;
  21432. // setup gl
  21433. _gl.useProgram( _sprite.program );
  21434. _gl.enableVertexAttribArray( attributes.position );
  21435. _gl.enableVertexAttribArray( attributes.uv );
  21436. _gl.disable( _gl.CULL_FACE );
  21437. _gl.enable( _gl.BLEND );
  21438. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21439. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21440. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21441. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21442. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21443. _gl.activeTexture( _gl.TEXTURE0 );
  21444. _gl.uniform1i( uniforms.map, 0 );
  21445. var oldFogType = 0;
  21446. var sceneFogType = 0;
  21447. var fog = scene.fog;
  21448. if ( fog ) {
  21449. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21450. if ( fog instanceof THREE.Fog ) {
  21451. _gl.uniform1f( uniforms.fogNear, fog.near );
  21452. _gl.uniform1f( uniforms.fogFar, fog.far );
  21453. _gl.uniform1i( uniforms.fogType, 1 );
  21454. oldFogType = 1;
  21455. sceneFogType = 1;
  21456. } else if ( fog instanceof THREE.FogExp2 ) {
  21457. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21458. _gl.uniform1i( uniforms.fogType, 2 );
  21459. oldFogType = 2;
  21460. sceneFogType = 2;
  21461. }
  21462. } else {
  21463. _gl.uniform1i( uniforms.fogType, 0 );
  21464. oldFogType = 0;
  21465. sceneFogType = 0;
  21466. }
  21467. // update positions and sort
  21468. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21469. for( i = 0; i < nSprites; i ++ ) {
  21470. sprite = sprites[ i ];
  21471. material = sprite.material;
  21472. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21473. if ( ! material.useScreenCoordinates ) {
  21474. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21475. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21476. } else {
  21477. sprite.z = - sprite.position.z;
  21478. }
  21479. }
  21480. sprites.sort( painterSortStable );
  21481. // render all sprites
  21482. for( i = 0; i < nSprites; i ++ ) {
  21483. sprite = sprites[ i ];
  21484. material = sprite.material;
  21485. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21486. if ( material.map && material.map.image && material.map.image.width ) {
  21487. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21488. if ( material.useScreenCoordinates === true ) {
  21489. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21490. _gl.uniform3f(
  21491. uniforms.screenPosition,
  21492. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21493. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21494. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21495. );
  21496. scale[ 0 ] = _renderer.devicePixelRatio;
  21497. scale[ 1 ] = _renderer.devicePixelRatio;
  21498. } else {
  21499. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21500. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21501. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21502. scale[ 0 ] = 1;
  21503. scale[ 1 ] = 1;
  21504. }
  21505. if ( scene.fog && material.fog ) {
  21506. fogType = sceneFogType;
  21507. } else {
  21508. fogType = 0;
  21509. }
  21510. if ( oldFogType !== fogType ) {
  21511. _gl.uniform1i( uniforms.fogType, fogType );
  21512. oldFogType = fogType;
  21513. }
  21514. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21515. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21516. scale[ 1 ] *= size * sprite.scale.y;
  21517. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21518. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21519. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21520. _gl.uniform1f( uniforms.opacity, material.opacity );
  21521. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21522. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21523. _gl.uniform2fv( uniforms.scale, scale );
  21524. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21525. _renderer.setDepthTest( material.depthTest );
  21526. _renderer.setDepthWrite( material.depthWrite );
  21527. _renderer.setTexture( material.map, 0 );
  21528. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21529. }
  21530. }
  21531. // restore gl
  21532. _gl.enable( _gl.CULL_FACE );
  21533. };
  21534. function createProgram ( shader, precision ) {
  21535. var program = _gl.createProgram();
  21536. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21537. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21538. var prefix = "precision " + precision + " float;\n";
  21539. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21540. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21541. _gl.compileShader( fragmentShader );
  21542. _gl.compileShader( vertexShader );
  21543. _gl.attachShader( program, fragmentShader );
  21544. _gl.attachShader( program, vertexShader );
  21545. _gl.linkProgram( program );
  21546. return program;
  21547. };
  21548. function painterSortStable ( a, b ) {
  21549. if ( a.z !== b.z ) {
  21550. return b.z - a.z;
  21551. } else {
  21552. return b.id - a.id;
  21553. }
  21554. };
  21555. };
  21556. /**
  21557. * @author alteredq / http://alteredqualia.com/
  21558. */
  21559. THREE.DepthPassPlugin = function () {
  21560. this.enabled = false;
  21561. this.renderTarget = null;
  21562. var _gl,
  21563. _renderer,
  21564. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21565. _frustum = new THREE.Frustum(),
  21566. _projScreenMatrix = new THREE.Matrix4();
  21567. this.init = function ( renderer ) {
  21568. _gl = renderer.context;
  21569. _renderer = renderer;
  21570. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21571. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21572. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21573. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21574. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21575. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21576. _depthMaterial._shadowPass = true;
  21577. _depthMaterialMorph._shadowPass = true;
  21578. _depthMaterialSkin._shadowPass = true;
  21579. _depthMaterialMorphSkin._shadowPass = true;
  21580. };
  21581. this.render = function ( scene, camera ) {
  21582. if ( ! this.enabled ) return;
  21583. this.update( scene, camera );
  21584. };
  21585. this.update = function ( scene, camera ) {
  21586. var i, il, j, jl, n,
  21587. program, buffer, material,
  21588. webglObject, object, light,
  21589. renderList,
  21590. fog = null;
  21591. // set GL state for depth map
  21592. _gl.clearColor( 1, 1, 1, 1 );
  21593. _gl.disable( _gl.BLEND );
  21594. _renderer.setDepthTest( true );
  21595. // update scene
  21596. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21597. // update camera matrices and frustum
  21598. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21599. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21600. _frustum.setFromMatrix( _projScreenMatrix );
  21601. // render depth map
  21602. _renderer.setRenderTarget( this.renderTarget );
  21603. _renderer.clear();
  21604. // set object matrices & frustum culling
  21605. renderList = scene.__webglObjects;
  21606. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21607. webglObject = renderList[ j ];
  21608. object = webglObject.object;
  21609. webglObject.render = false;
  21610. if ( object.visible ) {
  21611. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21612. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21613. webglObject.render = true;
  21614. }
  21615. }
  21616. }
  21617. // render regular objects
  21618. var objectMaterial, useMorphing, useSkinning;
  21619. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21620. webglObject = renderList[ j ];
  21621. if ( webglObject.render ) {
  21622. object = webglObject.object;
  21623. buffer = webglObject.buffer;
  21624. // todo: create proper depth material for particles
  21625. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21626. objectMaterial = getObjectMaterial( object );
  21627. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21628. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21629. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21630. if ( object.customDepthMaterial ) {
  21631. material = object.customDepthMaterial;
  21632. } else if ( useSkinning ) {
  21633. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21634. } else if ( useMorphing ) {
  21635. material = _depthMaterialMorph;
  21636. } else {
  21637. material = _depthMaterial;
  21638. }
  21639. if ( buffer instanceof THREE.BufferGeometry ) {
  21640. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21641. } else {
  21642. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21643. }
  21644. }
  21645. }
  21646. // set matrices and render immediate objects
  21647. renderList = scene.__webglObjectsImmediate;
  21648. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21649. webglObject = renderList[ j ];
  21650. object = webglObject.object;
  21651. if ( object.visible ) {
  21652. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21653. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21654. }
  21655. }
  21656. // restore GL state
  21657. var clearColor = _renderer.getClearColor(),
  21658. clearAlpha = _renderer.getClearAlpha();
  21659. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21660. _gl.enable( _gl.BLEND );
  21661. };
  21662. // For the moment just ignore objects that have multiple materials with different animation methods
  21663. // Only the first material will be taken into account for deciding which depth material to use
  21664. function getObjectMaterial( object ) {
  21665. return object.material instanceof THREE.MeshFaceMaterial
  21666. ? object.material.materials[ 0 ]
  21667. : object.material;
  21668. };
  21669. };
  21670. /**
  21671. * @author mikael emtinger / http://gomo.se/
  21672. *
  21673. */
  21674. THREE.ShaderFlares = {
  21675. 'lensFlareVertexTexture': {
  21676. vertexShader: [
  21677. "uniform lowp int renderType;",
  21678. "uniform vec3 screenPosition;",
  21679. "uniform vec2 scale;",
  21680. "uniform float rotation;",
  21681. "uniform sampler2D occlusionMap;",
  21682. "attribute vec2 position;",
  21683. "attribute vec2 uv;",
  21684. "varying vec2 vUV;",
  21685. "varying float vVisibility;",
  21686. "void main() {",
  21687. "vUV = uv;",
  21688. "vec2 pos = position;",
  21689. "if( renderType == 2 ) {",
  21690. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21691. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21692. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21693. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21694. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21695. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21696. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21697. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21698. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21699. "vVisibility = ( visibility.r / 9.0 ) *",
  21700. "( 1.0 - visibility.g / 9.0 ) *",
  21701. "( visibility.b / 9.0 ) *",
  21702. "( 1.0 - visibility.a / 9.0 );",
  21703. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21704. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21705. "}",
  21706. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21707. "}"
  21708. ].join( "\n" ),
  21709. fragmentShader: [
  21710. "uniform lowp int renderType;",
  21711. "uniform sampler2D map;",
  21712. "uniform float opacity;",
  21713. "uniform vec3 color;",
  21714. "varying vec2 vUV;",
  21715. "varying float vVisibility;",
  21716. "void main() {",
  21717. // pink square
  21718. "if( renderType == 0 ) {",
  21719. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21720. // restore
  21721. "} else if( renderType == 1 ) {",
  21722. "gl_FragColor = texture2D( map, vUV );",
  21723. // flare
  21724. "} else {",
  21725. "vec4 texture = texture2D( map, vUV );",
  21726. "texture.a *= opacity * vVisibility;",
  21727. "gl_FragColor = texture;",
  21728. "gl_FragColor.rgb *= color;",
  21729. "}",
  21730. "}"
  21731. ].join( "\n" )
  21732. },
  21733. 'lensFlare': {
  21734. vertexShader: [
  21735. "uniform lowp int renderType;",
  21736. "uniform vec3 screenPosition;",
  21737. "uniform vec2 scale;",
  21738. "uniform float rotation;",
  21739. "attribute vec2 position;",
  21740. "attribute vec2 uv;",
  21741. "varying vec2 vUV;",
  21742. "void main() {",
  21743. "vUV = uv;",
  21744. "vec2 pos = position;",
  21745. "if( renderType == 2 ) {",
  21746. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21747. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21748. "}",
  21749. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21750. "}"
  21751. ].join( "\n" ),
  21752. fragmentShader: [
  21753. "precision mediump float;",
  21754. "uniform lowp int renderType;",
  21755. "uniform sampler2D map;",
  21756. "uniform sampler2D occlusionMap;",
  21757. "uniform float opacity;",
  21758. "uniform vec3 color;",
  21759. "varying vec2 vUV;",
  21760. "void main() {",
  21761. // pink square
  21762. "if( renderType == 0 ) {",
  21763. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21764. // restore
  21765. "} else if( renderType == 1 ) {",
  21766. "gl_FragColor = texture2D( map, vUV );",
  21767. // flare
  21768. "} else {",
  21769. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21770. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21771. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21772. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21773. "visibility = ( 1.0 - visibility / 4.0 );",
  21774. "vec4 texture = texture2D( map, vUV );",
  21775. "texture.a *= opacity * visibility;",
  21776. "gl_FragColor = texture;",
  21777. "gl_FragColor.rgb *= color;",
  21778. "}",
  21779. "}"
  21780. ].join( "\n" )
  21781. }
  21782. };
  21783. /**
  21784. * @author mikael emtinger / http://gomo.se/
  21785. * @author alteredq / http://alteredqualia.com/
  21786. *
  21787. */
  21788. THREE.ShaderSprite = {
  21789. 'sprite': {
  21790. vertexShader: [
  21791. "uniform int useScreenCoordinates;",
  21792. "uniform int sizeAttenuation;",
  21793. "uniform vec3 screenPosition;",
  21794. "uniform mat4 modelViewMatrix;",
  21795. "uniform mat4 projectionMatrix;",
  21796. "uniform float rotation;",
  21797. "uniform vec2 scale;",
  21798. "uniform vec2 alignment;",
  21799. "uniform vec2 uvOffset;",
  21800. "uniform vec2 uvScale;",
  21801. "attribute vec2 position;",
  21802. "attribute vec2 uv;",
  21803. "varying vec2 vUV;",
  21804. "void main() {",
  21805. "vUV = uvOffset + uv * uvScale;",
  21806. "vec2 alignedPosition = position + alignment;",
  21807. "vec2 rotatedPosition;",
  21808. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21809. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21810. "vec4 finalPosition;",
  21811. "if( useScreenCoordinates != 0 ) {",
  21812. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21813. "} else {",
  21814. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21815. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21816. "}",
  21817. "gl_Position = finalPosition;",
  21818. "}"
  21819. ].join( "\n" ),
  21820. fragmentShader: [
  21821. "uniform vec3 color;",
  21822. "uniform sampler2D map;",
  21823. "uniform float opacity;",
  21824. "uniform int fogType;",
  21825. "uniform vec3 fogColor;",
  21826. "uniform float fogDensity;",
  21827. "uniform float fogNear;",
  21828. "uniform float fogFar;",
  21829. "uniform float alphaTest;",
  21830. "varying vec2 vUV;",
  21831. "void main() {",
  21832. "vec4 texture = texture2D( map, vUV );",
  21833. "if ( texture.a < alphaTest ) discard;",
  21834. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21835. "if ( fogType > 0 ) {",
  21836. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21837. "float fogFactor = 0.0;",
  21838. "if ( fogType == 1 ) {",
  21839. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21840. "} else {",
  21841. "const float LOG2 = 1.442695;",
  21842. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21843. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21844. "}",
  21845. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21846. "}",
  21847. "}"
  21848. ].join( "\n" )
  21849. }
  21850. };
粤ICP备19079148号