three.js 816 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = THREE || { REVISION: '59dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. self.Int32Array = self.Int32Array || Array;
  15. self.Float32Array = self.Float32Array || Array;
  16. String.prototype.trim = String.prototype.trim || function () {
  17. return this.replace( /^\s+|\s+$/g, '' );
  18. };
  19. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  20. THREE.extend = function ( obj, source ) {
  21. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  22. if ( Object.keys ) {
  23. var keys = Object.keys( source );
  24. for (var i = 0, il = keys.length; i < il; i++) {
  25. var prop = keys[i];
  26. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  27. }
  28. } else {
  29. var safeHasOwnProperty = {}.hasOwnProperty;
  30. for ( var prop in source ) {
  31. if ( safeHasOwnProperty.call( source, prop ) ) {
  32. obj[prop] = source[prop];
  33. }
  34. }
  35. }
  36. return obj;
  37. };
  38. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  39. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  40. // requestAnimationFrame polyfill by Erik Möller
  41. // fixes from Paul Irish and Tino Zijdel
  42. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  43. ( function () {
  44. var lastTime = 0;
  45. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  46. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  47. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  48. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  49. }
  50. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  51. self.requestAnimationFrame = function ( callback ) {
  52. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  53. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  54. lastTime = currTime + timeToCall;
  55. return id;
  56. };
  57. }
  58. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  59. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  60. }
  61. }() );
  62. // GL STATE CONSTANTS
  63. THREE.CullFaceNone = 0;
  64. THREE.CullFaceBack = 1;
  65. THREE.CullFaceFront = 2;
  66. THREE.CullFaceFrontBack = 3;
  67. THREE.FrontFaceDirectionCW = 0;
  68. THREE.FrontFaceDirectionCCW = 1;
  69. // SHADOWING TYPES
  70. THREE.BasicShadowMap = 0;
  71. THREE.PCFShadowMap = 1;
  72. THREE.PCFSoftShadowMap = 2;
  73. // MATERIAL CONSTANTS
  74. // side
  75. THREE.FrontSide = 0;
  76. THREE.BackSide = 1;
  77. THREE.DoubleSide = 2;
  78. // shading
  79. THREE.NoShading = 0;
  80. THREE.FlatShading = 1;
  81. THREE.SmoothShading = 2;
  82. // colors
  83. THREE.NoColors = 0;
  84. THREE.FaceColors = 1;
  85. THREE.VertexColors = 2;
  86. // blending modes
  87. THREE.NoBlending = 0;
  88. THREE.NormalBlending = 1;
  89. THREE.AdditiveBlending = 2;
  90. THREE.SubtractiveBlending = 3;
  91. THREE.MultiplyBlending = 4;
  92. THREE.CustomBlending = 5;
  93. // custom blending equations
  94. // (numbers start from 100 not to clash with other
  95. // mappings to OpenGL constants defined in Texture.js)
  96. THREE.AddEquation = 100;
  97. THREE.SubtractEquation = 101;
  98. THREE.ReverseSubtractEquation = 102;
  99. // custom blending destination factors
  100. THREE.ZeroFactor = 200;
  101. THREE.OneFactor = 201;
  102. THREE.SrcColorFactor = 202;
  103. THREE.OneMinusSrcColorFactor = 203;
  104. THREE.SrcAlphaFactor = 204;
  105. THREE.OneMinusSrcAlphaFactor = 205;
  106. THREE.DstAlphaFactor = 206;
  107. THREE.OneMinusDstAlphaFactor = 207;
  108. // custom blending source factors
  109. //THREE.ZeroFactor = 200;
  110. //THREE.OneFactor = 201;
  111. //THREE.SrcAlphaFactor = 204;
  112. //THREE.OneMinusSrcAlphaFactor = 205;
  113. //THREE.DstAlphaFactor = 206;
  114. //THREE.OneMinusDstAlphaFactor = 207;
  115. THREE.DstColorFactor = 208;
  116. THREE.OneMinusDstColorFactor = 209;
  117. THREE.SrcAlphaSaturateFactor = 210;
  118. // TEXTURE CONSTANTS
  119. THREE.MultiplyOperation = 0;
  120. THREE.MixOperation = 1;
  121. THREE.AddOperation = 2;
  122. // Mapping modes
  123. THREE.UVMapping = function () {};
  124. THREE.CubeReflectionMapping = function () {};
  125. THREE.CubeRefractionMapping = function () {};
  126. THREE.SphericalReflectionMapping = function () {};
  127. THREE.SphericalRefractionMapping = function () {};
  128. // Wrapping modes
  129. THREE.RepeatWrapping = 1000;
  130. THREE.ClampToEdgeWrapping = 1001;
  131. THREE.MirroredRepeatWrapping = 1002;
  132. // Filters
  133. THREE.NearestFilter = 1003;
  134. THREE.NearestMipMapNearestFilter = 1004;
  135. THREE.NearestMipMapLinearFilter = 1005;
  136. THREE.LinearFilter = 1006;
  137. THREE.LinearMipMapNearestFilter = 1007;
  138. THREE.LinearMipMapLinearFilter = 1008;
  139. // Data types
  140. THREE.UnsignedByteType = 1009;
  141. THREE.ByteType = 1010;
  142. THREE.ShortType = 1011;
  143. THREE.UnsignedShortType = 1012;
  144. THREE.IntType = 1013;
  145. THREE.UnsignedIntType = 1014;
  146. THREE.FloatType = 1015;
  147. // Pixel types
  148. //THREE.UnsignedByteType = 1009;
  149. THREE.UnsignedShort4444Type = 1016;
  150. THREE.UnsignedShort5551Type = 1017;
  151. THREE.UnsignedShort565Type = 1018;
  152. // Pixel formats
  153. THREE.AlphaFormat = 1019;
  154. THREE.RGBFormat = 1020;
  155. THREE.RGBAFormat = 1021;
  156. THREE.LuminanceFormat = 1022;
  157. THREE.LuminanceAlphaFormat = 1023;
  158. // Compressed texture formats
  159. THREE.RGB_S3TC_DXT1_Format = 2001;
  160. THREE.RGBA_S3TC_DXT1_Format = 2002;
  161. THREE.RGBA_S3TC_DXT3_Format = 2003;
  162. THREE.RGBA_S3TC_DXT5_Format = 2004;
  163. /*
  164. // Potential future PVRTC compressed texture formats
  165. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  166. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  167. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  168. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  169. */
  170. /**
  171. * @author mrdoob / http://mrdoob.com/
  172. */
  173. THREE.Color = function ( value ) {
  174. if ( value !== undefined ) this.set( value );
  175. return this;
  176. };
  177. THREE.Color.prototype = {
  178. constructor: THREE.Color,
  179. r: 1, g: 1, b: 1,
  180. set: function ( value ) {
  181. if ( value instanceof THREE.Color ) {
  182. this.copy( value );
  183. } else if ( typeof value === 'number' ) {
  184. this.setHex( value );
  185. } else if ( typeof value === 'string' ) {
  186. this.setStyle( value );
  187. }
  188. return this;
  189. },
  190. setHex: function ( hex ) {
  191. hex = Math.floor( hex );
  192. this.r = ( hex >> 16 & 255 ) / 255;
  193. this.g = ( hex >> 8 & 255 ) / 255;
  194. this.b = ( hex & 255 ) / 255;
  195. return this;
  196. },
  197. setRGB: function ( r, g, b ) {
  198. this.r = r;
  199. this.g = g;
  200. this.b = b;
  201. return this;
  202. },
  203. setHSL: function ( h, s, l ) {
  204. // h,s,l ranges are in 0.0 - 1.0
  205. if ( s === 0 ) {
  206. this.r = this.g = this.b = l;
  207. } else {
  208. var hue2rgb = function ( p, q, t ) {
  209. if ( t < 0 ) t += 1;
  210. if ( t > 1 ) t -= 1;
  211. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  212. if ( t < 1 / 2 ) return q;
  213. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  214. return p;
  215. };
  216. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  217. var q = ( 2 * l ) - p;
  218. this.r = hue2rgb( q, p, h + 1 / 3 );
  219. this.g = hue2rgb( q, p, h );
  220. this.b = hue2rgb( q, p, h - 1 / 3 );
  221. }
  222. return this;
  223. },
  224. setStyle: function ( style ) {
  225. // rgb(255,0,0)
  226. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  227. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  228. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  229. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  230. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  231. return this;
  232. }
  233. // rgb(100%,0%,0%)
  234. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  235. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  236. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  237. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  238. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  239. return this;
  240. }
  241. // #ff0000
  242. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  243. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  244. this.setHex( parseInt( color[ 1 ], 16 ) );
  245. return this;
  246. }
  247. // #f00
  248. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  249. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  250. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  251. return this;
  252. }
  253. // red
  254. if ( /^(\w+)$/i.test( style ) ) {
  255. this.setHex( THREE.ColorKeywords[ style ] );
  256. return this;
  257. }
  258. },
  259. copy: function ( color ) {
  260. this.r = color.r;
  261. this.g = color.g;
  262. this.b = color.b;
  263. return this;
  264. },
  265. copyGammaToLinear: function ( color ) {
  266. this.r = color.r * color.r;
  267. this.g = color.g * color.g;
  268. this.b = color.b * color.b;
  269. return this;
  270. },
  271. copyLinearToGamma: function ( color ) {
  272. this.r = Math.sqrt( color.r );
  273. this.g = Math.sqrt( color.g );
  274. this.b = Math.sqrt( color.b );
  275. return this;
  276. },
  277. convertGammaToLinear: function () {
  278. var r = this.r, g = this.g, b = this.b;
  279. this.r = r * r;
  280. this.g = g * g;
  281. this.b = b * b;
  282. return this;
  283. },
  284. convertLinearToGamma: function () {
  285. this.r = Math.sqrt( this.r );
  286. this.g = Math.sqrt( this.g );
  287. this.b = Math.sqrt( this.b );
  288. return this;
  289. },
  290. getHex: function () {
  291. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  292. },
  293. getHexString: function () {
  294. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  295. },
  296. getHSL: function () {
  297. var hsl = { h: 0, s: 0, l: 0 };
  298. return function () {
  299. // h,s,l ranges are in 0.0 - 1.0
  300. var r = this.r, g = this.g, b = this.b;
  301. var max = Math.max( r, g, b );
  302. var min = Math.min( r, g, b );
  303. var hue, saturation;
  304. var lightness = ( min + max ) / 2.0;
  305. if ( min === max ) {
  306. hue = 0;
  307. saturation = 0;
  308. } else {
  309. var delta = max - min;
  310. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  311. switch ( max ) {
  312. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  313. case g: hue = ( b - r ) / delta + 2; break;
  314. case b: hue = ( r - g ) / delta + 4; break;
  315. }
  316. hue /= 6;
  317. }
  318. hsl.h = hue;
  319. hsl.s = saturation;
  320. hsl.l = lightness;
  321. return hsl;
  322. };
  323. }(),
  324. getStyle: function () {
  325. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  326. },
  327. offsetHSL: function ( h, s, l ) {
  328. var hsl = this.getHSL();
  329. hsl.h += h; hsl.s += s; hsl.l += l;
  330. this.setHSL( hsl.h, hsl.s, hsl.l );
  331. return this;
  332. },
  333. add: function ( color ) {
  334. this.r += color.r;
  335. this.g += color.g;
  336. this.b += color.b;
  337. return this;
  338. },
  339. addColors: function ( color1, color2 ) {
  340. this.r = color1.r + color2.r;
  341. this.g = color1.g + color2.g;
  342. this.b = color1.b + color2.b;
  343. return this;
  344. },
  345. addScalar: function ( s ) {
  346. this.r += s;
  347. this.g += s;
  348. this.b += s;
  349. return this;
  350. },
  351. multiply: function ( color ) {
  352. this.r *= color.r;
  353. this.g *= color.g;
  354. this.b *= color.b;
  355. return this;
  356. },
  357. multiplyScalar: function ( s ) {
  358. this.r *= s;
  359. this.g *= s;
  360. this.b *= s;
  361. return this;
  362. },
  363. lerp: function ( color, alpha ) {
  364. this.r += ( color.r - this.r ) * alpha;
  365. this.g += ( color.g - this.g ) * alpha;
  366. this.b += ( color.b - this.b ) * alpha;
  367. return this;
  368. },
  369. equals: function ( c ) {
  370. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  371. },
  372. clone: function () {
  373. return new THREE.Color().setRGB( this.r, this.g, this.b );
  374. }
  375. };
  376. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  377. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  378. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  379. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  380. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  381. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  382. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  383. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  384. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  385. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  386. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  387. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  388. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  389. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  390. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  391. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  392. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  393. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  394. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  395. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  396. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  397. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  398. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  399. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  400. /**
  401. * @author mikael emtinger / http://gomo.se/
  402. * @author alteredq / http://alteredqualia.com/
  403. * @author WestLangley / http://github.com/WestLangley
  404. * @author bhouston / http://exocortex.com
  405. */
  406. THREE.Quaternion = function( x, y, z, w ) {
  407. this.x = x || 0;
  408. this.y = y || 0;
  409. this.z = z || 0;
  410. this.w = ( w !== undefined ) ? w : 1;
  411. };
  412. THREE.Quaternion.prototype = {
  413. constructor: THREE.Quaternion,
  414. set: function ( x, y, z, w ) {
  415. this.x = x;
  416. this.y = y;
  417. this.z = z;
  418. this.w = w;
  419. return this;
  420. },
  421. copy: function ( q ) {
  422. this.x = q.x;
  423. this.y = q.y;
  424. this.z = q.z;
  425. this.w = q.w;
  426. return this;
  427. },
  428. setFromEuler: function ( v, order ) {
  429. // http://www.mathworks.com/matlabcentral/fileexchange/
  430. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  431. // content/SpinCalc.m
  432. var c1 = Math.cos( v.x / 2 );
  433. var c2 = Math.cos( v.y / 2 );
  434. var c3 = Math.cos( v.z / 2 );
  435. var s1 = Math.sin( v.x / 2 );
  436. var s2 = Math.sin( v.y / 2 );
  437. var s3 = Math.sin( v.z / 2 );
  438. if ( order === undefined || order === 'XYZ' ) {
  439. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  440. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  441. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  442. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  443. } else if ( order === 'YXZ' ) {
  444. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  445. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  446. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  447. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  448. } else if ( order === 'ZXY' ) {
  449. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  450. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  451. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  452. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  453. } else if ( order === 'ZYX' ) {
  454. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  455. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  456. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  457. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  458. } else if ( order === 'YZX' ) {
  459. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  460. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  461. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  462. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  463. } else if ( order === 'XZY' ) {
  464. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  465. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  466. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  467. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  468. }
  469. return this;
  470. },
  471. setFromAxisAngle: function ( axis, angle ) {
  472. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  473. // axis have to be normalized
  474. var halfAngle = angle / 2,
  475. s = Math.sin( halfAngle );
  476. this.x = axis.x * s;
  477. this.y = axis.y * s;
  478. this.z = axis.z * s;
  479. this.w = Math.cos( halfAngle );
  480. return this;
  481. },
  482. setFromRotationMatrix: function ( m ) {
  483. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  484. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  485. var te = m.elements,
  486. m11 = te[0], m12 = te[4], m13 = te[8],
  487. m21 = te[1], m22 = te[5], m23 = te[9],
  488. m31 = te[2], m32 = te[6], m33 = te[10],
  489. trace = m11 + m22 + m33,
  490. s;
  491. if ( trace > 0 ) {
  492. s = 0.5 / Math.sqrt( trace + 1.0 );
  493. this.w = 0.25 / s;
  494. this.x = ( m32 - m23 ) * s;
  495. this.y = ( m13 - m31 ) * s;
  496. this.z = ( m21 - m12 ) * s;
  497. } else if ( m11 > m22 && m11 > m33 ) {
  498. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  499. this.w = (m32 - m23 ) / s;
  500. this.x = 0.25 * s;
  501. this.y = (m12 + m21 ) / s;
  502. this.z = (m13 + m31 ) / s;
  503. } else if ( m22 > m33 ) {
  504. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  505. this.w = (m13 - m31 ) / s;
  506. this.x = (m12 + m21 ) / s;
  507. this.y = 0.25 * s;
  508. this.z = (m23 + m32 ) / s;
  509. } else {
  510. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  511. this.w = ( m21 - m12 ) / s;
  512. this.x = ( m13 + m31 ) / s;
  513. this.y = ( m23 + m32 ) / s;
  514. this.z = 0.25 * s;
  515. }
  516. return this;
  517. },
  518. inverse: function () {
  519. this.conjugate().normalize();
  520. return this;
  521. },
  522. conjugate: function () {
  523. this.x *= -1;
  524. this.y *= -1;
  525. this.z *= -1;
  526. return this;
  527. },
  528. lengthSq: function () {
  529. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  530. },
  531. length: function () {
  532. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  533. },
  534. normalize: function () {
  535. var l = this.length();
  536. if ( l === 0 ) {
  537. this.x = 0;
  538. this.y = 0;
  539. this.z = 0;
  540. this.w = 1;
  541. } else {
  542. l = 1 / l;
  543. this.x = this.x * l;
  544. this.y = this.y * l;
  545. this.z = this.z * l;
  546. this.w = this.w * l;
  547. }
  548. return this;
  549. },
  550. multiply: function ( q, p ) {
  551. if ( p !== undefined ) {
  552. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  553. return this.multiplyQuaternions( q, p );
  554. }
  555. return this.multiplyQuaternions( this, q );
  556. },
  557. multiplyQuaternions: function ( a, b ) {
  558. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  559. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  560. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  561. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  562. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  563. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  564. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  565. return this;
  566. },
  567. multiplyVector3: function ( vector ) {
  568. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  569. return vector.applyQuaternion( this );
  570. },
  571. slerp: function ( qb, t ) {
  572. var x = this.x, y = this.y, z = this.z, w = this.w;
  573. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  574. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  575. if ( cosHalfTheta < 0 ) {
  576. this.w = -qb.w;
  577. this.x = -qb.x;
  578. this.y = -qb.y;
  579. this.z = -qb.z;
  580. cosHalfTheta = -cosHalfTheta;
  581. } else {
  582. this.copy( qb );
  583. }
  584. if ( cosHalfTheta >= 1.0 ) {
  585. this.w = w;
  586. this.x = x;
  587. this.y = y;
  588. this.z = z;
  589. return this;
  590. }
  591. var halfTheta = Math.acos( cosHalfTheta );
  592. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  593. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  594. this.w = 0.5 * ( w + this.w );
  595. this.x = 0.5 * ( x + this.x );
  596. this.y = 0.5 * ( y + this.y );
  597. this.z = 0.5 * ( z + this.z );
  598. return this;
  599. }
  600. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  601. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  602. this.w = ( w * ratioA + this.w * ratioB );
  603. this.x = ( x * ratioA + this.x * ratioB );
  604. this.y = ( y * ratioA + this.y * ratioB );
  605. this.z = ( z * ratioA + this.z * ratioB );
  606. return this;
  607. },
  608. equals: function ( v ) {
  609. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  610. },
  611. fromArray: function ( array ) {
  612. this.x = array[ 0 ];
  613. this.y = array[ 1 ];
  614. this.z = array[ 2 ];
  615. this.w = array[ 3 ];
  616. return this;
  617. },
  618. toArray: function () {
  619. return [ this.x, this.y, this.z, this.w ];
  620. },
  621. clone: function () {
  622. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  623. }
  624. };
  625. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  626. return qm.copy( qa ).slerp( qb, t );
  627. }
  628. /**
  629. * @author mrdoob / http://mrdoob.com/
  630. * @author philogb / http://blog.thejit.org/
  631. * @author egraether / http://egraether.com/
  632. * @author zz85 / http://www.lab4games.net/zz85/blog
  633. */
  634. THREE.Vector2 = function ( x, y ) {
  635. this.x = x || 0;
  636. this.y = y || 0;
  637. };
  638. THREE.Vector2.prototype = {
  639. constructor: THREE.Vector2,
  640. set: function ( x, y ) {
  641. this.x = x;
  642. this.y = y;
  643. return this;
  644. },
  645. setX: function ( x ) {
  646. this.x = x;
  647. return this;
  648. },
  649. setY: function ( y ) {
  650. this.y = y;
  651. return this;
  652. },
  653. setComponent: function ( index, value ) {
  654. switch ( index ) {
  655. case 0: this.x = value; break;
  656. case 1: this.y = value; break;
  657. default: throw new Error( "index is out of range: " + index );
  658. }
  659. },
  660. getComponent: function ( index ) {
  661. switch ( index ) {
  662. case 0: return this.x;
  663. case 1: return this.y;
  664. default: throw new Error( "index is out of range: " + index );
  665. }
  666. },
  667. copy: function ( v ) {
  668. this.x = v.x;
  669. this.y = v.y;
  670. return this;
  671. },
  672. add: function ( v, w ) {
  673. if ( w !== undefined ) {
  674. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  675. return this.addVectors( v, w );
  676. }
  677. this.x += v.x;
  678. this.y += v.y;
  679. return this;
  680. },
  681. addVectors: function ( a, b ) {
  682. this.x = a.x + b.x;
  683. this.y = a.y + b.y;
  684. return this;
  685. },
  686. addScalar: function ( s ) {
  687. this.x += s;
  688. this.y += s;
  689. return this;
  690. },
  691. sub: function ( v, w ) {
  692. if ( w !== undefined ) {
  693. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  694. return this.subVectors( v, w );
  695. }
  696. this.x -= v.x;
  697. this.y -= v.y;
  698. return this;
  699. },
  700. subVectors: function ( a, b ) {
  701. this.x = a.x - b.x;
  702. this.y = a.y - b.y;
  703. return this;
  704. },
  705. multiplyScalar: function ( s ) {
  706. this.x *= s;
  707. this.y *= s;
  708. return this;
  709. },
  710. divideScalar: function ( s ) {
  711. if ( s !== 0 ) {
  712. this.x /= s;
  713. this.y /= s;
  714. } else {
  715. this.set( 0, 0 );
  716. }
  717. return this;
  718. },
  719. min: function ( v ) {
  720. if ( this.x > v.x ) {
  721. this.x = v.x;
  722. }
  723. if ( this.y > v.y ) {
  724. this.y = v.y;
  725. }
  726. return this;
  727. },
  728. max: function ( v ) {
  729. if ( this.x < v.x ) {
  730. this.x = v.x;
  731. }
  732. if ( this.y < v.y ) {
  733. this.y = v.y;
  734. }
  735. return this;
  736. },
  737. clamp: function ( min, max ) {
  738. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  739. if ( this.x < min.x ) {
  740. this.x = min.x;
  741. } else if ( this.x > max.x ) {
  742. this.x = max.x;
  743. }
  744. if ( this.y < min.y ) {
  745. this.y = min.y;
  746. } else if ( this.y > max.y ) {
  747. this.y = max.y;
  748. }
  749. return this;
  750. },
  751. negate: function() {
  752. return this.multiplyScalar( - 1 );
  753. },
  754. dot: function ( v ) {
  755. return this.x * v.x + this.y * v.y;
  756. },
  757. lengthSq: function () {
  758. return this.x * this.x + this.y * this.y;
  759. },
  760. length: function () {
  761. return Math.sqrt( this.x * this.x + this.y * this.y );
  762. },
  763. normalize: function () {
  764. return this.divideScalar( this.length() );
  765. },
  766. distanceTo: function ( v ) {
  767. return Math.sqrt( this.distanceToSquared( v ) );
  768. },
  769. distanceToSquared: function ( v ) {
  770. var dx = this.x - v.x, dy = this.y - v.y;
  771. return dx * dx + dy * dy;
  772. },
  773. setLength: function ( l ) {
  774. var oldLength = this.length();
  775. if ( oldLength !== 0 && l !== oldLength ) {
  776. this.multiplyScalar( l / oldLength );
  777. }
  778. return this;
  779. },
  780. lerp: function ( v, alpha ) {
  781. this.x += ( v.x - this.x ) * alpha;
  782. this.y += ( v.y - this.y ) * alpha;
  783. return this;
  784. },
  785. equals: function( v ) {
  786. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  787. },
  788. fromArray: function ( array ) {
  789. this.x = array[ 0 ];
  790. this.y = array[ 1 ];
  791. return this;
  792. },
  793. toArray: function () {
  794. return [ this.x, this.y ];
  795. },
  796. clone: function () {
  797. return new THREE.Vector2( this.x, this.y );
  798. }
  799. };
  800. /**
  801. * @author mrdoob / http://mrdoob.com/
  802. * @author *kile / http://kile.stravaganza.org/
  803. * @author philogb / http://blog.thejit.org/
  804. * @author mikael emtinger / http://gomo.se/
  805. * @author egraether / http://egraether.com/
  806. * @author WestLangley / http://github.com/WestLangley
  807. */
  808. THREE.Vector3 = function ( x, y, z ) {
  809. this.x = x || 0;
  810. this.y = y || 0;
  811. this.z = z || 0;
  812. };
  813. THREE.Vector3.prototype = {
  814. constructor: THREE.Vector3,
  815. set: function ( x, y, z ) {
  816. this.x = x;
  817. this.y = y;
  818. this.z = z;
  819. return this;
  820. },
  821. setX: function ( x ) {
  822. this.x = x;
  823. return this;
  824. },
  825. setY: function ( y ) {
  826. this.y = y;
  827. return this;
  828. },
  829. setZ: function ( z ) {
  830. this.z = z;
  831. return this;
  832. },
  833. setComponent: function ( index, value ) {
  834. switch ( index ) {
  835. case 0: this.x = value; break;
  836. case 1: this.y = value; break;
  837. case 2: this.z = value; break;
  838. default: throw new Error( "index is out of range: " + index );
  839. }
  840. },
  841. getComponent: function ( index ) {
  842. switch ( index ) {
  843. case 0: return this.x;
  844. case 1: return this.y;
  845. case 2: return this.z;
  846. default: throw new Error( "index is out of range: " + index );
  847. }
  848. },
  849. copy: function ( v ) {
  850. this.x = v.x;
  851. this.y = v.y;
  852. this.z = v.z;
  853. return this;
  854. },
  855. add: function ( v, w ) {
  856. if ( w !== undefined ) {
  857. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  858. return this.addVectors( v, w );
  859. }
  860. this.x += v.x;
  861. this.y += v.y;
  862. this.z += v.z;
  863. return this;
  864. },
  865. addScalar: function ( s ) {
  866. this.x += s;
  867. this.y += s;
  868. this.z += s;
  869. return this;
  870. },
  871. addVectors: function ( a, b ) {
  872. this.x = a.x + b.x;
  873. this.y = a.y + b.y;
  874. this.z = a.z + b.z;
  875. return this;
  876. },
  877. sub: function ( v, w ) {
  878. if ( w !== undefined ) {
  879. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  880. return this.subVectors( v, w );
  881. }
  882. this.x -= v.x;
  883. this.y -= v.y;
  884. this.z -= v.z;
  885. return this;
  886. },
  887. subVectors: function ( a, b ) {
  888. this.x = a.x - b.x;
  889. this.y = a.y - b.y;
  890. this.z = a.z - b.z;
  891. return this;
  892. },
  893. multiply: function ( v, w ) {
  894. if ( w !== undefined ) {
  895. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  896. return this.multiplyVectors( v, w );
  897. }
  898. this.x *= v.x;
  899. this.y *= v.y;
  900. this.z *= v.z;
  901. return this;
  902. },
  903. multiplyScalar: function ( s ) {
  904. this.x *= s;
  905. this.y *= s;
  906. this.z *= s;
  907. return this;
  908. },
  909. multiplyVectors: function ( a, b ) {
  910. this.x = a.x * b.x;
  911. this.y = a.y * b.y;
  912. this.z = a.z * b.z;
  913. return this;
  914. },
  915. applyMatrix3: function ( m ) {
  916. var x = this.x;
  917. var y = this.y;
  918. var z = this.z;
  919. var e = m.elements;
  920. this.x = e[0] * x + e[3] * y + e[6] * z;
  921. this.y = e[1] * x + e[4] * y + e[7] * z;
  922. this.z = e[2] * x + e[5] * y + e[8] * z;
  923. return this;
  924. },
  925. applyMatrix4: function ( m ) {
  926. // input: THREE.Matrix4 affine matrix
  927. var x = this.x, y = this.y, z = this.z;
  928. var e = m.elements;
  929. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  930. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  931. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  932. return this;
  933. },
  934. applyProjection: function ( m ) {
  935. // input: THREE.Matrix4 projection matrix
  936. var x = this.x, y = this.y, z = this.z;
  937. var e = m.elements;
  938. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  939. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  940. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  941. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  942. return this;
  943. },
  944. applyQuaternion: function ( q ) {
  945. var x = this.x;
  946. var y = this.y;
  947. var z = this.z;
  948. var qx = q.x;
  949. var qy = q.y;
  950. var qz = q.z;
  951. var qw = q.w;
  952. // calculate quat * vector
  953. var ix = qw * x + qy * z - qz * y;
  954. var iy = qw * y + qz * x - qx * z;
  955. var iz = qw * z + qx * y - qy * x;
  956. var iw = -qx * x - qy * y - qz * z;
  957. // calculate result * inverse quat
  958. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  959. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  960. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  961. return this;
  962. },
  963. transformDirection: function ( m ) {
  964. // input: THREE.Matrix4 affine matrix
  965. // vector interpreted as a direction
  966. var x = this.x, y = this.y, z = this.z;
  967. var e = m.elements;
  968. this.x = e[0] * x + e[4] * y + e[8] * z;
  969. this.y = e[1] * x + e[5] * y + e[9] * z;
  970. this.z = e[2] * x + e[6] * y + e[10] * z;
  971. this.normalize();
  972. return this;
  973. },
  974. divide: function ( v ) {
  975. this.x /= v.x;
  976. this.y /= v.y;
  977. this.z /= v.z;
  978. return this;
  979. },
  980. divideScalar: function ( s ) {
  981. if ( s !== 0 ) {
  982. this.x /= s;
  983. this.y /= s;
  984. this.z /= s;
  985. } else {
  986. this.x = 0;
  987. this.y = 0;
  988. this.z = 0;
  989. }
  990. return this;
  991. },
  992. min: function ( v ) {
  993. if ( this.x > v.x ) {
  994. this.x = v.x;
  995. }
  996. if ( this.y > v.y ) {
  997. this.y = v.y;
  998. }
  999. if ( this.z > v.z ) {
  1000. this.z = v.z;
  1001. }
  1002. return this;
  1003. },
  1004. max: function ( v ) {
  1005. if ( this.x < v.x ) {
  1006. this.x = v.x;
  1007. }
  1008. if ( this.y < v.y ) {
  1009. this.y = v.y;
  1010. }
  1011. if ( this.z < v.z ) {
  1012. this.z = v.z;
  1013. }
  1014. return this;
  1015. },
  1016. clamp: function ( min, max ) {
  1017. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1018. if ( this.x < min.x ) {
  1019. this.x = min.x;
  1020. } else if ( this.x > max.x ) {
  1021. this.x = max.x;
  1022. }
  1023. if ( this.y < min.y ) {
  1024. this.y = min.y;
  1025. } else if ( this.y > max.y ) {
  1026. this.y = max.y;
  1027. }
  1028. if ( this.z < min.z ) {
  1029. this.z = min.z;
  1030. } else if ( this.z > max.z ) {
  1031. this.z = max.z;
  1032. }
  1033. return this;
  1034. },
  1035. negate: function () {
  1036. return this.multiplyScalar( - 1 );
  1037. },
  1038. dot: function ( v ) {
  1039. return this.x * v.x + this.y * v.y + this.z * v.z;
  1040. },
  1041. lengthSq: function () {
  1042. return this.x * this.x + this.y * this.y + this.z * this.z;
  1043. },
  1044. length: function () {
  1045. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1046. },
  1047. lengthManhattan: function () {
  1048. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1049. },
  1050. normalize: function () {
  1051. return this.divideScalar( this.length() );
  1052. },
  1053. setLength: function ( l ) {
  1054. var oldLength = this.length();
  1055. if ( oldLength !== 0 && l !== oldLength ) {
  1056. this.multiplyScalar( l / oldLength );
  1057. }
  1058. return this;
  1059. },
  1060. lerp: function ( v, alpha ) {
  1061. this.x += ( v.x - this.x ) * alpha;
  1062. this.y += ( v.y - this.y ) * alpha;
  1063. this.z += ( v.z - this.z ) * alpha;
  1064. return this;
  1065. },
  1066. cross: function ( v, w ) {
  1067. if ( w !== undefined ) {
  1068. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1069. return this.crossVectors( v, w );
  1070. }
  1071. var x = this.x, y = this.y, z = this.z;
  1072. this.x = y * v.z - z * v.y;
  1073. this.y = z * v.x - x * v.z;
  1074. this.z = x * v.y - y * v.x;
  1075. return this;
  1076. },
  1077. crossVectors: function ( a, b ) {
  1078. this.x = a.y * b.z - a.z * b.y;
  1079. this.y = a.z * b.x - a.x * b.z;
  1080. this.z = a.x * b.y - a.y * b.x;
  1081. return this;
  1082. },
  1083. angleTo: function ( v ) {
  1084. var theta = this.dot( v ) / ( this.length() * v.length() );
  1085. // clamp, to handle numerical problems
  1086. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1087. },
  1088. distanceTo: function ( v ) {
  1089. return Math.sqrt( this.distanceToSquared( v ) );
  1090. },
  1091. distanceToSquared: function ( v ) {
  1092. var dx = this.x - v.x;
  1093. var dy = this.y - v.y;
  1094. var dz = this.z - v.z;
  1095. return dx * dx + dy * dy + dz * dz;
  1096. },
  1097. setEulerFromRotationMatrix: function ( m, order ) {
  1098. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1099. // clamp, to handle numerical problems
  1100. function clamp( x ) {
  1101. return Math.min( Math.max( x, -1 ), 1 );
  1102. }
  1103. var te = m.elements;
  1104. var m11 = te[0], m12 = te[4], m13 = te[8];
  1105. var m21 = te[1], m22 = te[5], m23 = te[9];
  1106. var m31 = te[2], m32 = te[6], m33 = te[10];
  1107. if ( order === undefined || order === 'XYZ' ) {
  1108. this.y = Math.asin( clamp( m13 ) );
  1109. if ( Math.abs( m13 ) < 0.99999 ) {
  1110. this.x = Math.atan2( - m23, m33 );
  1111. this.z = Math.atan2( - m12, m11 );
  1112. } else {
  1113. this.x = Math.atan2( m32, m22 );
  1114. this.z = 0;
  1115. }
  1116. } else if ( order === 'YXZ' ) {
  1117. this.x = Math.asin( - clamp( m23 ) );
  1118. if ( Math.abs( m23 ) < 0.99999 ) {
  1119. this.y = Math.atan2( m13, m33 );
  1120. this.z = Math.atan2( m21, m22 );
  1121. } else {
  1122. this.y = Math.atan2( - m31, m11 );
  1123. this.z = 0;
  1124. }
  1125. } else if ( order === 'ZXY' ) {
  1126. this.x = Math.asin( clamp( m32 ) );
  1127. if ( Math.abs( m32 ) < 0.99999 ) {
  1128. this.y = Math.atan2( - m31, m33 );
  1129. this.z = Math.atan2( - m12, m22 );
  1130. } else {
  1131. this.y = 0;
  1132. this.z = Math.atan2( m21, m11 );
  1133. }
  1134. } else if ( order === 'ZYX' ) {
  1135. this.y = Math.asin( - clamp( m31 ) );
  1136. if ( Math.abs( m31 ) < 0.99999 ) {
  1137. this.x = Math.atan2( m32, m33 );
  1138. this.z = Math.atan2( m21, m11 );
  1139. } else {
  1140. this.x = 0;
  1141. this.z = Math.atan2( - m12, m22 );
  1142. }
  1143. } else if ( order === 'YZX' ) {
  1144. this.z = Math.asin( clamp( m21 ) );
  1145. if ( Math.abs( m21 ) < 0.99999 ) {
  1146. this.x = Math.atan2( - m23, m22 );
  1147. this.y = Math.atan2( - m31, m11 );
  1148. } else {
  1149. this.x = 0;
  1150. this.y = Math.atan2( m13, m33 );
  1151. }
  1152. } else if ( order === 'XZY' ) {
  1153. this.z = Math.asin( - clamp( m12 ) );
  1154. if ( Math.abs( m12 ) < 0.99999 ) {
  1155. this.x = Math.atan2( m32, m22 );
  1156. this.y = Math.atan2( m13, m11 );
  1157. } else {
  1158. this.x = Math.atan2( - m23, m33 );
  1159. this.y = 0;
  1160. }
  1161. }
  1162. return this;
  1163. },
  1164. setEulerFromQuaternion: function ( q, order ) {
  1165. // q is assumed to be normalized
  1166. // clamp, to handle numerical problems
  1167. function clamp( x ) {
  1168. return Math.min( Math.max( x, -1 ), 1 );
  1169. }
  1170. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1171. var sqx = q.x * q.x;
  1172. var sqy = q.y * q.y;
  1173. var sqz = q.z * q.z;
  1174. var sqw = q.w * q.w;
  1175. if ( order === undefined || order === 'XYZ' ) {
  1176. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1177. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1178. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1179. } else if ( order === 'YXZ' ) {
  1180. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1181. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1182. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1183. } else if ( order === 'ZXY' ) {
  1184. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1185. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1186. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1187. } else if ( order === 'ZYX' ) {
  1188. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1189. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1190. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1191. } else if ( order === 'YZX' ) {
  1192. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1193. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1194. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1195. } else if ( order === 'XZY' ) {
  1196. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1197. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1198. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1199. }
  1200. return this;
  1201. },
  1202. getPositionFromMatrix: function ( m ) {
  1203. this.x = m.elements[12];
  1204. this.y = m.elements[13];
  1205. this.z = m.elements[14];
  1206. return this;
  1207. },
  1208. getScaleFromMatrix: function ( m ) {
  1209. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1210. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1211. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1212. this.x = sx;
  1213. this.y = sy;
  1214. this.z = sz;
  1215. return this;
  1216. },
  1217. getColumnFromMatrix: function ( index, matrix ) {
  1218. var offset = index * 4;
  1219. var me = matrix.elements;
  1220. this.x = me[ offset ];
  1221. this.y = me[ offset + 1 ];
  1222. this.z = me[ offset + 2 ];
  1223. return this;
  1224. },
  1225. equals: function ( v ) {
  1226. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1227. },
  1228. fromArray: function ( array ) {
  1229. this.x = array[ 0 ];
  1230. this.y = array[ 1 ];
  1231. this.z = array[ 2 ];
  1232. return this;
  1233. },
  1234. toArray: function () {
  1235. return [ this.x, this.y, this.z ];
  1236. },
  1237. clone: function () {
  1238. return new THREE.Vector3( this.x, this.y, this.z );
  1239. }
  1240. };
  1241. THREE.extend( THREE.Vector3.prototype, {
  1242. applyEuler: function () {
  1243. var q1 = new THREE.Quaternion();
  1244. return function ( v, eulerOrder ) {
  1245. var quaternion = q1.setFromEuler( v, eulerOrder );
  1246. this.applyQuaternion( quaternion );
  1247. return this;
  1248. };
  1249. }(),
  1250. applyAxisAngle: function () {
  1251. var q1 = new THREE.Quaternion();
  1252. return function ( axis, angle ) {
  1253. var quaternion = q1.setFromAxisAngle( axis, angle );
  1254. this.applyQuaternion( quaternion );
  1255. return this;
  1256. };
  1257. }(),
  1258. projectOnVector: function () {
  1259. var v1 = new THREE.Vector3();
  1260. return function ( vector ) {
  1261. v1.copy( vector ).normalize();
  1262. var d = this.dot( v1 );
  1263. return this.copy( v1 ).multiplyScalar( d );
  1264. };
  1265. }(),
  1266. projectOnPlane: function () {
  1267. var v1 = new THREE.Vector3();
  1268. return function ( planeNormal ) {
  1269. v1.copy( this ).projectOnVector( planeNormal );
  1270. return this.sub( v1 );
  1271. }
  1272. }(),
  1273. reflect: function () {
  1274. var v1 = new THREE.Vector3();
  1275. return function ( vector ) {
  1276. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1277. return this.subVectors( v1, this );
  1278. }
  1279. }()
  1280. } );
  1281. /**
  1282. * @author supereggbert / http://www.paulbrunt.co.uk/
  1283. * @author philogb / http://blog.thejit.org/
  1284. * @author mikael emtinger / http://gomo.se/
  1285. * @author egraether / http://egraether.com/
  1286. * @author WestLangley / http://github.com/WestLangley
  1287. */
  1288. THREE.Vector4 = function ( x, y, z, w ) {
  1289. this.x = x || 0;
  1290. this.y = y || 0;
  1291. this.z = z || 0;
  1292. this.w = ( w !== undefined ) ? w : 1;
  1293. };
  1294. THREE.Vector4.prototype = {
  1295. constructor: THREE.Vector4,
  1296. set: function ( x, y, z, w ) {
  1297. this.x = x;
  1298. this.y = y;
  1299. this.z = z;
  1300. this.w = w;
  1301. return this;
  1302. },
  1303. setX: function ( x ) {
  1304. this.x = x;
  1305. return this;
  1306. },
  1307. setY: function ( y ) {
  1308. this.y = y;
  1309. return this;
  1310. },
  1311. setZ: function ( z ) {
  1312. this.z = z;
  1313. return this;
  1314. },
  1315. setW: function ( w ) {
  1316. this.w = w;
  1317. return this;
  1318. },
  1319. setComponent: function ( index, value ) {
  1320. switch ( index ) {
  1321. case 0: this.x = value; break;
  1322. case 1: this.y = value; break;
  1323. case 2: this.z = value; break;
  1324. case 3: this.w = value; break;
  1325. default: throw new Error( "index is out of range: " + index );
  1326. }
  1327. },
  1328. getComponent: function ( index ) {
  1329. switch ( index ) {
  1330. case 0: return this.x;
  1331. case 1: return this.y;
  1332. case 2: return this.z;
  1333. case 3: return this.w;
  1334. default: throw new Error( "index is out of range: " + index );
  1335. }
  1336. },
  1337. copy: function ( v ) {
  1338. this.x = v.x;
  1339. this.y = v.y;
  1340. this.z = v.z;
  1341. this.w = ( v.w !== undefined ) ? v.w : 1;
  1342. return this;
  1343. },
  1344. add: function ( v, w ) {
  1345. if ( w !== undefined ) {
  1346. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1347. return this.addVectors( v, w );
  1348. }
  1349. this.x += v.x;
  1350. this.y += v.y;
  1351. this.z += v.z;
  1352. this.w += v.w;
  1353. return this;
  1354. },
  1355. addScalar: function ( s ) {
  1356. this.x += s;
  1357. this.y += s;
  1358. this.z += s;
  1359. this.w += s;
  1360. return this;
  1361. },
  1362. addVectors: function ( a, b ) {
  1363. this.x = a.x + b.x;
  1364. this.y = a.y + b.y;
  1365. this.z = a.z + b.z;
  1366. this.w = a.w + b.w;
  1367. return this;
  1368. },
  1369. sub: function ( v, w ) {
  1370. if ( w !== undefined ) {
  1371. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1372. return this.subVectors( v, w );
  1373. }
  1374. this.x -= v.x;
  1375. this.y -= v.y;
  1376. this.z -= v.z;
  1377. this.w -= v.w;
  1378. return this;
  1379. },
  1380. subVectors: function ( a, b ) {
  1381. this.x = a.x - b.x;
  1382. this.y = a.y - b.y;
  1383. this.z = a.z - b.z;
  1384. this.w = a.w - b.w;
  1385. return this;
  1386. },
  1387. multiplyScalar: function ( s ) {
  1388. this.x *= s;
  1389. this.y *= s;
  1390. this.z *= s;
  1391. this.w *= s;
  1392. return this;
  1393. },
  1394. applyMatrix4: function ( m ) {
  1395. var x = this.x;
  1396. var y = this.y;
  1397. var z = this.z;
  1398. var w = this.w;
  1399. var e = m.elements;
  1400. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1401. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1402. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1403. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1404. return this;
  1405. },
  1406. divideScalar: function ( s ) {
  1407. if ( s !== 0 ) {
  1408. this.x /= s;
  1409. this.y /= s;
  1410. this.z /= s;
  1411. this.w /= s;
  1412. } else {
  1413. this.x = 0;
  1414. this.y = 0;
  1415. this.z = 0;
  1416. this.w = 1;
  1417. }
  1418. return this;
  1419. },
  1420. setAxisAngleFromQuaternion: function ( q ) {
  1421. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1422. // q is assumed to be normalized
  1423. this.w = 2 * Math.acos( q.w );
  1424. var s = Math.sqrt( 1 - q.w * q.w );
  1425. if ( s < 0.0001 ) {
  1426. this.x = 1;
  1427. this.y = 0;
  1428. this.z = 0;
  1429. } else {
  1430. this.x = q.x / s;
  1431. this.y = q.y / s;
  1432. this.z = q.z / s;
  1433. }
  1434. return this;
  1435. },
  1436. setAxisAngleFromRotationMatrix: function ( m ) {
  1437. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1438. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1439. var angle, x, y, z, // variables for result
  1440. epsilon = 0.01, // margin to allow for rounding errors
  1441. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1442. te = m.elements,
  1443. m11 = te[0], m12 = te[4], m13 = te[8],
  1444. m21 = te[1], m22 = te[5], m23 = te[9],
  1445. m31 = te[2], m32 = te[6], m33 = te[10];
  1446. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1447. && ( Math.abs( m13 - m31 ) < epsilon )
  1448. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1449. // singularity found
  1450. // first check for identity matrix which must have +1 for all terms
  1451. // in leading diagonal and zero in other terms
  1452. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1453. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1454. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1455. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1456. // this singularity is identity matrix so angle = 0
  1457. this.set( 1, 0, 0, 0 );
  1458. return this; // zero angle, arbitrary axis
  1459. }
  1460. // otherwise this singularity is angle = 180
  1461. angle = Math.PI;
  1462. var xx = ( m11 + 1 ) / 2;
  1463. var yy = ( m22 + 1 ) / 2;
  1464. var zz = ( m33 + 1 ) / 2;
  1465. var xy = ( m12 + m21 ) / 4;
  1466. var xz = ( m13 + m31 ) / 4;
  1467. var yz = ( m23 + m32 ) / 4;
  1468. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1469. if ( xx < epsilon ) {
  1470. x = 0;
  1471. y = 0.707106781;
  1472. z = 0.707106781;
  1473. } else {
  1474. x = Math.sqrt( xx );
  1475. y = xy / x;
  1476. z = xz / x;
  1477. }
  1478. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1479. if ( yy < epsilon ) {
  1480. x = 0.707106781;
  1481. y = 0;
  1482. z = 0.707106781;
  1483. } else {
  1484. y = Math.sqrt( yy );
  1485. x = xy / y;
  1486. z = yz / y;
  1487. }
  1488. } else { // m33 is the largest diagonal term so base result on this
  1489. if ( zz < epsilon ) {
  1490. x = 0.707106781;
  1491. y = 0.707106781;
  1492. z = 0;
  1493. } else {
  1494. z = Math.sqrt( zz );
  1495. x = xz / z;
  1496. y = yz / z;
  1497. }
  1498. }
  1499. this.set( x, y, z, angle );
  1500. return this; // return 180 deg rotation
  1501. }
  1502. // as we have reached here there are no singularities so we can handle normally
  1503. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1504. + ( m13 - m31 ) * ( m13 - m31 )
  1505. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1506. if ( Math.abs( s ) < 0.001 ) s = 1;
  1507. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1508. // caught by singularity test above, but I've left it in just in case
  1509. this.x = ( m32 - m23 ) / s;
  1510. this.y = ( m13 - m31 ) / s;
  1511. this.z = ( m21 - m12 ) / s;
  1512. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1513. return this;
  1514. },
  1515. min: function ( v ) {
  1516. if ( this.x > v.x ) {
  1517. this.x = v.x;
  1518. }
  1519. if ( this.y > v.y ) {
  1520. this.y = v.y;
  1521. }
  1522. if ( this.z > v.z ) {
  1523. this.z = v.z;
  1524. }
  1525. if ( this.w > v.w ) {
  1526. this.w = v.w;
  1527. }
  1528. return this;
  1529. },
  1530. max: function ( v ) {
  1531. if ( this.x < v.x ) {
  1532. this.x = v.x;
  1533. }
  1534. if ( this.y < v.y ) {
  1535. this.y = v.y;
  1536. }
  1537. if ( this.z < v.z ) {
  1538. this.z = v.z;
  1539. }
  1540. if ( this.w < v.w ) {
  1541. this.w = v.w;
  1542. }
  1543. return this;
  1544. },
  1545. clamp: function ( min, max ) {
  1546. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1547. if ( this.x < min.x ) {
  1548. this.x = min.x;
  1549. } else if ( this.x > max.x ) {
  1550. this.x = max.x;
  1551. }
  1552. if ( this.y < min.y ) {
  1553. this.y = min.y;
  1554. } else if ( this.y > max.y ) {
  1555. this.y = max.y;
  1556. }
  1557. if ( this.z < min.z ) {
  1558. this.z = min.z;
  1559. } else if ( this.z > max.z ) {
  1560. this.z = max.z;
  1561. }
  1562. if ( this.w < min.w ) {
  1563. this.w = min.w;
  1564. } else if ( this.w > max.w ) {
  1565. this.w = max.w;
  1566. }
  1567. return this;
  1568. },
  1569. negate: function() {
  1570. return this.multiplyScalar( -1 );
  1571. },
  1572. dot: function ( v ) {
  1573. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1574. },
  1575. lengthSq: function () {
  1576. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1577. },
  1578. length: function () {
  1579. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1580. },
  1581. lengthManhattan: function () {
  1582. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1583. },
  1584. normalize: function () {
  1585. return this.divideScalar( this.length() );
  1586. },
  1587. setLength: function ( l ) {
  1588. var oldLength = this.length();
  1589. if ( oldLength !== 0 && l !== oldLength ) {
  1590. this.multiplyScalar( l / oldLength );
  1591. }
  1592. return this;
  1593. },
  1594. lerp: function ( v, alpha ) {
  1595. this.x += ( v.x - this.x ) * alpha;
  1596. this.y += ( v.y - this.y ) * alpha;
  1597. this.z += ( v.z - this.z ) * alpha;
  1598. this.w += ( v.w - this.w ) * alpha;
  1599. return this;
  1600. },
  1601. equals: function ( v ) {
  1602. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1603. },
  1604. fromArray: function ( array ) {
  1605. this.x = array[ 0 ];
  1606. this.y = array[ 1 ];
  1607. this.z = array[ 2 ];
  1608. this.w = array[ 3 ];
  1609. return this;
  1610. },
  1611. toArray: function () {
  1612. return [ this.x, this.y, this.z, this.w ];
  1613. },
  1614. clone: function () {
  1615. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1616. }
  1617. };
  1618. /**
  1619. * @author bhouston / http://exocortex.com
  1620. */
  1621. THREE.Line3 = function ( start, end ) {
  1622. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1623. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1624. };
  1625. THREE.Line3.prototype = {
  1626. constructor: THREE.Line3,
  1627. set: function ( start, end ) {
  1628. this.start.copy( start );
  1629. this.end.copy( end );
  1630. return this;
  1631. },
  1632. copy: function ( line ) {
  1633. this.start.copy( line.start );
  1634. this.end.copy( line.end );
  1635. return this;
  1636. },
  1637. center: function ( optionalTarget ) {
  1638. var result = optionalTarget || new THREE.Vector3();
  1639. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1640. },
  1641. delta: function ( optionalTarget ) {
  1642. var result = optionalTarget || new THREE.Vector3();
  1643. return result.subVectors( this.end, this.start );
  1644. },
  1645. distanceSq: function () {
  1646. return this.start.distanceToSquared( this.end );
  1647. },
  1648. distance: function () {
  1649. return this.start.distanceTo( this.end );
  1650. },
  1651. at: function ( t, optionalTarget ) {
  1652. var result = optionalTarget || new THREE.Vector3();
  1653. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1654. },
  1655. closestPointToPointParameter: function() {
  1656. var startP = new THREE.Vector3();
  1657. var startEnd = new THREE.Vector3();
  1658. return function ( point, clampToLine ) {
  1659. startP.subVectors( point, this.start );
  1660. startEnd.subVectors( this.end, this.start );
  1661. var startEnd2 = startEnd.dot( startEnd );
  1662. var startEnd_startP = startEnd.dot( startP );
  1663. var t = startEnd_startP / startEnd2;
  1664. if ( clampToLine ) {
  1665. t = THREE.Math.clamp( t, 0, 1 );
  1666. }
  1667. return t;
  1668. };
  1669. }(),
  1670. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1671. var t = this.closestPointToPointParameter( point, clampToLine );
  1672. var result = optionalTarget || new THREE.Vector3();
  1673. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1674. },
  1675. applyMatrix4: function ( matrix ) {
  1676. this.start.applyMatrix4( matrix );
  1677. this.end.applyMatrix4( matrix );
  1678. return this;
  1679. },
  1680. equals: function ( line ) {
  1681. return line.start.equals( this.start ) && line.end.equals( this.end );
  1682. },
  1683. clone: function () {
  1684. return new THREE.Line3().copy( this );
  1685. }
  1686. };
  1687. /**
  1688. * @author bhouston / http://exocortex.com
  1689. */
  1690. THREE.Box2 = function ( min, max ) {
  1691. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1692. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1693. };
  1694. THREE.Box2.prototype = {
  1695. constructor: THREE.Box2,
  1696. set: function ( min, max ) {
  1697. this.min.copy( min );
  1698. this.max.copy( max );
  1699. return this;
  1700. },
  1701. setFromPoints: function ( points ) {
  1702. if ( points.length > 0 ) {
  1703. var point = points[ 0 ];
  1704. this.min.copy( point );
  1705. this.max.copy( point );
  1706. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1707. point = points[ i ];
  1708. if ( point.x < this.min.x ) {
  1709. this.min.x = point.x;
  1710. } else if ( point.x > this.max.x ) {
  1711. this.max.x = point.x;
  1712. }
  1713. if ( point.y < this.min.y ) {
  1714. this.min.y = point.y;
  1715. } else if ( point.y > this.max.y ) {
  1716. this.max.y = point.y;
  1717. }
  1718. }
  1719. } else {
  1720. this.makeEmpty();
  1721. }
  1722. return this;
  1723. },
  1724. setFromCenterAndSize: function () {
  1725. var v1 = new THREE.Vector2();
  1726. return function ( center, size ) {
  1727. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1728. this.min.copy( center ).sub( halfSize );
  1729. this.max.copy( center ).add( halfSize );
  1730. return this;
  1731. };
  1732. }(),
  1733. copy: function ( box ) {
  1734. this.min.copy( box.min );
  1735. this.max.copy( box.max );
  1736. return this;
  1737. },
  1738. makeEmpty: function () {
  1739. this.min.x = this.min.y = Infinity;
  1740. this.max.x = this.max.y = -Infinity;
  1741. return this;
  1742. },
  1743. empty: function () {
  1744. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1745. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1746. },
  1747. center: function ( optionalTarget ) {
  1748. var result = optionalTarget || new THREE.Vector2();
  1749. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1750. },
  1751. size: function ( optionalTarget ) {
  1752. var result = optionalTarget || new THREE.Vector2();
  1753. return result.subVectors( this.max, this.min );
  1754. },
  1755. expandByPoint: function ( point ) {
  1756. this.min.min( point );
  1757. this.max.max( point );
  1758. return this;
  1759. },
  1760. expandByVector: function ( vector ) {
  1761. this.min.sub( vector );
  1762. this.max.add( vector );
  1763. return this;
  1764. },
  1765. expandByScalar: function ( scalar ) {
  1766. this.min.addScalar( -scalar );
  1767. this.max.addScalar( scalar );
  1768. return this;
  1769. },
  1770. containsPoint: function ( point ) {
  1771. if ( point.x < this.min.x || point.x > this.max.x ||
  1772. point.y < this.min.y || point.y > this.max.y ) {
  1773. return false;
  1774. }
  1775. return true;
  1776. },
  1777. containsBox: function ( box ) {
  1778. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1779. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1780. return true;
  1781. }
  1782. return false;
  1783. },
  1784. getParameter: function ( point ) {
  1785. // This can potentially have a divide by zero if the box
  1786. // has a size dimension of 0.
  1787. return new THREE.Vector2(
  1788. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1789. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1790. );
  1791. },
  1792. isIntersectionBox: function ( box ) {
  1793. // using 6 splitting planes to rule out intersections.
  1794. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1795. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1796. return false;
  1797. }
  1798. return true;
  1799. },
  1800. clampPoint: function ( point, optionalTarget ) {
  1801. var result = optionalTarget || new THREE.Vector2();
  1802. return result.copy( point ).clamp( this.min, this.max );
  1803. },
  1804. distanceToPoint: function () {
  1805. var v1 = new THREE.Vector2();
  1806. return function ( point ) {
  1807. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1808. return clampedPoint.sub( point ).length();
  1809. };
  1810. }(),
  1811. intersect: function ( box ) {
  1812. this.min.max( box.min );
  1813. this.max.min( box.max );
  1814. return this;
  1815. },
  1816. union: function ( box ) {
  1817. this.min.min( box.min );
  1818. this.max.max( box.max );
  1819. return this;
  1820. },
  1821. translate: function ( offset ) {
  1822. this.min.add( offset );
  1823. this.max.add( offset );
  1824. return this;
  1825. },
  1826. equals: function ( box ) {
  1827. return box.min.equals( this.min ) && box.max.equals( this.max );
  1828. },
  1829. clone: function () {
  1830. return new THREE.Box2().copy( this );
  1831. }
  1832. };
  1833. /**
  1834. * @author bhouston / http://exocortex.com
  1835. * @author WestLangley / http://github.com/WestLangley
  1836. */
  1837. THREE.Box3 = function ( min, max ) {
  1838. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1839. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1840. };
  1841. THREE.Box3.prototype = {
  1842. constructor: THREE.Box3,
  1843. set: function ( min, max ) {
  1844. this.min.copy( min );
  1845. this.max.copy( max );
  1846. return this;
  1847. },
  1848. setFromPoints: function ( points ) {
  1849. if ( points.length > 0 ) {
  1850. var point = points[ 0 ];
  1851. this.min.copy( point );
  1852. this.max.copy( point );
  1853. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1854. point = points[ i ];
  1855. if ( point.x < this.min.x ) {
  1856. this.min.x = point.x;
  1857. } else if ( point.x > this.max.x ) {
  1858. this.max.x = point.x;
  1859. }
  1860. if ( point.y < this.min.y ) {
  1861. this.min.y = point.y;
  1862. } else if ( point.y > this.max.y ) {
  1863. this.max.y = point.y;
  1864. }
  1865. if ( point.z < this.min.z ) {
  1866. this.min.z = point.z;
  1867. } else if ( point.z > this.max.z ) {
  1868. this.max.z = point.z;
  1869. }
  1870. }
  1871. } else {
  1872. this.makeEmpty();
  1873. }
  1874. return this;
  1875. },
  1876. setFromCenterAndSize: function() {
  1877. var v1 = new THREE.Vector3();
  1878. return function ( center, size ) {
  1879. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1880. this.min.copy( center ).sub( halfSize );
  1881. this.max.copy( center ).add( halfSize );
  1882. return this;
  1883. };
  1884. }(),
  1885. setFromObject: function() {
  1886. // Computes the world-axis-aligned bounding box of an object (including its children),
  1887. // accounting for both the object's, and childrens', world transforms
  1888. var v1 = new THREE.Vector3();
  1889. return function( object ) {
  1890. var scope = this;
  1891. object.updateMatrixWorld( true );
  1892. this.makeEmpty();
  1893. object.traverse( function ( node ) {
  1894. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  1895. var vertices = node.geometry.vertices;
  1896. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  1897. v1.copy( vertices[ i ] );
  1898. v1.applyMatrix4( node.matrixWorld );
  1899. scope.expandByPoint( v1 );
  1900. }
  1901. }
  1902. } );
  1903. return this;
  1904. };
  1905. }(),
  1906. copy: function ( box ) {
  1907. this.min.copy( box.min );
  1908. this.max.copy( box.max );
  1909. return this;
  1910. },
  1911. makeEmpty: function () {
  1912. this.min.x = this.min.y = this.min.z = Infinity;
  1913. this.max.x = this.max.y = this.max.z = -Infinity;
  1914. return this;
  1915. },
  1916. empty: function () {
  1917. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1918. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1919. },
  1920. center: function ( optionalTarget ) {
  1921. var result = optionalTarget || new THREE.Vector3();
  1922. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1923. },
  1924. size: function ( optionalTarget ) {
  1925. var result = optionalTarget || new THREE.Vector3();
  1926. return result.subVectors( this.max, this.min );
  1927. },
  1928. expandByPoint: function ( point ) {
  1929. this.min.min( point );
  1930. this.max.max( point );
  1931. return this;
  1932. },
  1933. expandByVector: function ( vector ) {
  1934. this.min.sub( vector );
  1935. this.max.add( vector );
  1936. return this;
  1937. },
  1938. expandByScalar: function ( scalar ) {
  1939. this.min.addScalar( -scalar );
  1940. this.max.addScalar( scalar );
  1941. return this;
  1942. },
  1943. containsPoint: function ( point ) {
  1944. if ( point.x < this.min.x || point.x > this.max.x ||
  1945. point.y < this.min.y || point.y > this.max.y ||
  1946. point.z < this.min.z || point.z > this.max.z ) {
  1947. return false;
  1948. }
  1949. return true;
  1950. },
  1951. containsBox: function ( box ) {
  1952. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1953. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1954. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1955. return true;
  1956. }
  1957. return false;
  1958. },
  1959. getParameter: function ( point ) {
  1960. // This can potentially have a divide by zero if the box
  1961. // has a size dimension of 0.
  1962. return new THREE.Vector3(
  1963. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1964. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1965. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1966. );
  1967. },
  1968. isIntersectionBox: function ( box ) {
  1969. // using 6 splitting planes to rule out intersections.
  1970. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1971. box.max.y < this.min.y || box.min.y > this.max.y ||
  1972. box.max.z < this.min.z || box.min.z > this.max.z ) {
  1973. return false;
  1974. }
  1975. return true;
  1976. },
  1977. clampPoint: function ( point, optionalTarget ) {
  1978. var result = optionalTarget || new THREE.Vector3();
  1979. return result.copy( point ).clamp( this.min, this.max );
  1980. },
  1981. distanceToPoint: function() {
  1982. var v1 = new THREE.Vector3();
  1983. return function ( point ) {
  1984. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1985. return clampedPoint.sub( point ).length();
  1986. };
  1987. }(),
  1988. getBoundingSphere: function() {
  1989. var v1 = new THREE.Vector3();
  1990. return function ( optionalTarget ) {
  1991. var result = optionalTarget || new THREE.Sphere();
  1992. result.center = this.center();
  1993. result.radius = this.size( v1 ).length() * 0.5;
  1994. return result;
  1995. };
  1996. }(),
  1997. intersect: function ( box ) {
  1998. this.min.max( box.min );
  1999. this.max.min( box.max );
  2000. return this;
  2001. },
  2002. union: function ( box ) {
  2003. this.min.min( box.min );
  2004. this.max.max( box.max );
  2005. return this;
  2006. },
  2007. applyMatrix4: function() {
  2008. var points = [
  2009. new THREE.Vector3(),
  2010. new THREE.Vector3(),
  2011. new THREE.Vector3(),
  2012. new THREE.Vector3(),
  2013. new THREE.Vector3(),
  2014. new THREE.Vector3(),
  2015. new THREE.Vector3(),
  2016. new THREE.Vector3()
  2017. ];
  2018. return function ( matrix ) {
  2019. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2020. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2021. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2022. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2023. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2024. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2025. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2026. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2027. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2028. this.makeEmpty();
  2029. this.setFromPoints( points );
  2030. return this;
  2031. };
  2032. }(),
  2033. translate: function ( offset ) {
  2034. this.min.add( offset );
  2035. this.max.add( offset );
  2036. return this;
  2037. },
  2038. equals: function ( box ) {
  2039. return box.min.equals( this.min ) && box.max.equals( this.max );
  2040. },
  2041. clone: function () {
  2042. return new THREE.Box3().copy( this );
  2043. }
  2044. };
  2045. /**
  2046. * @author alteredq / http://alteredqualia.com/
  2047. * @author WestLangley / http://github.com/WestLangley
  2048. * @author bhouston / http://exocortex.com
  2049. */
  2050. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2051. this.elements = new Float32Array(9);
  2052. this.set(
  2053. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2054. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2055. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2056. );
  2057. };
  2058. THREE.Matrix3.prototype = {
  2059. constructor: THREE.Matrix3,
  2060. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2061. var te = this.elements;
  2062. te[0] = n11; te[3] = n12; te[6] = n13;
  2063. te[1] = n21; te[4] = n22; te[7] = n23;
  2064. te[2] = n31; te[5] = n32; te[8] = n33;
  2065. return this;
  2066. },
  2067. identity: function () {
  2068. this.set(
  2069. 1, 0, 0,
  2070. 0, 1, 0,
  2071. 0, 0, 1
  2072. );
  2073. return this;
  2074. },
  2075. copy: function ( m ) {
  2076. var me = m.elements;
  2077. this.set(
  2078. me[0], me[3], me[6],
  2079. me[1], me[4], me[7],
  2080. me[2], me[5], me[8]
  2081. );
  2082. return this;
  2083. },
  2084. multiplyVector3: function ( vector ) {
  2085. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2086. return vector.applyMatrix3( this );
  2087. },
  2088. multiplyVector3Array: function() {
  2089. var v1 = new THREE.Vector3();
  2090. return function ( a ) {
  2091. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2092. v1.x = a[ i ];
  2093. v1.y = a[ i + 1 ];
  2094. v1.z = a[ i + 2 ];
  2095. v1.applyMatrix3(this);
  2096. a[ i ] = v1.x;
  2097. a[ i + 1 ] = v1.y;
  2098. a[ i + 2 ] = v1.z;
  2099. }
  2100. return a;
  2101. };
  2102. }(),
  2103. multiplyScalar: function ( s ) {
  2104. var te = this.elements;
  2105. te[0] *= s; te[3] *= s; te[6] *= s;
  2106. te[1] *= s; te[4] *= s; te[7] *= s;
  2107. te[2] *= s; te[5] *= s; te[8] *= s;
  2108. return this;
  2109. },
  2110. determinant: function () {
  2111. var te = this.elements;
  2112. var a = te[0], b = te[1], c = te[2],
  2113. d = te[3], e = te[4], f = te[5],
  2114. g = te[6], h = te[7], i = te[8];
  2115. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2116. },
  2117. getInverse: function ( matrix, throwOnInvertible ) {
  2118. // input: THREE.Matrix4
  2119. // ( based on http://code.google.com/p/webgl-mjs/ )
  2120. var me = matrix.elements;
  2121. var te = this.elements;
  2122. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2123. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2124. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2125. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2126. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2127. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2128. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2129. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2130. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2131. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2132. // no inverse
  2133. if ( det === 0 ) {
  2134. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2135. if ( throwOnInvertible || false ) {
  2136. throw new Error( msg );
  2137. } else {
  2138. console.warn( msg );
  2139. }
  2140. this.identity();
  2141. return this;
  2142. }
  2143. this.multiplyScalar( 1.0 / det );
  2144. return this;
  2145. },
  2146. transpose: function () {
  2147. var tmp, m = this.elements;
  2148. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2149. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2150. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2151. return this;
  2152. },
  2153. getNormalMatrix: function ( m ) {
  2154. // input: THREE.Matrix4
  2155. this.getInverse( m ).transpose();
  2156. return this;
  2157. },
  2158. transposeIntoArray: function ( r ) {
  2159. var m = this.elements;
  2160. r[ 0 ] = m[ 0 ];
  2161. r[ 1 ] = m[ 3 ];
  2162. r[ 2 ] = m[ 6 ];
  2163. r[ 3 ] = m[ 1 ];
  2164. r[ 4 ] = m[ 4 ];
  2165. r[ 5 ] = m[ 7 ];
  2166. r[ 6 ] = m[ 2 ];
  2167. r[ 7 ] = m[ 5 ];
  2168. r[ 8 ] = m[ 8 ];
  2169. return this;
  2170. },
  2171. clone: function () {
  2172. var te = this.elements;
  2173. return new THREE.Matrix3(
  2174. te[0], te[3], te[6],
  2175. te[1], te[4], te[7],
  2176. te[2], te[5], te[8]
  2177. );
  2178. }
  2179. };
  2180. /**
  2181. * @author mrdoob / http://mrdoob.com/
  2182. * @author supereggbert / http://www.paulbrunt.co.uk/
  2183. * @author philogb / http://blog.thejit.org/
  2184. * @author jordi_ros / http://plattsoft.com
  2185. * @author D1plo1d / http://github.com/D1plo1d
  2186. * @author alteredq / http://alteredqualia.com/
  2187. * @author mikael emtinger / http://gomo.se/
  2188. * @author timknip / http://www.floorplanner.com/
  2189. * @author bhouston / http://exocortex.com
  2190. * @author WestLangley / http://github.com/WestLangley
  2191. */
  2192. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2193. var te = this.elements = new Float32Array( 16 );
  2194. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2195. // we should not support semi specification of Matrix4, it is just weird.
  2196. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2197. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2198. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2199. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2200. };
  2201. THREE.Matrix4.prototype = {
  2202. constructor: THREE.Matrix4,
  2203. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2204. var te = this.elements;
  2205. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2206. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2207. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2208. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2209. return this;
  2210. },
  2211. identity: function () {
  2212. this.set(
  2213. 1, 0, 0, 0,
  2214. 0, 1, 0, 0,
  2215. 0, 0, 1, 0,
  2216. 0, 0, 0, 1
  2217. );
  2218. return this;
  2219. },
  2220. copy: function ( m ) {
  2221. var me = m.elements;
  2222. this.set(
  2223. me[0], me[4], me[8], me[12],
  2224. me[1], me[5], me[9], me[13],
  2225. me[2], me[6], me[10], me[14],
  2226. me[3], me[7], me[11], me[15]
  2227. );
  2228. return this;
  2229. },
  2230. extractPosition: function ( m ) {
  2231. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2232. return this.copyPosition( m );
  2233. },
  2234. copyPosition: function ( m ) {
  2235. var te = this.elements;
  2236. var me = m.elements;
  2237. te[12] = me[12];
  2238. te[13] = me[13];
  2239. te[14] = me[14];
  2240. return this;
  2241. },
  2242. extractRotation: function () {
  2243. var v1 = new THREE.Vector3();
  2244. return function ( m ) {
  2245. var te = this.elements;
  2246. var me = m.elements;
  2247. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2248. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2249. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2250. te[0] = me[0] * scaleX;
  2251. te[1] = me[1] * scaleX;
  2252. te[2] = me[2] * scaleX;
  2253. te[4] = me[4] * scaleY;
  2254. te[5] = me[5] * scaleY;
  2255. te[6] = me[6] * scaleY;
  2256. te[8] = me[8] * scaleZ;
  2257. te[9] = me[9] * scaleZ;
  2258. te[10] = me[10] * scaleZ;
  2259. return this;
  2260. };
  2261. }(),
  2262. setRotationFromEuler: function ( v, order ) {
  2263. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromEuler() has been deprecated in favor of makeRotationFromEuler. Please update your code.' );
  2264. return this.makeRotationFromEuler( v, order );
  2265. },
  2266. makeRotationFromEuler: function ( v, order ) {
  2267. var te = this.elements;
  2268. var x = v.x, y = v.y, z = v.z;
  2269. var a = Math.cos( x ), b = Math.sin( x );
  2270. var c = Math.cos( y ), d = Math.sin( y );
  2271. var e = Math.cos( z ), f = Math.sin( z );
  2272. if ( order === undefined || order === 'XYZ' ) {
  2273. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2274. te[0] = c * e;
  2275. te[4] = - c * f;
  2276. te[8] = d;
  2277. te[1] = af + be * d;
  2278. te[5] = ae - bf * d;
  2279. te[9] = - b * c;
  2280. te[2] = bf - ae * d;
  2281. te[6] = be + af * d;
  2282. te[10] = a * c;
  2283. } else if ( order === 'YXZ' ) {
  2284. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2285. te[0] = ce + df * b;
  2286. te[4] = de * b - cf;
  2287. te[8] = a * d;
  2288. te[1] = a * f;
  2289. te[5] = a * e;
  2290. te[9] = - b;
  2291. te[2] = cf * b - de;
  2292. te[6] = df + ce * b;
  2293. te[10] = a * c;
  2294. } else if ( order === 'ZXY' ) {
  2295. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2296. te[0] = ce - df * b;
  2297. te[4] = - a * f;
  2298. te[8] = de + cf * b;
  2299. te[1] = cf + de * b;
  2300. te[5] = a * e;
  2301. te[9] = df - ce * b;
  2302. te[2] = - a * d;
  2303. te[6] = b;
  2304. te[10] = a * c;
  2305. } else if ( order === 'ZYX' ) {
  2306. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2307. te[0] = c * e;
  2308. te[4] = be * d - af;
  2309. te[8] = ae * d + bf;
  2310. te[1] = c * f;
  2311. te[5] = bf * d + ae;
  2312. te[9] = af * d - be;
  2313. te[2] = - d;
  2314. te[6] = b * c;
  2315. te[10] = a * c;
  2316. } else if ( order === 'YZX' ) {
  2317. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2318. te[0] = c * e;
  2319. te[4] = bd - ac * f;
  2320. te[8] = bc * f + ad;
  2321. te[1] = f;
  2322. te[5] = a * e;
  2323. te[9] = - b * e;
  2324. te[2] = - d * e;
  2325. te[6] = ad * f + bc;
  2326. te[10] = ac - bd * f;
  2327. } else if ( order === 'XZY' ) {
  2328. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2329. te[0] = c * e;
  2330. te[4] = - f;
  2331. te[8] = d * e;
  2332. te[1] = ac * f + bd;
  2333. te[5] = a * e;
  2334. te[9] = ad * f - bc;
  2335. te[2] = bc * f - ad;
  2336. te[6] = b * e;
  2337. te[10] = bd * f + ac;
  2338. }
  2339. // last column
  2340. te[3] = 0;
  2341. te[7] = 0;
  2342. te[11] = 0;
  2343. // bottom row
  2344. te[12] = 0;
  2345. te[13] = 0;
  2346. te[14] = 0;
  2347. te[15] = 1;
  2348. return this;
  2349. },
  2350. setRotationFromQuaternion: function ( q ) {
  2351. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2352. return this.makeRotationFromQuaternion( q );
  2353. },
  2354. makeRotationFromQuaternion: function ( q ) {
  2355. var te = this.elements;
  2356. var x = q.x, y = q.y, z = q.z, w = q.w;
  2357. var x2 = x + x, y2 = y + y, z2 = z + z;
  2358. var xx = x * x2, xy = x * y2, xz = x * z2;
  2359. var yy = y * y2, yz = y * z2, zz = z * z2;
  2360. var wx = w * x2, wy = w * y2, wz = w * z2;
  2361. te[0] = 1 - ( yy + zz );
  2362. te[4] = xy - wz;
  2363. te[8] = xz + wy;
  2364. te[1] = xy + wz;
  2365. te[5] = 1 - ( xx + zz );
  2366. te[9] = yz - wx;
  2367. te[2] = xz - wy;
  2368. te[6] = yz + wx;
  2369. te[10] = 1 - ( xx + yy );
  2370. // last column
  2371. te[3] = 0;
  2372. te[7] = 0;
  2373. te[11] = 0;
  2374. // bottom row
  2375. te[12] = 0;
  2376. te[13] = 0;
  2377. te[14] = 0;
  2378. te[15] = 1;
  2379. return this;
  2380. },
  2381. lookAt: function() {
  2382. var x = new THREE.Vector3();
  2383. var y = new THREE.Vector3();
  2384. var z = new THREE.Vector3();
  2385. return function ( eye, target, up ) {
  2386. var te = this.elements;
  2387. z.subVectors( eye, target ).normalize();
  2388. if ( z.length() === 0 ) {
  2389. z.z = 1;
  2390. }
  2391. x.crossVectors( up, z ).normalize();
  2392. if ( x.length() === 0 ) {
  2393. z.x += 0.0001;
  2394. x.crossVectors( up, z ).normalize();
  2395. }
  2396. y.crossVectors( z, x );
  2397. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2398. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2399. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2400. return this;
  2401. };
  2402. }(),
  2403. multiply: function ( m, n ) {
  2404. if ( n !== undefined ) {
  2405. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2406. return this.multiplyMatrices( m, n );
  2407. }
  2408. return this.multiplyMatrices( this, m );
  2409. },
  2410. multiplyMatrices: function ( a, b ) {
  2411. var ae = a.elements;
  2412. var be = b.elements;
  2413. var te = this.elements;
  2414. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2415. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2416. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2417. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2418. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2419. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2420. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2421. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2422. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2423. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2424. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2425. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2426. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2427. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2428. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2429. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2430. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2431. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2432. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2433. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2434. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2435. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2436. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2437. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2438. return this;
  2439. },
  2440. multiplyToArray: function ( a, b, r ) {
  2441. var te = this.elements;
  2442. this.multiplyMatrices( a, b );
  2443. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2444. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2445. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2446. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2447. return this;
  2448. },
  2449. multiplyScalar: function ( s ) {
  2450. var te = this.elements;
  2451. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2452. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2453. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2454. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2455. return this;
  2456. },
  2457. multiplyVector3: function ( vector ) {
  2458. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2459. return vector.applyProjection( this );
  2460. },
  2461. multiplyVector4: function ( vector ) {
  2462. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2463. return vector.applyMatrix4( this );
  2464. },
  2465. multiplyVector3Array: function() {
  2466. var v1 = new THREE.Vector3();
  2467. return function ( a ) {
  2468. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2469. v1.x = a[ i ];
  2470. v1.y = a[ i + 1 ];
  2471. v1.z = a[ i + 2 ];
  2472. v1.applyProjection( this );
  2473. a[ i ] = v1.x;
  2474. a[ i + 1 ] = v1.y;
  2475. a[ i + 2 ] = v1.z;
  2476. }
  2477. return a;
  2478. };
  2479. }(),
  2480. rotateAxis: function ( v ) {
  2481. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2482. v.transformDirection( this );
  2483. },
  2484. crossVector: function ( vector ) {
  2485. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2486. return vector.applyMatrix4( this );
  2487. },
  2488. determinant: function () {
  2489. var te = this.elements;
  2490. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2491. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2492. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2493. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2494. //TODO: make this more efficient
  2495. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2496. return (
  2497. n41 * (
  2498. +n14 * n23 * n32
  2499. -n13 * n24 * n32
  2500. -n14 * n22 * n33
  2501. +n12 * n24 * n33
  2502. +n13 * n22 * n34
  2503. -n12 * n23 * n34
  2504. ) +
  2505. n42 * (
  2506. +n11 * n23 * n34
  2507. -n11 * n24 * n33
  2508. +n14 * n21 * n33
  2509. -n13 * n21 * n34
  2510. +n13 * n24 * n31
  2511. -n14 * n23 * n31
  2512. ) +
  2513. n43 * (
  2514. +n11 * n24 * n32
  2515. -n11 * n22 * n34
  2516. -n14 * n21 * n32
  2517. +n12 * n21 * n34
  2518. +n14 * n22 * n31
  2519. -n12 * n24 * n31
  2520. ) +
  2521. n44 * (
  2522. -n13 * n22 * n31
  2523. -n11 * n23 * n32
  2524. +n11 * n22 * n33
  2525. +n13 * n21 * n32
  2526. -n12 * n21 * n33
  2527. +n12 * n23 * n31
  2528. )
  2529. );
  2530. },
  2531. transpose: function () {
  2532. var te = this.elements;
  2533. var tmp;
  2534. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2535. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2536. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2537. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2538. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2539. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2540. return this;
  2541. },
  2542. flattenToArray: function ( flat ) {
  2543. var te = this.elements;
  2544. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2545. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2546. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2547. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2548. return flat;
  2549. },
  2550. flattenToArrayOffset: function( flat, offset ) {
  2551. var te = this.elements;
  2552. flat[ offset ] = te[0];
  2553. flat[ offset + 1 ] = te[1];
  2554. flat[ offset + 2 ] = te[2];
  2555. flat[ offset + 3 ] = te[3];
  2556. flat[ offset + 4 ] = te[4];
  2557. flat[ offset + 5 ] = te[5];
  2558. flat[ offset + 6 ] = te[6];
  2559. flat[ offset + 7 ] = te[7];
  2560. flat[ offset + 8 ] = te[8];
  2561. flat[ offset + 9 ] = te[9];
  2562. flat[ offset + 10 ] = te[10];
  2563. flat[ offset + 11 ] = te[11];
  2564. flat[ offset + 12 ] = te[12];
  2565. flat[ offset + 13 ] = te[13];
  2566. flat[ offset + 14 ] = te[14];
  2567. flat[ offset + 15 ] = te[15];
  2568. return flat;
  2569. },
  2570. getPosition: function() {
  2571. var v1 = new THREE.Vector3();
  2572. return function () {
  2573. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2574. var te = this.elements;
  2575. return v1.set( te[12], te[13], te[14] );
  2576. };
  2577. }(),
  2578. setPosition: function ( v ) {
  2579. var te = this.elements;
  2580. te[12] = v.x;
  2581. te[13] = v.y;
  2582. te[14] = v.z;
  2583. return this;
  2584. },
  2585. getInverse: function ( m, throwOnInvertible ) {
  2586. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2587. var te = this.elements;
  2588. var me = m.elements;
  2589. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2590. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2591. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2592. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2593. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2594. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2595. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2596. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2597. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2598. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2599. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2600. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2601. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2602. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2603. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2604. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2605. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2606. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2607. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2608. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2609. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2610. if ( det == 0 ) {
  2611. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2612. if ( throwOnInvertible || false ) {
  2613. throw new Error( msg );
  2614. } else {
  2615. console.warn( msg );
  2616. }
  2617. this.identity();
  2618. return this;
  2619. }
  2620. this.multiplyScalar( 1 / det );
  2621. return this;
  2622. },
  2623. translate: function ( v ) {
  2624. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2625. },
  2626. rotateX: function ( angle ) {
  2627. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2628. },
  2629. rotateY: function ( angle ) {
  2630. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2631. },
  2632. rotateZ: function ( angle ) {
  2633. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2634. },
  2635. rotateByAxis: function ( axis, angle ) {
  2636. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2637. },
  2638. scale: function ( v ) {
  2639. var te = this.elements;
  2640. var x = v.x, y = v.y, z = v.z;
  2641. te[0] *= x; te[4] *= y; te[8] *= z;
  2642. te[1] *= x; te[5] *= y; te[9] *= z;
  2643. te[2] *= x; te[6] *= y; te[10] *= z;
  2644. te[3] *= x; te[7] *= y; te[11] *= z;
  2645. return this;
  2646. },
  2647. getMaxScaleOnAxis: function () {
  2648. var te = this.elements;
  2649. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2650. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2651. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2652. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2653. },
  2654. makeTranslation: function ( x, y, z ) {
  2655. this.set(
  2656. 1, 0, 0, x,
  2657. 0, 1, 0, y,
  2658. 0, 0, 1, z,
  2659. 0, 0, 0, 1
  2660. );
  2661. return this;
  2662. },
  2663. makeRotationX: function ( theta ) {
  2664. var c = Math.cos( theta ), s = Math.sin( theta );
  2665. this.set(
  2666. 1, 0, 0, 0,
  2667. 0, c, -s, 0,
  2668. 0, s, c, 0,
  2669. 0, 0, 0, 1
  2670. );
  2671. return this;
  2672. },
  2673. makeRotationY: function ( theta ) {
  2674. var c = Math.cos( theta ), s = Math.sin( theta );
  2675. this.set(
  2676. c, 0, s, 0,
  2677. 0, 1, 0, 0,
  2678. -s, 0, c, 0,
  2679. 0, 0, 0, 1
  2680. );
  2681. return this;
  2682. },
  2683. makeRotationZ: function ( theta ) {
  2684. var c = Math.cos( theta ), s = Math.sin( theta );
  2685. this.set(
  2686. c, -s, 0, 0,
  2687. s, c, 0, 0,
  2688. 0, 0, 1, 0,
  2689. 0, 0, 0, 1
  2690. );
  2691. return this;
  2692. },
  2693. makeRotationAxis: function ( axis, angle ) {
  2694. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2695. var c = Math.cos( angle );
  2696. var s = Math.sin( angle );
  2697. var t = 1 - c;
  2698. var x = axis.x, y = axis.y, z = axis.z;
  2699. var tx = t * x, ty = t * y;
  2700. this.set(
  2701. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2702. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2703. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2704. 0, 0, 0, 1
  2705. );
  2706. return this;
  2707. },
  2708. makeScale: function ( x, y, z ) {
  2709. this.set(
  2710. x, 0, 0, 0,
  2711. 0, y, 0, 0,
  2712. 0, 0, z, 0,
  2713. 0, 0, 0, 1
  2714. );
  2715. return this;
  2716. },
  2717. compose: function ( position, quaternion, scale ) {
  2718. console.warn( 'DEPRECATED: Matrix4\'s .compose() has been deprecated in favor of makeFromPositionQuaternionScale. Please update your code.' );
  2719. return this.makeFromPositionQuaternionScale( position, quaternion, scale );
  2720. },
  2721. makeFromPositionQuaternionScale: function ( position, quaternion, scale ) {
  2722. this.makeRotationFromQuaternion( quaternion );
  2723. this.scale( scale );
  2724. this.setPosition( position );
  2725. return this;
  2726. },
  2727. makeFromPositionEulerScale: function ( position, rotation, eulerOrder, scale ) {
  2728. this.makeRotationFromEuler( rotation, eulerOrder );
  2729. this.scale( scale );
  2730. this.setPosition( position );
  2731. return this;
  2732. },
  2733. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2734. var te = this.elements;
  2735. var x = 2 * near / ( right - left );
  2736. var y = 2 * near / ( top - bottom );
  2737. var a = ( right + left ) / ( right - left );
  2738. var b = ( top + bottom ) / ( top - bottom );
  2739. var c = - ( far + near ) / ( far - near );
  2740. var d = - 2 * far * near / ( far - near );
  2741. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2742. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2743. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2744. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2745. return this;
  2746. },
  2747. makePerspective: function ( fov, aspect, near, far ) {
  2748. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2749. var ymin = - ymax;
  2750. var xmin = ymin * aspect;
  2751. var xmax = ymax * aspect;
  2752. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2753. },
  2754. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2755. var te = this.elements;
  2756. var w = right - left;
  2757. var h = top - bottom;
  2758. var p = far - near;
  2759. var x = ( right + left ) / w;
  2760. var y = ( top + bottom ) / h;
  2761. var z = ( far + near ) / p;
  2762. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2763. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2764. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2765. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2766. return this;
  2767. },
  2768. clone: function () {
  2769. var te = this.elements;
  2770. return new THREE.Matrix4(
  2771. te[0], te[4], te[8], te[12],
  2772. te[1], te[5], te[9], te[13],
  2773. te[2], te[6], te[10], te[14],
  2774. te[3], te[7], te[11], te[15]
  2775. );
  2776. }
  2777. };
  2778. THREE.extend( THREE.Matrix4.prototype, {
  2779. decompose: function() {
  2780. var x = new THREE.Vector3();
  2781. var y = new THREE.Vector3();
  2782. var z = new THREE.Vector3();
  2783. var matrix = new THREE.Matrix4();
  2784. return function ( position, quaternion, scale ) {
  2785. var te = this.elements;
  2786. // grab the axis vectors
  2787. x.set( te[0], te[1], te[2] );
  2788. y.set( te[4], te[5], te[6] );
  2789. z.set( te[8], te[9], te[10] );
  2790. position = ( position instanceof THREE.Vector3 ) ? position : new THREE.Vector3();
  2791. quaternion = ( quaternion instanceof THREE.Quaternion ) ? quaternion : new THREE.Quaternion();
  2792. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2793. scale.x = x.length();
  2794. scale.y = y.length();
  2795. scale.z = z.length();
  2796. position.x = te[12];
  2797. position.y = te[13];
  2798. position.z = te[14];
  2799. // scale the rotation part
  2800. matrix.copy( this );
  2801. matrix.elements[0] /= scale.x;
  2802. matrix.elements[1] /= scale.x;
  2803. matrix.elements[2] /= scale.x;
  2804. matrix.elements[4] /= scale.y;
  2805. matrix.elements[5] /= scale.y;
  2806. matrix.elements[6] /= scale.y;
  2807. matrix.elements[8] /= scale.z;
  2808. matrix.elements[9] /= scale.z;
  2809. matrix.elements[10] /= scale.z;
  2810. quaternion.setFromRotationMatrix( matrix );
  2811. return [ position, quaternion, scale ];
  2812. };
  2813. }()
  2814. } );
  2815. /**
  2816. * @author bhouston / http://exocortex.com
  2817. */
  2818. THREE.Ray = function ( origin, direction ) {
  2819. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2820. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2821. };
  2822. THREE.Ray.prototype = {
  2823. constructor: THREE.Ray,
  2824. set: function ( origin, direction ) {
  2825. this.origin.copy( origin );
  2826. this.direction.copy( direction );
  2827. return this;
  2828. },
  2829. copy: function ( ray ) {
  2830. this.origin.copy( ray.origin );
  2831. this.direction.copy( ray.direction );
  2832. return this;
  2833. },
  2834. at: function( t, optionalTarget ) {
  2835. var result = optionalTarget || new THREE.Vector3();
  2836. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2837. },
  2838. recast: function() {
  2839. var v1 = new THREE.Vector3();
  2840. return function ( t ) {
  2841. this.origin.copy( this.at( t, v1 ) );
  2842. return this;
  2843. };
  2844. }(),
  2845. closestPointToPoint: function ( point, optionalTarget ) {
  2846. var result = optionalTarget || new THREE.Vector3();
  2847. result.subVectors( point, this.origin );
  2848. var directionDistance = result.dot( this.direction );
  2849. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2850. },
  2851. distanceToPoint: function() {
  2852. var v1 = new THREE.Vector3();
  2853. return function ( point ) {
  2854. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  2855. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2856. return v1.distanceTo( point );
  2857. };
  2858. }(),
  2859. isIntersectionSphere: function( sphere ) {
  2860. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2861. },
  2862. isIntersectionPlane: function ( plane ) {
  2863. // check if the line and plane are non-perpendicular, if they
  2864. // eventually they will intersect.
  2865. var denominator = plane.normal.dot( this.direction );
  2866. if ( denominator != 0 ) {
  2867. return true;
  2868. }
  2869. // line is coplanar, return origin
  2870. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2871. return true;
  2872. }
  2873. return false;
  2874. },
  2875. distanceToPlane: function ( plane ) {
  2876. var denominator = plane.normal.dot( this.direction );
  2877. if ( denominator == 0 ) {
  2878. // line is coplanar, return origin
  2879. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2880. return 0;
  2881. }
  2882. // Unsure if this is the correct method to handle this case.
  2883. return undefined;
  2884. }
  2885. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2886. return t;
  2887. },
  2888. intersectPlane: function ( plane, optionalTarget ) {
  2889. var t = this.distanceToPlane( plane );
  2890. if ( t === undefined ) {
  2891. return undefined;
  2892. }
  2893. return this.at( t, optionalTarget );
  2894. },
  2895. applyMatrix4: function ( matrix4 ) {
  2896. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2897. this.origin.applyMatrix4( matrix4 );
  2898. this.direction.sub( this.origin );
  2899. return this;
  2900. },
  2901. equals: function ( ray ) {
  2902. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2903. },
  2904. clone: function () {
  2905. return new THREE.Ray().copy( this );
  2906. }
  2907. };
  2908. /**
  2909. * @author bhouston / http://exocortex.com
  2910. * @author mrdoob / http://mrdoob.com/
  2911. */
  2912. THREE.Sphere = function ( center, radius ) {
  2913. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  2914. this.radius = ( radius !== undefined ) ? radius : 0;
  2915. };
  2916. THREE.Sphere.prototype = {
  2917. constructor: THREE.Sphere,
  2918. set: function ( center, radius ) {
  2919. this.center.copy( center );
  2920. this.radius = radius;
  2921. return this;
  2922. },
  2923. setFromPoints: function ( points ) {
  2924. var radiusSq, maxRadiusSq = 0;
  2925. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2926. radiusSq = points[ i ].lengthSq();
  2927. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2928. }
  2929. this.center.set( 0, 0, 0 );
  2930. this.radius = Math.sqrt( maxRadiusSq );
  2931. return this;
  2932. },
  2933. copy: function ( sphere ) {
  2934. this.center.copy( sphere.center );
  2935. this.radius = sphere.radius;
  2936. return this;
  2937. },
  2938. empty: function () {
  2939. return ( this.radius <= 0 );
  2940. },
  2941. containsPoint: function ( point ) {
  2942. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2943. },
  2944. distanceToPoint: function ( point ) {
  2945. return ( point.distanceTo( this.center ) - this.radius );
  2946. },
  2947. intersectsSphere: function ( sphere ) {
  2948. var radiusSum = this.radius + sphere.radius;
  2949. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2950. },
  2951. clampPoint: function ( point, optionalTarget ) {
  2952. var deltaLengthSq = this.center.distanceToSquared( point );
  2953. var result = optionalTarget || new THREE.Vector3();
  2954. result.copy( point );
  2955. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2956. result.sub( this.center ).normalize();
  2957. result.multiplyScalar( this.radius ).add( this.center );
  2958. }
  2959. return result;
  2960. },
  2961. getBoundingBox: function ( optionalTarget ) {
  2962. var box = optionalTarget || new THREE.Box3();
  2963. box.set( this.center, this.center );
  2964. box.expandByScalar( this.radius );
  2965. return box;
  2966. },
  2967. applyMatrix4: function ( matrix ) {
  2968. this.center.applyMatrix4( matrix );
  2969. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2970. return this;
  2971. },
  2972. translate: function ( offset ) {
  2973. this.center.add( offset );
  2974. return this;
  2975. },
  2976. equals: function ( sphere ) {
  2977. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2978. },
  2979. clone: function () {
  2980. return new THREE.Sphere().copy( this );
  2981. }
  2982. };
  2983. /**
  2984. * @author mrdoob / http://mrdoob.com/
  2985. * @author alteredq / http://alteredqualia.com/
  2986. * @author bhouston / http://exocortex.com
  2987. */
  2988. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2989. this.planes = [
  2990. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2991. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2992. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2993. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2994. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2995. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2996. ];
  2997. };
  2998. THREE.Frustum.prototype = {
  2999. constructor: THREE.Frustum,
  3000. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3001. var planes = this.planes;
  3002. planes[0].copy( p0 );
  3003. planes[1].copy( p1 );
  3004. planes[2].copy( p2 );
  3005. planes[3].copy( p3 );
  3006. planes[4].copy( p4 );
  3007. planes[5].copy( p5 );
  3008. return this;
  3009. },
  3010. copy: function ( frustum ) {
  3011. var planes = this.planes;
  3012. for( var i = 0; i < 6; i ++ ) {
  3013. planes[i].copy( frustum.planes[i] );
  3014. }
  3015. return this;
  3016. },
  3017. setFromMatrix: function ( m ) {
  3018. var planes = this.planes;
  3019. var me = m.elements;
  3020. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3021. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3022. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3023. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3024. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3025. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3026. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3027. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3028. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3029. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3030. return this;
  3031. },
  3032. intersectsObject: function () {
  3033. var center = new THREE.Vector3();
  3034. return function ( object ) {
  3035. // this method is expanded inlined for performance reasons.
  3036. var matrix = object.matrixWorld;
  3037. var planes = this.planes;
  3038. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3039. center.getPositionFromMatrix( matrix );
  3040. for ( var i = 0; i < 6; i ++ ) {
  3041. var distance = planes[ i ].distanceToPoint( center );
  3042. if ( distance < negRadius ) {
  3043. return false;
  3044. }
  3045. }
  3046. return true;
  3047. };
  3048. }(),
  3049. intersectsSphere: function ( sphere ) {
  3050. var planes = this.planes;
  3051. var center = sphere.center;
  3052. var negRadius = -sphere.radius;
  3053. for ( var i = 0; i < 6; i ++ ) {
  3054. var distance = planes[ i ].distanceToPoint( center );
  3055. if ( distance < negRadius ) {
  3056. return false;
  3057. }
  3058. }
  3059. return true;
  3060. },
  3061. containsPoint: function ( point ) {
  3062. var planes = this.planes;
  3063. for ( var i = 0; i < 6; i ++ ) {
  3064. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3065. return false;
  3066. }
  3067. }
  3068. return true;
  3069. },
  3070. clone: function () {
  3071. return new THREE.Frustum().copy( this );
  3072. }
  3073. };
  3074. /**
  3075. * @author bhouston / http://exocortex.com
  3076. */
  3077. THREE.Plane = function ( normal, constant ) {
  3078. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3079. this.constant = ( constant !== undefined ) ? constant : 0;
  3080. };
  3081. THREE.Plane.prototype = {
  3082. constructor: THREE.Plane,
  3083. set: function ( normal, constant ) {
  3084. this.normal.copy( normal );
  3085. this.constant = constant;
  3086. return this;
  3087. },
  3088. setComponents: function ( x, y, z, w ) {
  3089. this.normal.set( x, y, z );
  3090. this.constant = w;
  3091. return this;
  3092. },
  3093. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3094. this.normal.copy( normal );
  3095. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3096. return this;
  3097. },
  3098. setFromCoplanarPoints: function() {
  3099. var v1 = new THREE.Vector3();
  3100. var v2 = new THREE.Vector3();
  3101. return function ( a, b, c ) {
  3102. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3103. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3104. this.setFromNormalAndCoplanarPoint( normal, a );
  3105. return this;
  3106. };
  3107. }(),
  3108. copy: function ( plane ) {
  3109. this.normal.copy( plane.normal );
  3110. this.constant = plane.constant;
  3111. return this;
  3112. },
  3113. normalize: function () {
  3114. // Note: will lead to a divide by zero if the plane is invalid.
  3115. var inverseNormalLength = 1.0 / this.normal.length();
  3116. this.normal.multiplyScalar( inverseNormalLength );
  3117. this.constant *= inverseNormalLength;
  3118. return this;
  3119. },
  3120. negate: function () {
  3121. this.constant *= -1;
  3122. this.normal.negate();
  3123. return this;
  3124. },
  3125. distanceToPoint: function ( point ) {
  3126. return this.normal.dot( point ) + this.constant;
  3127. },
  3128. distanceToSphere: function ( sphere ) {
  3129. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3130. },
  3131. projectPoint: function ( point, optionalTarget ) {
  3132. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3133. },
  3134. orthoPoint: function ( point, optionalTarget ) {
  3135. var perpendicularMagnitude = this.distanceToPoint( point );
  3136. var result = optionalTarget || new THREE.Vector3();
  3137. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3138. },
  3139. isIntersectionLine: function ( line ) {
  3140. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3141. var startSign = this.distanceToPoint( line.start );
  3142. var endSign = this.distanceToPoint( line.end );
  3143. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3144. },
  3145. intersectLine: function() {
  3146. var v1 = new THREE.Vector3();
  3147. return function ( line, optionalTarget ) {
  3148. var result = optionalTarget || new THREE.Vector3();
  3149. var direction = line.delta( v1 );
  3150. var denominator = this.normal.dot( direction );
  3151. if ( denominator == 0 ) {
  3152. // line is coplanar, return origin
  3153. if( this.distanceToPoint( line.start ) == 0 ) {
  3154. return result.copy( line.start );
  3155. }
  3156. // Unsure if this is the correct method to handle this case.
  3157. return undefined;
  3158. }
  3159. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3160. if( t < 0 || t > 1 ) {
  3161. return undefined;
  3162. }
  3163. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3164. };
  3165. }(),
  3166. coplanarPoint: function ( optionalTarget ) {
  3167. var result = optionalTarget || new THREE.Vector3();
  3168. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3169. },
  3170. applyMatrix4: function() {
  3171. var v1 = new THREE.Vector3();
  3172. var v2 = new THREE.Vector3();
  3173. return function ( matrix, optionalNormalMatrix ) {
  3174. // compute new normal based on theory here:
  3175. // http://www.songho.ca/opengl/gl_normaltransform.html
  3176. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3177. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3178. var newCoplanarPoint = this.coplanarPoint( v2 );
  3179. newCoplanarPoint.applyMatrix4( matrix );
  3180. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3181. return this;
  3182. };
  3183. }(),
  3184. translate: function ( offset ) {
  3185. this.constant = this.constant - offset.dot( this.normal );
  3186. return this;
  3187. },
  3188. equals: function ( plane ) {
  3189. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3190. },
  3191. clone: function () {
  3192. return new THREE.Plane().copy( this );
  3193. }
  3194. };
  3195. /**
  3196. * @author alteredq / http://alteredqualia.com/
  3197. * @author mrdoob / http://mrdoob.com/
  3198. */
  3199. THREE.Math = {
  3200. generateUUID: function () {
  3201. // http://www.broofa.com/Tools/Math.uuid.htm
  3202. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3203. var uuid = new Array(36);
  3204. var rnd = 0, r;
  3205. return function () {
  3206. for ( var i = 0; i < 36; i ++ ) {
  3207. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3208. uuid[ i ] = '-';
  3209. } else if ( i == 14 ) {
  3210. uuid[ i ] = '4';
  3211. } else {
  3212. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3213. r = rnd & 0xf;
  3214. rnd = rnd >> 4;
  3215. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3216. }
  3217. }
  3218. return uuid.join('');
  3219. };
  3220. }(),
  3221. // Clamp value to range <a, b>
  3222. clamp: function ( x, a, b ) {
  3223. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3224. },
  3225. // Clamp value to range <a, inf)
  3226. clampBottom: function ( x, a ) {
  3227. return x < a ? a : x;
  3228. },
  3229. // Linear mapping from range <a1, a2> to range <b1, b2>
  3230. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3231. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3232. },
  3233. // http://en.wikipedia.org/wiki/Smoothstep
  3234. smoothstep: function ( x, min, max ) {
  3235. if ( x <= min ) return 0;
  3236. if ( x >= max ) return 1;
  3237. x = ( x - min )/( max - min );
  3238. return x*x*(3 - 2*x);
  3239. },
  3240. smootherstep: function ( x, min, max ) {
  3241. if ( x <= min ) return 0;
  3242. if ( x >= max ) return 1;
  3243. x = ( x - min )/( max - min );
  3244. return x*x*x*(x*(x*6 - 15) + 10);
  3245. },
  3246. // Random float from <0, 1> with 16 bits of randomness
  3247. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3248. random16: function () {
  3249. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3250. },
  3251. // Random integer from <low, high> interval
  3252. randInt: function ( low, high ) {
  3253. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3254. },
  3255. // Random float from <low, high> interval
  3256. randFloat: function ( low, high ) {
  3257. return low + Math.random() * ( high - low );
  3258. },
  3259. // Random float from <-range/2, range/2> interval
  3260. randFloatSpread: function ( range ) {
  3261. return range * ( 0.5 - Math.random() );
  3262. },
  3263. sign: function ( x ) {
  3264. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3265. },
  3266. degToRad: function() {
  3267. var degreeToRadiansFactor = Math.PI / 180;
  3268. return function ( degrees ) {
  3269. return degrees * degreeToRadiansFactor;
  3270. };
  3271. }(),
  3272. radToDeg: function() {
  3273. var radianToDegreesFactor = 180 / Math.PI;
  3274. return function ( radians ) {
  3275. return radians * radianToDegreesFactor;
  3276. };
  3277. }()
  3278. };
  3279. /**
  3280. * Spline from Tween.js, slightly optimized (and trashed)
  3281. * http://sole.github.com/tween.js/examples/05_spline.html
  3282. *
  3283. * @author mrdoob / http://mrdoob.com/
  3284. * @author alteredq / http://alteredqualia.com/
  3285. */
  3286. THREE.Spline = function ( points ) {
  3287. this.points = points;
  3288. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3289. point, intPoint, weight, w2, w3,
  3290. pa, pb, pc, pd;
  3291. this.initFromArray = function( a ) {
  3292. this.points = [];
  3293. for ( var i = 0; i < a.length; i++ ) {
  3294. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3295. }
  3296. };
  3297. this.getPoint = function ( k ) {
  3298. point = ( this.points.length - 1 ) * k;
  3299. intPoint = Math.floor( point );
  3300. weight = point - intPoint;
  3301. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3302. c[ 1 ] = intPoint;
  3303. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3304. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3305. pa = this.points[ c[ 0 ] ];
  3306. pb = this.points[ c[ 1 ] ];
  3307. pc = this.points[ c[ 2 ] ];
  3308. pd = this.points[ c[ 3 ] ];
  3309. w2 = weight * weight;
  3310. w3 = weight * w2;
  3311. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3312. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3313. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3314. return v3;
  3315. };
  3316. this.getControlPointsArray = function () {
  3317. var i, p, l = this.points.length,
  3318. coords = [];
  3319. for ( i = 0; i < l; i ++ ) {
  3320. p = this.points[ i ];
  3321. coords[ i ] = [ p.x, p.y, p.z ];
  3322. }
  3323. return coords;
  3324. };
  3325. // approximate length by summing linear segments
  3326. this.getLength = function ( nSubDivisions ) {
  3327. var i, index, nSamples, position,
  3328. point = 0, intPoint = 0, oldIntPoint = 0,
  3329. oldPosition = new THREE.Vector3(),
  3330. tmpVec = new THREE.Vector3(),
  3331. chunkLengths = [],
  3332. totalLength = 0;
  3333. // first point has 0 length
  3334. chunkLengths[ 0 ] = 0;
  3335. if ( !nSubDivisions ) nSubDivisions = 100;
  3336. nSamples = this.points.length * nSubDivisions;
  3337. oldPosition.copy( this.points[ 0 ] );
  3338. for ( i = 1; i < nSamples; i ++ ) {
  3339. index = i / nSamples;
  3340. position = this.getPoint( index );
  3341. tmpVec.copy( position );
  3342. totalLength += tmpVec.distanceTo( oldPosition );
  3343. oldPosition.copy( position );
  3344. point = ( this.points.length - 1 ) * index;
  3345. intPoint = Math.floor( point );
  3346. if ( intPoint != oldIntPoint ) {
  3347. chunkLengths[ intPoint ] = totalLength;
  3348. oldIntPoint = intPoint;
  3349. }
  3350. }
  3351. // last point ends with total length
  3352. chunkLengths[ chunkLengths.length ] = totalLength;
  3353. return { chunks: chunkLengths, total: totalLength };
  3354. };
  3355. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3356. var i, j,
  3357. index, indexCurrent, indexNext,
  3358. linearDistance, realDistance,
  3359. sampling, position,
  3360. newpoints = [],
  3361. tmpVec = new THREE.Vector3(),
  3362. sl = this.getLength();
  3363. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3364. for ( i = 1; i < this.points.length; i++ ) {
  3365. //tmpVec.copy( this.points[ i - 1 ] );
  3366. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3367. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3368. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3369. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3370. indexNext = i / ( this.points.length - 1 );
  3371. for ( j = 1; j < sampling - 1; j++ ) {
  3372. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3373. position = this.getPoint( index );
  3374. newpoints.push( tmpVec.copy( position ).clone() );
  3375. }
  3376. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3377. }
  3378. this.points = newpoints;
  3379. };
  3380. // Catmull-Rom
  3381. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3382. var v0 = ( p2 - p0 ) * 0.5,
  3383. v1 = ( p3 - p1 ) * 0.5;
  3384. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3385. };
  3386. };
  3387. /**
  3388. * @author bhouston / http://exocortex.com
  3389. * @author mrdoob / http://mrdoob.com/
  3390. */
  3391. THREE.Triangle = function ( a, b, c ) {
  3392. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3393. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3394. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3395. };
  3396. THREE.Triangle.normal = function() {
  3397. var v0 = new THREE.Vector3();
  3398. return function ( a, b, c, optionalTarget ) {
  3399. var result = optionalTarget || new THREE.Vector3();
  3400. result.subVectors( c, b );
  3401. v0.subVectors( a, b );
  3402. result.cross( v0 );
  3403. var resultLengthSq = result.lengthSq();
  3404. if( resultLengthSq > 0 ) {
  3405. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3406. }
  3407. return result.set( 0, 0, 0 );
  3408. };
  3409. }();
  3410. // static/instance method to calculate barycoordinates
  3411. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3412. THREE.Triangle.barycoordFromPoint = function() {
  3413. var v0 = new THREE.Vector3();
  3414. var v1 = new THREE.Vector3();
  3415. var v2 = new THREE.Vector3();
  3416. return function ( point, a, b, c, optionalTarget ) {
  3417. v0.subVectors( c, a );
  3418. v1.subVectors( b, a );
  3419. v2.subVectors( point, a );
  3420. var dot00 = v0.dot( v0 );
  3421. var dot01 = v0.dot( v1 );
  3422. var dot02 = v0.dot( v2 );
  3423. var dot11 = v1.dot( v1 );
  3424. var dot12 = v1.dot( v2 );
  3425. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3426. var result = optionalTarget || new THREE.Vector3();
  3427. // colinear or singular triangle
  3428. if( denom == 0 ) {
  3429. // arbitrary location outside of triangle?
  3430. // not sure if this is the best idea, maybe should be returning undefined
  3431. return result.set( -2, -1, -1 );
  3432. }
  3433. var invDenom = 1 / denom;
  3434. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3435. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3436. // barycoordinates must always sum to 1
  3437. return result.set( 1 - u - v, v, u );
  3438. };
  3439. }();
  3440. THREE.Triangle.containsPoint = function() {
  3441. var v1 = new THREE.Vector3();
  3442. return function ( point, a, b, c ) {
  3443. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3444. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3445. };
  3446. }();
  3447. THREE.Triangle.prototype = {
  3448. constructor: THREE.Triangle,
  3449. set: function ( a, b, c ) {
  3450. this.a.copy( a );
  3451. this.b.copy( b );
  3452. this.c.copy( c );
  3453. return this;
  3454. },
  3455. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3456. this.a.copy( points[i0] );
  3457. this.b.copy( points[i1] );
  3458. this.c.copy( points[i2] );
  3459. return this;
  3460. },
  3461. copy: function ( triangle ) {
  3462. this.a.copy( triangle.a );
  3463. this.b.copy( triangle.b );
  3464. this.c.copy( triangle.c );
  3465. return this;
  3466. },
  3467. area: function() {
  3468. var v0 = new THREE.Vector3();
  3469. var v1 = new THREE.Vector3();
  3470. return function () {
  3471. v0.subVectors( this.c, this.b );
  3472. v1.subVectors( this.a, this.b );
  3473. return v0.cross( v1 ).length() * 0.5;
  3474. };
  3475. }(),
  3476. midpoint: function ( optionalTarget ) {
  3477. var result = optionalTarget || new THREE.Vector3();
  3478. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3479. },
  3480. normal: function ( optionalTarget ) {
  3481. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3482. },
  3483. plane: function ( optionalTarget ) {
  3484. var result = optionalTarget || new THREE.Plane();
  3485. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3486. },
  3487. barycoordFromPoint: function ( point, optionalTarget ) {
  3488. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3489. },
  3490. containsPoint: function ( point ) {
  3491. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3492. },
  3493. equals: function ( triangle ) {
  3494. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3495. },
  3496. clone: function () {
  3497. return new THREE.Triangle().copy( this );
  3498. }
  3499. };
  3500. /**
  3501. * @author mrdoob / http://mrdoob.com/
  3502. */
  3503. THREE.Vertex = function ( v ) {
  3504. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3505. return v;
  3506. };
  3507. /**
  3508. * @author mrdoob / http://mrdoob.com/
  3509. */
  3510. THREE.UV = function ( u, v ) {
  3511. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3512. return new THREE.Vector2( u, v );
  3513. };
  3514. /**
  3515. * @author alteredq / http://alteredqualia.com/
  3516. */
  3517. THREE.Clock = function ( autoStart ) {
  3518. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3519. this.startTime = 0;
  3520. this.oldTime = 0;
  3521. this.elapsedTime = 0;
  3522. this.running = false;
  3523. };
  3524. THREE.Clock.prototype = {
  3525. constructor: THREE.Clock,
  3526. start: function () {
  3527. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3528. ? self.performance.now()
  3529. : Date.now();
  3530. this.oldTime = this.startTime;
  3531. this.running = true;
  3532. },
  3533. stop: function () {
  3534. this.getElapsedTime();
  3535. this.running = false;
  3536. },
  3537. getElapsedTime: function () {
  3538. this.getDelta();
  3539. return this.elapsedTime;
  3540. },
  3541. getDelta: function () {
  3542. var diff = 0;
  3543. if ( this.autoStart && ! this.running ) {
  3544. this.start();
  3545. }
  3546. if ( this.running ) {
  3547. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3548. ? self.performance.now()
  3549. : Date.now();
  3550. diff = 0.001 * ( newTime - this.oldTime );
  3551. this.oldTime = newTime;
  3552. this.elapsedTime += diff;
  3553. }
  3554. return diff;
  3555. }
  3556. };
  3557. /**
  3558. * https://github.com/mrdoob/eventdispatcher.js/
  3559. */
  3560. THREE.EventDispatcher = function () {}
  3561. THREE.EventDispatcher.prototype = {
  3562. constructor: THREE.EventDispatcher,
  3563. addEventListener: function ( type, listener ) {
  3564. if ( this._listeners === undefined ) this._listeners = {};
  3565. var listeners = this._listeners;
  3566. if ( listeners[ type ] === undefined ) {
  3567. listeners[ type ] = [];
  3568. }
  3569. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3570. listeners[ type ].push( listener );
  3571. }
  3572. },
  3573. hasEventListener: function ( type, listener ) {
  3574. if ( this._listeners === undefined ) return false;
  3575. var listeners = this._listeners;
  3576. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3577. return true;
  3578. }
  3579. return false;
  3580. },
  3581. removeEventListener: function ( type, listener ) {
  3582. if ( this._listeners === undefined ) return;
  3583. var listeners = this._listeners;
  3584. var index = listeners[ type ].indexOf( listener );
  3585. if ( index !== - 1 ) {
  3586. listeners[ type ].splice( index, 1 );
  3587. }
  3588. },
  3589. dispatchEvent: function ( event ) {
  3590. if ( this._listeners === undefined ) return;
  3591. var listeners = this._listeners;
  3592. var listenerArray = listeners[ event.type ];
  3593. if ( listenerArray !== undefined ) {
  3594. event.target = this;
  3595. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3596. listenerArray[ i ].call( this, event );
  3597. }
  3598. }
  3599. }
  3600. };
  3601. /**
  3602. * @author mrdoob / http://mrdoob.com/
  3603. * @author bhouston / http://exocortex.com/
  3604. */
  3605. ( function ( THREE ) {
  3606. THREE.Raycaster = function ( origin, direction, near, far ) {
  3607. this.ray = new THREE.Ray( origin, direction );
  3608. // normalized ray.direction required for accurate distance calculations
  3609. if ( this.ray.direction.lengthSq() > 0 ) {
  3610. this.ray.direction.normalize();
  3611. }
  3612. this.near = near || 0;
  3613. this.far = far || Infinity;
  3614. };
  3615. var sphere = new THREE.Sphere();
  3616. var localRay = new THREE.Ray();
  3617. var facePlane = new THREE.Plane();
  3618. var intersectPoint = new THREE.Vector3();
  3619. var matrixPosition = new THREE.Vector3();
  3620. var inverseMatrix = new THREE.Matrix4();
  3621. var descSort = function ( a, b ) {
  3622. return a.distance - b.distance;
  3623. };
  3624. var intersectObject = function ( object, raycaster, intersects ) {
  3625. if ( object instanceof THREE.Particle ) {
  3626. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3627. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3628. if ( distance > object.scale.x ) {
  3629. return intersects;
  3630. }
  3631. intersects.push( {
  3632. distance: distance,
  3633. point: object.position,
  3634. face: null,
  3635. object: object
  3636. } );
  3637. } else if ( object instanceof THREE.LOD ) {
  3638. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3639. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  3640. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  3641. } else if (object instanceof THREE.Mesh ) {
  3642. // Checking boundingSphere distance to ray
  3643. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3644. sphere.set( matrixPosition, object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3645. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  3646. return intersects;
  3647. }
  3648. var geometry = object.geometry;
  3649. var vertices = geometry.vertices;
  3650. if ( geometry instanceof THREE.BufferGeometry ) {
  3651. var material = object.material;
  3652. if ( material === undefined ) return intersects;
  3653. if ( ! geometry.dynamic ) return intersects;
  3654. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3655. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3656. var side = object.material.side;
  3657. var a, b, c;
  3658. var precision = raycaster.precision;
  3659. inverseMatrix.getInverse( object.matrixWorld );
  3660. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3661. var fl;
  3662. var indexed = false;
  3663. if ( geometry.attributes.index ) {
  3664. indexed = true;
  3665. fl = geometry.attributes.index.numItems / 3;
  3666. } else {
  3667. fl = geometry.attributes.position.numItems / 9;
  3668. }
  3669. var vA = new THREE.Vector3();
  3670. var vB = new THREE.Vector3();
  3671. var vC = new THREE.Vector3();
  3672. var vCB = new THREE.Vector3();
  3673. var vAB = new THREE.Vector3();
  3674. for ( var oi = 0; oi < geometry.offsets.length; ++oi ) {
  3675. var start = geometry.offsets[ oi ].start;
  3676. var count = geometry.offsets[ oi ].count;
  3677. var index = geometry.offsets[ oi ].index;
  3678. for ( var i = start, il = start + count; i < il; i += 3 ) {
  3679. if ( indexed ) {
  3680. a = index + geometry.attributes.index.array[ i ];
  3681. b = index + geometry.attributes.index.array[ i + 1 ];
  3682. c = index + geometry.attributes.index.array[ i + 2 ];
  3683. } else {
  3684. a = index;
  3685. b = index + 1;
  3686. c = index + 2;
  3687. }
  3688. vA.set( geometry.attributes.position.array[ a * 3 ],
  3689. geometry.attributes.position.array[ a * 3 + 1 ],
  3690. geometry.attributes.position.array[ a * 3 + 2] );
  3691. vB.set( geometry.attributes.position.array[ b * 3 ],
  3692. geometry.attributes.position.array[ b * 3 + 1 ],
  3693. geometry.attributes.position.array[ b * 3 + 2] );
  3694. vC.set( geometry.attributes.position.array[ c * 3 ],
  3695. geometry.attributes.position.array[ c * 3 + 1 ],
  3696. geometry.attributes.position.array[ c * 3 + 2 ] );
  3697. facePlane.setFromCoplanarPoints( vA, vB, vC );
  3698. var planeDistance = localRay.distanceToPlane( facePlane );
  3699. // bail if raycaster and plane are parallel
  3700. if ( Math.abs( planeDistance ) < precision ) continue;
  3701. // if negative distance, then plane is behind raycaster
  3702. if ( planeDistance < 0 ) continue;
  3703. // check if we hit the wrong side of a single sided face
  3704. side = material.side;
  3705. if ( side !== THREE.DoubleSide ) {
  3706. var planeSign = localRay.direction.dot( facePlane.normal );
  3707. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3708. }
  3709. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3710. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3711. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3712. if ( ! THREE.Triangle.containsPoint( intersectPoint, vA, vB, vC ) ) continue;
  3713. intersects.push( {
  3714. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3715. point: raycaster.ray.at(planeDistance),
  3716. face: null,
  3717. faceIndex: null,
  3718. object: object
  3719. } );
  3720. }
  3721. }
  3722. } else if ( geometry instanceof THREE.Geometry ) {
  3723. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3724. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3725. var side = object.material.side;
  3726. var a, b, c, d;
  3727. var precision = raycaster.precision;
  3728. inverseMatrix.getInverse( object.matrixWorld );
  3729. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3730. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3731. var face = geometry.faces[ f ];
  3732. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3733. if ( material === undefined ) continue;
  3734. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3735. var planeDistance = localRay.distanceToPlane( facePlane );
  3736. // bail if raycaster and plane are parallel
  3737. if ( Math.abs( planeDistance ) < precision ) continue;
  3738. // if negative distance, then plane is behind raycaster
  3739. if ( planeDistance < 0 ) continue;
  3740. // check if we hit the wrong side of a single sided face
  3741. side = material.side;
  3742. if ( side !== THREE.DoubleSide ) {
  3743. var planeSign = localRay.direction.dot( facePlane.normal );
  3744. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3745. }
  3746. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3747. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3748. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3749. if ( face instanceof THREE.Face3 ) {
  3750. a = vertices[ face.a ];
  3751. b = vertices[ face.b ];
  3752. c = vertices[ face.c ];
  3753. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3754. } else if ( face instanceof THREE.Face4 ) {
  3755. a = vertices[ face.a ];
  3756. b = vertices[ face.b ];
  3757. c = vertices[ face.c ];
  3758. d = vertices[ face.d ];
  3759. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3760. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3761. } else {
  3762. // This is added because if we call out of this if/else group when none of the cases
  3763. // match it will add a point to the intersection list erroneously.
  3764. throw Error( "face type not supported" );
  3765. }
  3766. intersects.push( {
  3767. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3768. point: raycaster.ray.at( planeDistance ),
  3769. face: face,
  3770. faceIndex: f,
  3771. object: object
  3772. } );
  3773. }
  3774. }
  3775. }
  3776. };
  3777. var intersectDescendants = function ( object, raycaster, intersects ) {
  3778. var descendants = object.getDescendants();
  3779. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3780. intersectObject( descendants[ i ], raycaster, intersects );
  3781. }
  3782. };
  3783. //
  3784. THREE.Raycaster.prototype.precision = 0.0001;
  3785. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3786. this.ray.set( origin, direction );
  3787. // normalized ray.direction required for accurate distance calculations
  3788. if ( this.ray.direction.length() > 0 ) {
  3789. this.ray.direction.normalize();
  3790. }
  3791. };
  3792. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3793. var intersects = [];
  3794. if ( recursive === true ) {
  3795. intersectDescendants( object, this, intersects );
  3796. }
  3797. intersectObject( object, this, intersects );
  3798. intersects.sort( descSort );
  3799. return intersects;
  3800. };
  3801. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3802. var intersects = [];
  3803. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3804. intersectObject( objects[ i ], this, intersects );
  3805. if ( recursive === true ) {
  3806. intersectDescendants( objects[ i ], this, intersects );
  3807. }
  3808. }
  3809. intersects.sort( descSort );
  3810. return intersects;
  3811. };
  3812. }( THREE ) );
  3813. /**
  3814. * @author mrdoob / http://mrdoob.com/
  3815. * @author mikael emtinger / http://gomo.se/
  3816. * @author alteredq / http://alteredqualia.com/
  3817. * @author WestLangley / http://github.com/WestLangley
  3818. */
  3819. THREE.Object3D = function () {
  3820. this.id = THREE.Math.generateUUID();
  3821. this.name = '';
  3822. this.parent = undefined;
  3823. this.children = [];
  3824. this.up = new THREE.Vector3( 0, 1, 0 );
  3825. this.position = new THREE.Vector3();
  3826. this.rotation = new THREE.Vector3();
  3827. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3828. this.scale = new THREE.Vector3( 1, 1, 1 );
  3829. this.renderDepth = null;
  3830. this.rotationAutoUpdate = true;
  3831. this.matrix = new THREE.Matrix4();
  3832. this.matrixWorld = new THREE.Matrix4();
  3833. this.matrixAutoUpdate = true;
  3834. this.matrixWorldNeedsUpdate = true;
  3835. this.quaternion = new THREE.Quaternion();
  3836. this.useQuaternion = false;
  3837. this.visible = true;
  3838. this.castShadow = false;
  3839. this.receiveShadow = false;
  3840. this.frustumCulled = true;
  3841. this.userData = {};
  3842. };
  3843. THREE.Object3D.prototype = {
  3844. constructor: THREE.Object3D,
  3845. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  3846. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  3847. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  3848. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  3849. applyMatrix: function () {
  3850. var m1 = new THREE.Matrix4();
  3851. return function ( matrix ) {
  3852. this.matrix.multiplyMatrices( matrix, this.matrix );
  3853. this.position.getPositionFromMatrix( this.matrix );
  3854. this.scale.getScaleFromMatrix( this.matrix );
  3855. m1.extractRotation( this.matrix );
  3856. if ( this.useQuaternion === true ) {
  3857. this.quaternion.setFromRotationMatrix( m1 );
  3858. } else {
  3859. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3860. }
  3861. }
  3862. }(),
  3863. rotateOnAxis: function() {
  3864. // rotate object on axis in object space
  3865. // axis is assumed to be normalized
  3866. var q1 = new THREE.Quaternion();
  3867. var q2 = new THREE.Quaternion();
  3868. return function ( axis, angle ) {
  3869. q1.setFromAxisAngle( axis, angle );
  3870. if ( this.useQuaternion === true ) {
  3871. this.quaternion.multiply( q1 );
  3872. } else {
  3873. q2.setFromEuler( this.rotation, this.eulerOrder );
  3874. q2.multiply( q1 );
  3875. this.rotation.setEulerFromQuaternion( q2, this.eulerOrder );
  3876. }
  3877. return this;
  3878. }
  3879. }(),
  3880. translateOnAxis: function () {
  3881. // translate object by distance along axis in object space
  3882. // axis is assumed to be normalized
  3883. var v1 = new THREE.Vector3();
  3884. return function ( axis, distance ) {
  3885. v1.copy( axis );
  3886. if ( this.useQuaternion === true ) {
  3887. v1.applyQuaternion( this.quaternion );
  3888. } else {
  3889. v1.applyEuler( this.rotation, this.eulerOrder );
  3890. }
  3891. this.position.add( v1.multiplyScalar( distance ) );
  3892. return this;
  3893. }
  3894. }(),
  3895. translate: function ( distance, axis ) {
  3896. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  3897. return this.translateOnAxis( axis, distance );
  3898. },
  3899. translateX: function () {
  3900. var v1 = new THREE.Vector3( 1, 0, 0 );
  3901. return function ( distance ) {
  3902. return this.translateOnAxis( v1, distance );
  3903. };
  3904. }(),
  3905. translateY: function () {
  3906. var v1 = new THREE.Vector3( 0, 1, 0 );
  3907. return function ( distance ) {
  3908. return this.translateOnAxis( v1, distance );
  3909. };
  3910. }(),
  3911. translateZ: function () {
  3912. var v1 = new THREE.Vector3( 0, 0, 1 );
  3913. return function ( distance ) {
  3914. return this.translateOnAxis( v1, distance );
  3915. };
  3916. }(),
  3917. localToWorld: function ( vector ) {
  3918. return vector.applyMatrix4( this.matrixWorld );
  3919. },
  3920. worldToLocal: function () {
  3921. var m1 = new THREE.Matrix4();
  3922. return function ( vector ) {
  3923. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  3924. };
  3925. }(),
  3926. lookAt: function () {
  3927. // This routine does not support objects with rotated and/or translated parent(s)
  3928. var m1 = new THREE.Matrix4();
  3929. return function ( vector ) {
  3930. m1.lookAt( vector, this.position, this.up );
  3931. if ( this.useQuaternion === true ) {
  3932. this.quaternion.setFromRotationMatrix( m1 );
  3933. } else {
  3934. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  3935. }
  3936. };
  3937. }(),
  3938. add: function ( object ) {
  3939. if ( object === this ) {
  3940. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3941. return;
  3942. }
  3943. if ( object instanceof THREE.Object3D ) {
  3944. if ( object.parent !== undefined ) {
  3945. object.parent.remove( object );
  3946. }
  3947. object.parent = this;
  3948. this.children.push( object );
  3949. // add to scene
  3950. var scene = this;
  3951. while ( scene.parent !== undefined ) {
  3952. scene = scene.parent;
  3953. }
  3954. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3955. scene.__addObject( object );
  3956. }
  3957. }
  3958. },
  3959. remove: function ( object ) {
  3960. var index = this.children.indexOf( object );
  3961. if ( index !== - 1 ) {
  3962. object.parent = undefined;
  3963. this.children.splice( index, 1 );
  3964. // remove from scene
  3965. var scene = this;
  3966. while ( scene.parent !== undefined ) {
  3967. scene = scene.parent;
  3968. }
  3969. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3970. scene.__removeObject( object );
  3971. }
  3972. }
  3973. },
  3974. traverse: function ( callback ) {
  3975. callback( this );
  3976. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3977. this.children[ i ].traverse( callback );
  3978. }
  3979. },
  3980. getObjectById: function ( id, recursive ) {
  3981. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3982. var child = this.children[ i ];
  3983. if ( child.id === id ) {
  3984. return child;
  3985. }
  3986. if ( recursive === true ) {
  3987. child = child.getObjectById( id, recursive );
  3988. if ( child !== undefined ) {
  3989. return child;
  3990. }
  3991. }
  3992. }
  3993. return undefined;
  3994. },
  3995. getObjectByName: function ( name, recursive ) {
  3996. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3997. var child = this.children[ i ];
  3998. if ( child.name === name ) {
  3999. return child;
  4000. }
  4001. if ( recursive === true ) {
  4002. child = child.getObjectByName( name, recursive );
  4003. if ( child !== undefined ) {
  4004. return child;
  4005. }
  4006. }
  4007. }
  4008. return undefined;
  4009. },
  4010. getChildByName: function ( name, recursive ) {
  4011. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4012. return this.getObjectByName( name, recursive );
  4013. },
  4014. getDescendants: function ( array ) {
  4015. if ( array === undefined ) array = [];
  4016. Array.prototype.push.apply( array, this.children );
  4017. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4018. this.children[ i ].getDescendants( array );
  4019. }
  4020. return array;
  4021. },
  4022. updateMatrix: function () {
  4023. // if we are not using a quaternion directly, convert Euler rotation to this.quaternion.
  4024. if ( this.useQuaternion === false ) {
  4025. this.matrix.makeFromPositionEulerScale( this.position, this.rotation, this.eulerOrder, this.scale );
  4026. } else {
  4027. this.matrix.makeFromPositionQuaternionScale( this.position, this.quaternion, this.scale );
  4028. }
  4029. this.matrixWorldNeedsUpdate = true;
  4030. },
  4031. updateMatrixWorld: function ( force ) {
  4032. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4033. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4034. if ( this.parent === undefined ) {
  4035. this.matrixWorld.copy( this.matrix );
  4036. } else {
  4037. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4038. }
  4039. this.matrixWorldNeedsUpdate = false;
  4040. force = true;
  4041. }
  4042. // update children
  4043. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4044. this.children[ i ].updateMatrixWorld( force );
  4045. }
  4046. },
  4047. clone: function ( object, recursive ) {
  4048. if ( object === undefined ) object = new THREE.Object3D();
  4049. if ( recursive === undefined ) recursive = true;
  4050. object.name = this.name;
  4051. object.up.copy( this.up );
  4052. object.position.copy( this.position );
  4053. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  4054. object.eulerOrder = this.eulerOrder;
  4055. object.scale.copy( this.scale );
  4056. object.renderDepth = this.renderDepth;
  4057. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4058. object.matrix.copy( this.matrix );
  4059. object.matrixWorld.copy( this.matrixWorld );
  4060. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4061. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4062. object.quaternion.copy( this.quaternion );
  4063. object.useQuaternion = this.useQuaternion;
  4064. object.visible = this.visible;
  4065. object.castShadow = this.castShadow;
  4066. object.receiveShadow = this.receiveShadow;
  4067. object.frustumCulled = this.frustumCulled;
  4068. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4069. if ( recursive === true ) {
  4070. for ( var i = 0; i < this.children.length; i ++ ) {
  4071. var child = this.children[ i ];
  4072. object.add( child.clone() );
  4073. }
  4074. }
  4075. return object;
  4076. }
  4077. };
  4078. THREE.Object3D.defaultEulerOrder = 'XYZ';
  4079. /**
  4080. * @author mrdoob / http://mrdoob.com/
  4081. * @author supereggbert / http://www.paulbrunt.co.uk/
  4082. * @author julianwa / https://github.com/julianwa
  4083. */
  4084. THREE.Projector = function () {
  4085. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4086. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4087. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4088. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  4089. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4090. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  4091. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4092. _vector3 = new THREE.Vector3(),
  4093. _vector4 = new THREE.Vector4(),
  4094. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4095. _boundingBox = new THREE.Box3(),
  4096. _points3 = new Array( 3 ),
  4097. _points4 = new Array( 4 ),
  4098. _viewMatrix = new THREE.Matrix4(),
  4099. _viewProjectionMatrix = new THREE.Matrix4(),
  4100. _modelMatrix,
  4101. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4102. _normalMatrix = new THREE.Matrix3(),
  4103. _normalViewMatrix = new THREE.Matrix3(),
  4104. _centroid = new THREE.Vector3(),
  4105. _frustum = new THREE.Frustum(),
  4106. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4107. _clippedVertex2PositionScreen = new THREE.Vector4();
  4108. this.projectVector = function ( vector, camera ) {
  4109. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4110. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4111. return vector.applyProjection( _viewProjectionMatrix );
  4112. };
  4113. this.unprojectVector = function ( vector, camera ) {
  4114. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4115. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4116. return vector.applyProjection( _viewProjectionMatrix );
  4117. };
  4118. this.pickingRay = function ( vector, camera ) {
  4119. // set two vectors with opposing z values
  4120. vector.z = -1.0;
  4121. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4122. this.unprojectVector( vector, camera );
  4123. this.unprojectVector( end, camera );
  4124. // find direction from vector to end
  4125. end.sub( vector ).normalize();
  4126. return new THREE.Raycaster( vector, end );
  4127. };
  4128. var getObject = function ( object ) {
  4129. _object = getNextObjectInPool();
  4130. _object.object = object;
  4131. if ( object.renderDepth !== null ) {
  4132. _object.z = object.renderDepth;
  4133. } else {
  4134. _vector3.getPositionFromMatrix( object.matrixWorld );
  4135. _vector3.applyProjection( _viewProjectionMatrix );
  4136. _object.z = _vector3.z;
  4137. }
  4138. return _object;
  4139. };
  4140. var projectObject = function ( object ) {
  4141. if ( object.visible === false ) return;
  4142. if ( object instanceof THREE.Light ) {
  4143. _renderData.lights.push( object );
  4144. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4145. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4146. _renderData.objects.push( getObject( object ) );
  4147. }
  4148. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  4149. _renderData.sprites.push( getObject( object ) );
  4150. }
  4151. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4152. projectObject( object.children[ i ] );
  4153. }
  4154. };
  4155. var projectGraph = function ( root, sortObjects ) {
  4156. _objectCount = 0;
  4157. _renderData.objects.length = 0;
  4158. _renderData.sprites.length = 0;
  4159. _renderData.lights.length = 0;
  4160. projectObject( root );
  4161. if ( sortObjects === true ) {
  4162. _renderData.objects.sort( painterSort );
  4163. }
  4164. };
  4165. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4166. var visible = false,
  4167. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4168. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4169. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4170. _face3Count = 0;
  4171. _face4Count = 0;
  4172. _lineCount = 0;
  4173. _particleCount = 0;
  4174. _renderData.elements.length = 0;
  4175. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4176. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4177. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4178. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4179. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4180. _frustum.setFromMatrix( _viewProjectionMatrix );
  4181. projectGraph( scene, sortObjects );
  4182. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4183. object = _renderData.objects[ o ].object;
  4184. _modelMatrix = object.matrixWorld;
  4185. _vertexCount = 0;
  4186. if ( object instanceof THREE.Mesh ) {
  4187. geometry = object.geometry;
  4188. vertices = geometry.vertices;
  4189. faces = geometry.faces;
  4190. faceVertexUvs = geometry.faceVertexUvs;
  4191. _normalMatrix.getNormalMatrix( _modelMatrix );
  4192. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4193. objectMaterials = isFaceMaterial === true ? object.material : null;
  4194. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4195. _vertex = getNextVertexInPool();
  4196. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4197. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4198. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4199. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4200. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4201. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4202. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4203. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4204. }
  4205. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4206. face = faces[ f ];
  4207. var material = isFaceMaterial === true
  4208. ? objectMaterials.materials[ face.materialIndex ]
  4209. : object.material;
  4210. if ( material === undefined ) continue;
  4211. var side = material.side;
  4212. if ( face instanceof THREE.Face3 ) {
  4213. v1 = _vertexPool[ face.a ];
  4214. v2 = _vertexPool[ face.b ];
  4215. v3 = _vertexPool[ face.c ];
  4216. _points3[ 0 ] = v1.positionScreen;
  4217. _points3[ 1 ] = v2.positionScreen;
  4218. _points3[ 2 ] = v3.positionScreen;
  4219. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4220. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4221. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4222. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4223. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4224. _face = getNextFace3InPool();
  4225. _face.v1.copy( v1 );
  4226. _face.v2.copy( v2 );
  4227. _face.v3.copy( v3 );
  4228. } else {
  4229. continue;
  4230. }
  4231. } else {
  4232. continue;
  4233. }
  4234. } else if ( face instanceof THREE.Face4 ) {
  4235. v1 = _vertexPool[ face.a ];
  4236. v2 = _vertexPool[ face.b ];
  4237. v3 = _vertexPool[ face.c ];
  4238. v4 = _vertexPool[ face.d ];
  4239. _points4[ 0 ] = v1.positionScreen;
  4240. _points4[ 1 ] = v2.positionScreen;
  4241. _points4[ 2 ] = v3.positionScreen;
  4242. _points4[ 3 ] = v4.positionScreen;
  4243. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4244. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4245. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4246. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4247. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4248. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4249. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4250. _face = getNextFace4InPool();
  4251. _face.v1.copy( v1 );
  4252. _face.v2.copy( v2 );
  4253. _face.v3.copy( v3 );
  4254. _face.v4.copy( v4 );
  4255. } else {
  4256. continue;
  4257. }
  4258. } else {
  4259. continue;
  4260. }
  4261. }
  4262. _face.normalModel.copy( face.normal );
  4263. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4264. _face.normalModel.negate();
  4265. }
  4266. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4267. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4268. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4269. faceVertexNormals = face.vertexNormals;
  4270. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4271. var normalModel = _face.vertexNormalsModel[ n ];
  4272. normalModel.copy( faceVertexNormals[ n ] );
  4273. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4274. normalModel.negate();
  4275. }
  4276. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4277. var normalModelView = _face.vertexNormalsModelView[ n ];
  4278. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4279. }
  4280. _face.vertexNormalsLength = faceVertexNormals.length;
  4281. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4282. uvs = faceVertexUvs[ c ][ f ];
  4283. if ( uvs === undefined ) continue;
  4284. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4285. _face.uvs[ c ][ u ] = uvs[ u ];
  4286. }
  4287. }
  4288. _face.color = face.color;
  4289. _face.material = material;
  4290. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4291. _face.z = _centroid.z;
  4292. _renderData.elements.push( _face );
  4293. }
  4294. } else if ( object instanceof THREE.Line ) {
  4295. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4296. vertices = object.geometry.vertices;
  4297. v1 = getNextVertexInPool();
  4298. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4299. // Handle LineStrip and LinePieces
  4300. var step = object.type === THREE.LinePieces ? 2 : 1;
  4301. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4302. v1 = getNextVertexInPool();
  4303. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4304. if ( ( v + 1 ) % step > 0 ) continue;
  4305. v2 = _vertexPool[ _vertexCount - 2 ];
  4306. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4307. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4308. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4309. // Perform the perspective divide
  4310. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4311. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4312. _line = getNextLineInPool();
  4313. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4314. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4315. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4316. _line.material = object.material;
  4317. if ( object.material.vertexColors === THREE.VertexColors ) {
  4318. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4319. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4320. }
  4321. _renderData.elements.push( _line );
  4322. }
  4323. }
  4324. }
  4325. }
  4326. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4327. object = _renderData.sprites[ o ].object;
  4328. _modelMatrix = object.matrixWorld;
  4329. if ( object instanceof THREE.Particle ) {
  4330. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4331. _vector4.applyMatrix4( _viewProjectionMatrix );
  4332. _vector4.z /= _vector4.w;
  4333. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4334. _particle = getNextParticleInPool();
  4335. _particle.object = object;
  4336. _particle.x = _vector4.x / _vector4.w;
  4337. _particle.y = _vector4.y / _vector4.w;
  4338. _particle.z = _vector4.z;
  4339. _particle.rotation = object.rotation.z;
  4340. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4341. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4342. _particle.material = object.material;
  4343. _renderData.elements.push( _particle );
  4344. }
  4345. }
  4346. }
  4347. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4348. return _renderData;
  4349. };
  4350. // Pools
  4351. function getNextObjectInPool() {
  4352. if ( _objectCount === _objectPoolLength ) {
  4353. var object = new THREE.RenderableObject();
  4354. _objectPool.push( object );
  4355. _objectPoolLength ++;
  4356. _objectCount ++;
  4357. return object;
  4358. }
  4359. return _objectPool[ _objectCount ++ ];
  4360. }
  4361. function getNextVertexInPool() {
  4362. if ( _vertexCount === _vertexPoolLength ) {
  4363. var vertex = new THREE.RenderableVertex();
  4364. _vertexPool.push( vertex );
  4365. _vertexPoolLength ++;
  4366. _vertexCount ++;
  4367. return vertex;
  4368. }
  4369. return _vertexPool[ _vertexCount ++ ];
  4370. }
  4371. function getNextFace3InPool() {
  4372. if ( _face3Count === _face3PoolLength ) {
  4373. var face = new THREE.RenderableFace3();
  4374. _face3Pool.push( face );
  4375. _face3PoolLength ++;
  4376. _face3Count ++;
  4377. return face;
  4378. }
  4379. return _face3Pool[ _face3Count ++ ];
  4380. }
  4381. function getNextFace4InPool() {
  4382. if ( _face4Count === _face4PoolLength ) {
  4383. var face = new THREE.RenderableFace4();
  4384. _face4Pool.push( face );
  4385. _face4PoolLength ++;
  4386. _face4Count ++;
  4387. return face;
  4388. }
  4389. return _face4Pool[ _face4Count ++ ];
  4390. }
  4391. function getNextLineInPool() {
  4392. if ( _lineCount === _linePoolLength ) {
  4393. var line = new THREE.RenderableLine();
  4394. _linePool.push( line );
  4395. _linePoolLength ++;
  4396. _lineCount ++
  4397. return line;
  4398. }
  4399. return _linePool[ _lineCount ++ ];
  4400. }
  4401. function getNextParticleInPool() {
  4402. if ( _particleCount === _particlePoolLength ) {
  4403. var particle = new THREE.RenderableParticle();
  4404. _particlePool.push( particle );
  4405. _particlePoolLength ++;
  4406. _particleCount ++
  4407. return particle;
  4408. }
  4409. return _particlePool[ _particleCount ++ ];
  4410. }
  4411. //
  4412. function painterSort( a, b ) {
  4413. return b.z - a.z;
  4414. }
  4415. function clipLine( s1, s2 ) {
  4416. var alpha1 = 0, alpha2 = 1,
  4417. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4418. // Z = -1 and Z = +1, respectively.
  4419. bc1near = s1.z + s1.w,
  4420. bc2near = s2.z + s2.w,
  4421. bc1far = - s1.z + s1.w,
  4422. bc2far = - s2.z + s2.w;
  4423. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4424. // Both vertices lie entirely within all clip planes.
  4425. return true;
  4426. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4427. // Both vertices lie entirely outside one of the clip planes.
  4428. return false;
  4429. } else {
  4430. // The line segment spans at least one clip plane.
  4431. if ( bc1near < 0 ) {
  4432. // v1 lies outside the near plane, v2 inside
  4433. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4434. } else if ( bc2near < 0 ) {
  4435. // v2 lies outside the near plane, v1 inside
  4436. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4437. }
  4438. if ( bc1far < 0 ) {
  4439. // v1 lies outside the far plane, v2 inside
  4440. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4441. } else if ( bc2far < 0 ) {
  4442. // v2 lies outside the far plane, v2 inside
  4443. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4444. }
  4445. if ( alpha2 < alpha1 ) {
  4446. // The line segment spans two boundaries, but is outside both of them.
  4447. // (This can't happen when we're only clipping against just near/far but good
  4448. // to leave the check here for future usage if other clip planes are added.)
  4449. return false;
  4450. } else {
  4451. // Update the s1 and s2 vertices to match the clipped line segment.
  4452. s1.lerp( s2, alpha1 );
  4453. s2.lerp( s1, 1 - alpha2 );
  4454. return true;
  4455. }
  4456. }
  4457. }
  4458. };
  4459. /**
  4460. * @author mrdoob / http://mrdoob.com/
  4461. * @author alteredq / http://alteredqualia.com/
  4462. */
  4463. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4464. this.a = a;
  4465. this.b = b;
  4466. this.c = c;
  4467. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4468. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4469. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4470. this.vertexColors = color instanceof Array ? color : [];
  4471. this.vertexTangents = [];
  4472. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4473. this.centroid = new THREE.Vector3();
  4474. };
  4475. THREE.Face3.prototype = {
  4476. constructor: THREE.Face3,
  4477. clone: function () {
  4478. var face = new THREE.Face3( this.a, this.b, this.c );
  4479. face.normal.copy( this.normal );
  4480. face.color.copy( this.color );
  4481. face.centroid.copy( this.centroid );
  4482. face.materialIndex = this.materialIndex;
  4483. var i, il;
  4484. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4485. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4486. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4487. return face;
  4488. }
  4489. };
  4490. /**
  4491. * @author mrdoob / http://mrdoob.com/
  4492. * @author alteredq / http://alteredqualia.com/
  4493. */
  4494. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4495. this.a = a;
  4496. this.b = b;
  4497. this.c = c;
  4498. this.d = d;
  4499. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4500. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4501. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4502. this.vertexColors = color instanceof Array ? color : [];
  4503. this.vertexTangents = [];
  4504. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4505. this.centroid = new THREE.Vector3();
  4506. };
  4507. THREE.Face4.prototype = {
  4508. constructor: THREE.Face4,
  4509. clone: function () {
  4510. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4511. face.normal.copy( this.normal );
  4512. face.color.copy( this.color );
  4513. face.centroid.copy( this.centroid );
  4514. face.materialIndex = this.materialIndex;
  4515. var i, il;
  4516. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4517. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4518. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4519. return face;
  4520. }
  4521. };
  4522. /**
  4523. * @author mrdoob / http://mrdoob.com/
  4524. * @author kile / http://kile.stravaganza.org/
  4525. * @author alteredq / http://alteredqualia.com/
  4526. * @author mikael emtinger / http://gomo.se/
  4527. * @author zz85 / http://www.lab4games.net/zz85/blog
  4528. * @author bhouston / http://exocortex.com
  4529. */
  4530. THREE.Geometry = function () {
  4531. this.id = THREE.Math.generateUUID();
  4532. this.name = '';
  4533. this.vertices = [];
  4534. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4535. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4536. this.faces = [];
  4537. this.faceUvs = [[]];
  4538. this.faceVertexUvs = [[]];
  4539. this.morphTargets = [];
  4540. this.morphColors = [];
  4541. this.morphNormals = [];
  4542. this.skinWeights = [];
  4543. this.skinIndices = [];
  4544. this.lineDistances = [];
  4545. this.boundingBox = null;
  4546. this.boundingSphere = null;
  4547. this.hasTangents = false;
  4548. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4549. // update flags
  4550. this.verticesNeedUpdate = false;
  4551. this.elementsNeedUpdate = false;
  4552. this.uvsNeedUpdate = false;
  4553. this.normalsNeedUpdate = false;
  4554. this.tangentsNeedUpdate = false;
  4555. this.colorsNeedUpdate = false;
  4556. this.lineDistancesNeedUpdate = false;
  4557. this.buffersNeedUpdate = false;
  4558. };
  4559. THREE.Geometry.prototype = {
  4560. constructor: THREE.Geometry,
  4561. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4562. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4563. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4564. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4565. applyMatrix: function ( matrix ) {
  4566. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4567. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4568. var vertex = this.vertices[ i ];
  4569. vertex.applyMatrix4( matrix );
  4570. }
  4571. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4572. var face = this.faces[ i ];
  4573. face.normal.applyMatrix3( normalMatrix ).normalize();
  4574. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4575. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4576. }
  4577. face.centroid.applyMatrix4( matrix );
  4578. }
  4579. if ( this.boundingBox instanceof THREE.Box3 ) {
  4580. this.computeBoundingBox();
  4581. }
  4582. if ( this.boundingSphere instanceof THREE.Sphere ) {
  4583. this.computeBoundingSphere();
  4584. }
  4585. },
  4586. computeCentroids: function () {
  4587. var f, fl, face;
  4588. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4589. face = this.faces[ f ];
  4590. face.centroid.set( 0, 0, 0 );
  4591. if ( face instanceof THREE.Face3 ) {
  4592. face.centroid.add( this.vertices[ face.a ] );
  4593. face.centroid.add( this.vertices[ face.b ] );
  4594. face.centroid.add( this.vertices[ face.c ] );
  4595. face.centroid.divideScalar( 3 );
  4596. } else if ( face instanceof THREE.Face4 ) {
  4597. face.centroid.add( this.vertices[ face.a ] );
  4598. face.centroid.add( this.vertices[ face.b ] );
  4599. face.centroid.add( this.vertices[ face.c ] );
  4600. face.centroid.add( this.vertices[ face.d ] );
  4601. face.centroid.divideScalar( 4 );
  4602. }
  4603. }
  4604. },
  4605. computeFaceNormals: function () {
  4606. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4607. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4608. var face = this.faces[ f ];
  4609. var vA = this.vertices[ face.a ];
  4610. var vB = this.vertices[ face.b ];
  4611. var vC = this.vertices[ face.c ];
  4612. cb.subVectors( vC, vB );
  4613. ab.subVectors( vA, vB );
  4614. cb.cross( ab );
  4615. cb.normalize();
  4616. face.normal.copy( cb );
  4617. }
  4618. },
  4619. computeVertexNormals: function ( areaWeighted ) {
  4620. var v, vl, f, fl, face, vertices;
  4621. // create internal buffers for reuse when calling this method repeatedly
  4622. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4623. if ( this.__tmpVertices === undefined ) {
  4624. this.__tmpVertices = new Array( this.vertices.length );
  4625. vertices = this.__tmpVertices;
  4626. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4627. vertices[ v ] = new THREE.Vector3();
  4628. }
  4629. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4630. face = this.faces[ f ];
  4631. if ( face instanceof THREE.Face3 ) {
  4632. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4633. } else if ( face instanceof THREE.Face4 ) {
  4634. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4635. }
  4636. }
  4637. } else {
  4638. vertices = this.__tmpVertices;
  4639. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4640. vertices[ v ].set( 0, 0, 0 );
  4641. }
  4642. }
  4643. if ( areaWeighted ) {
  4644. // vertex normals weighted by triangle areas
  4645. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4646. var vA, vB, vC, vD;
  4647. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4648. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4649. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4650. face = this.faces[ f ];
  4651. if ( face instanceof THREE.Face3 ) {
  4652. vA = this.vertices[ face.a ];
  4653. vB = this.vertices[ face.b ];
  4654. vC = this.vertices[ face.c ];
  4655. cb.subVectors( vC, vB );
  4656. ab.subVectors( vA, vB );
  4657. cb.cross( ab );
  4658. vertices[ face.a ].add( cb );
  4659. vertices[ face.b ].add( cb );
  4660. vertices[ face.c ].add( cb );
  4661. } else if ( face instanceof THREE.Face4 ) {
  4662. vA = this.vertices[ face.a ];
  4663. vB = this.vertices[ face.b ];
  4664. vC = this.vertices[ face.c ];
  4665. vD = this.vertices[ face.d ];
  4666. // abd
  4667. db.subVectors( vD, vB );
  4668. ab.subVectors( vA, vB );
  4669. db.cross( ab );
  4670. vertices[ face.a ].add( db );
  4671. vertices[ face.b ].add( db );
  4672. vertices[ face.d ].add( db );
  4673. // bcd
  4674. dc.subVectors( vD, vC );
  4675. bc.subVectors( vB, vC );
  4676. dc.cross( bc );
  4677. vertices[ face.b ].add( dc );
  4678. vertices[ face.c ].add( dc );
  4679. vertices[ face.d ].add( dc );
  4680. }
  4681. }
  4682. } else {
  4683. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4684. face = this.faces[ f ];
  4685. if ( face instanceof THREE.Face3 ) {
  4686. vertices[ face.a ].add( face.normal );
  4687. vertices[ face.b ].add( face.normal );
  4688. vertices[ face.c ].add( face.normal );
  4689. } else if ( face instanceof THREE.Face4 ) {
  4690. vertices[ face.a ].add( face.normal );
  4691. vertices[ face.b ].add( face.normal );
  4692. vertices[ face.c ].add( face.normal );
  4693. vertices[ face.d ].add( face.normal );
  4694. }
  4695. }
  4696. }
  4697. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4698. vertices[ v ].normalize();
  4699. }
  4700. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4701. face = this.faces[ f ];
  4702. if ( face instanceof THREE.Face3 ) {
  4703. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4704. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4705. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4706. } else if ( face instanceof THREE.Face4 ) {
  4707. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4708. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4709. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4710. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4711. }
  4712. }
  4713. },
  4714. computeMorphNormals: function () {
  4715. var i, il, f, fl, face;
  4716. // save original normals
  4717. // - create temp variables on first access
  4718. // otherwise just copy (for faster repeated calls)
  4719. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4720. face = this.faces[ f ];
  4721. if ( ! face.__originalFaceNormal ) {
  4722. face.__originalFaceNormal = face.normal.clone();
  4723. } else {
  4724. face.__originalFaceNormal.copy( face.normal );
  4725. }
  4726. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4727. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4728. if ( ! face.__originalVertexNormals[ i ] ) {
  4729. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4730. } else {
  4731. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4732. }
  4733. }
  4734. }
  4735. // use temp geometry to compute face and vertex normals for each morph
  4736. var tmpGeo = new THREE.Geometry();
  4737. tmpGeo.faces = this.faces;
  4738. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4739. // create on first access
  4740. if ( ! this.morphNormals[ i ] ) {
  4741. this.morphNormals[ i ] = {};
  4742. this.morphNormals[ i ].faceNormals = [];
  4743. this.morphNormals[ i ].vertexNormals = [];
  4744. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4745. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4746. var faceNormal, vertexNormals;
  4747. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4748. face = this.faces[ f ];
  4749. faceNormal = new THREE.Vector3();
  4750. if ( face instanceof THREE.Face3 ) {
  4751. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4752. } else {
  4753. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4754. }
  4755. dstNormalsFace.push( faceNormal );
  4756. dstNormalsVertex.push( vertexNormals );
  4757. }
  4758. }
  4759. var morphNormals = this.morphNormals[ i ];
  4760. // set vertices to morph target
  4761. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4762. // compute morph normals
  4763. tmpGeo.computeFaceNormals();
  4764. tmpGeo.computeVertexNormals();
  4765. // store morph normals
  4766. var faceNormal, vertexNormals;
  4767. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4768. face = this.faces[ f ];
  4769. faceNormal = morphNormals.faceNormals[ f ];
  4770. vertexNormals = morphNormals.vertexNormals[ f ];
  4771. faceNormal.copy( face.normal );
  4772. if ( face instanceof THREE.Face3 ) {
  4773. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4774. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4775. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4776. } else {
  4777. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4778. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4779. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4780. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4781. }
  4782. }
  4783. }
  4784. // restore original normals
  4785. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4786. face = this.faces[ f ];
  4787. face.normal = face.__originalFaceNormal;
  4788. face.vertexNormals = face.__originalVertexNormals;
  4789. }
  4790. },
  4791. computeTangents: function () {
  4792. // based on http://www.terathon.com/code/tangent.html
  4793. // tangents go to vertices
  4794. var f, fl, v, vl, i, il, vertexIndex,
  4795. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4796. x1, x2, y1, y2, z1, z2,
  4797. s1, s2, t1, t2, r, t, test,
  4798. tan1 = [], tan2 = [],
  4799. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4800. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4801. n = new THREE.Vector3(), w;
  4802. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4803. tan1[ v ] = new THREE.Vector3();
  4804. tan2[ v ] = new THREE.Vector3();
  4805. }
  4806. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4807. vA = context.vertices[ a ];
  4808. vB = context.vertices[ b ];
  4809. vC = context.vertices[ c ];
  4810. uvA = uv[ ua ];
  4811. uvB = uv[ ub ];
  4812. uvC = uv[ uc ];
  4813. x1 = vB.x - vA.x;
  4814. x2 = vC.x - vA.x;
  4815. y1 = vB.y - vA.y;
  4816. y2 = vC.y - vA.y;
  4817. z1 = vB.z - vA.z;
  4818. z2 = vC.z - vA.z;
  4819. s1 = uvB.x - uvA.x;
  4820. s2 = uvC.x - uvA.x;
  4821. t1 = uvB.y - uvA.y;
  4822. t2 = uvC.y - uvA.y;
  4823. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4824. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4825. ( t2 * y1 - t1 * y2 ) * r,
  4826. ( t2 * z1 - t1 * z2 ) * r );
  4827. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4828. ( s1 * y2 - s2 * y1 ) * r,
  4829. ( s1 * z2 - s2 * z1 ) * r );
  4830. tan1[ a ].add( sdir );
  4831. tan1[ b ].add( sdir );
  4832. tan1[ c ].add( sdir );
  4833. tan2[ a ].add( tdir );
  4834. tan2[ b ].add( tdir );
  4835. tan2[ c ].add( tdir );
  4836. }
  4837. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4838. face = this.faces[ f ];
  4839. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4840. if ( face instanceof THREE.Face3 ) {
  4841. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4842. } else if ( face instanceof THREE.Face4 ) {
  4843. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4844. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4845. }
  4846. }
  4847. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4848. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4849. face = this.faces[ f ];
  4850. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4851. n.copy( face.vertexNormals[ i ] );
  4852. vertexIndex = face[ faceIndex[ i ] ];
  4853. t = tan1[ vertexIndex ];
  4854. // Gram-Schmidt orthogonalize
  4855. tmp.copy( t );
  4856. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4857. // Calculate handedness
  4858. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4859. test = tmp2.dot( tan2[ vertexIndex ] );
  4860. w = (test < 0.0) ? -1.0 : 1.0;
  4861. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4862. }
  4863. }
  4864. this.hasTangents = true;
  4865. },
  4866. computeLineDistances: function ( ) {
  4867. var d = 0;
  4868. var vertices = this.vertices;
  4869. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4870. if ( i > 0 ) {
  4871. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4872. }
  4873. this.lineDistances[ i ] = d;
  4874. }
  4875. },
  4876. computeBoundingBox: function () {
  4877. if ( this.boundingBox === null ) {
  4878. this.boundingBox = new THREE.Box3();
  4879. }
  4880. this.boundingBox.setFromPoints( this.vertices );
  4881. },
  4882. computeBoundingSphere: function () {
  4883. if ( this.boundingSphere === null ) {
  4884. this.boundingSphere = new THREE.Sphere();
  4885. }
  4886. this.boundingSphere.setFromPoints( this.vertices );
  4887. },
  4888. /*
  4889. * Checks for duplicate vertices with hashmap.
  4890. * Duplicated vertices are removed
  4891. * and faces' vertices are updated.
  4892. */
  4893. mergeVertices: function () {
  4894. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4895. var unique = [], changes = [];
  4896. var v, key;
  4897. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4898. var precision = Math.pow( 10, precisionPoints );
  4899. var i,il, face;
  4900. var indices, k, j, jl, u;
  4901. // reset cache of vertices as it now will be changing.
  4902. this.__tmpVertices = undefined;
  4903. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4904. v = this.vertices[ i ];
  4905. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  4906. if ( verticesMap[ key ] === undefined ) {
  4907. verticesMap[ key ] = i;
  4908. unique.push( this.vertices[ i ] );
  4909. changes[ i ] = unique.length - 1;
  4910. } else {
  4911. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4912. changes[ i ] = changes[ verticesMap[ key ] ];
  4913. }
  4914. };
  4915. // if faces are completely degenerate after merging vertices, we
  4916. // have to remove them from the geometry.
  4917. var faceIndicesToRemove = [];
  4918. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4919. face = this.faces[ i ];
  4920. if ( face instanceof THREE.Face3 ) {
  4921. face.a = changes[ face.a ];
  4922. face.b = changes[ face.b ];
  4923. face.c = changes[ face.c ];
  4924. indices = [ face.a, face.b, face.c ];
  4925. var dupIndex = -1;
  4926. // if any duplicate vertices are found in a Face3
  4927. // we have to remove the face as nothing can be saved
  4928. for ( var n = 0; n < 3; n ++ ) {
  4929. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4930. dupIndex = n;
  4931. faceIndicesToRemove.push( i );
  4932. break;
  4933. }
  4934. }
  4935. } else if ( face instanceof THREE.Face4 ) {
  4936. face.a = changes[ face.a ];
  4937. face.b = changes[ face.b ];
  4938. face.c = changes[ face.c ];
  4939. face.d = changes[ face.d ];
  4940. // check dups in (a, b, c, d) and convert to -> face3
  4941. indices = [ face.a, face.b, face.c, face.d ];
  4942. var dupIndex = -1;
  4943. for ( var n = 0; n < 4; n ++ ) {
  4944. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4945. // if more than one duplicated vertex is found
  4946. // we can't generate any valid Face3's, thus
  4947. // we need to remove this face complete.
  4948. if ( dupIndex >= 0 ) {
  4949. faceIndicesToRemove.push( i );
  4950. }
  4951. dupIndex = n;
  4952. }
  4953. }
  4954. if ( dupIndex >= 0 ) {
  4955. indices.splice( dupIndex, 1 );
  4956. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4957. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4958. u = this.faceVertexUvs[ j ][ i ];
  4959. if ( u ) {
  4960. u.splice( dupIndex, 1 );
  4961. }
  4962. }
  4963. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4964. newFace.vertexNormals = face.vertexNormals;
  4965. newFace.vertexNormals.splice( dupIndex, 1 );
  4966. }
  4967. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4968. newFace.vertexColors = face.vertexColors;
  4969. newFace.vertexColors.splice( dupIndex, 1 );
  4970. }
  4971. this.faces[ i ] = newFace;
  4972. }
  4973. }
  4974. }
  4975. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4976. this.faces.splice( i, 1 );
  4977. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4978. this.faceVertexUvs[ j ].splice( i, 1 );
  4979. }
  4980. }
  4981. // Use unique set of vertices
  4982. var diff = this.vertices.length - unique.length;
  4983. this.vertices = unique;
  4984. return diff;
  4985. },
  4986. clone: function () {
  4987. var geometry = new THREE.Geometry();
  4988. var vertices = this.vertices;
  4989. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4990. geometry.vertices.push( vertices[ i ].clone() );
  4991. }
  4992. var faces = this.faces;
  4993. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4994. geometry.faces.push( faces[ i ].clone() );
  4995. }
  4996. var uvs = this.faceVertexUvs[ 0 ];
  4997. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4998. var uv = uvs[ i ], uvCopy = [];
  4999. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5000. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5001. }
  5002. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5003. }
  5004. return geometry;
  5005. },
  5006. dispose: function () {
  5007. this.dispatchEvent( { type: 'dispose' } );
  5008. }
  5009. };
  5010. /**
  5011. * @author alteredq / http://alteredqualia.com/
  5012. */
  5013. THREE.BufferGeometry = function () {
  5014. this.id = THREE.Math.generateUUID();
  5015. // attributes
  5016. this.attributes = {};
  5017. // attributes typed arrays are kept only if dynamic flag is set
  5018. this.dynamic = false;
  5019. // offsets for chunks when using indexed elements
  5020. this.offsets = [];
  5021. // boundings
  5022. this.boundingBox = null;
  5023. this.boundingSphere = null;
  5024. this.hasTangents = false;
  5025. // for compatibility
  5026. this.morphTargets = [];
  5027. };
  5028. THREE.BufferGeometry.prototype = {
  5029. constructor: THREE.BufferGeometry,
  5030. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  5031. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  5032. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  5033. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  5034. applyMatrix: function ( matrix ) {
  5035. var positionArray;
  5036. var normalArray;
  5037. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5038. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5039. if ( positionArray !== undefined ) {
  5040. matrix.multiplyVector3Array( positionArray );
  5041. this.verticesNeedUpdate = true;
  5042. }
  5043. if ( normalArray !== undefined ) {
  5044. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5045. normalMatrix.multiplyVector3Array( normalArray );
  5046. this.normalizeNormals();
  5047. this.normalsNeedUpdate = true;
  5048. }
  5049. },
  5050. computeBoundingBox: function () {
  5051. if ( this.boundingBox === null ) {
  5052. this.boundingBox = new THREE.Box3();
  5053. }
  5054. var positions = this.attributes[ "position" ].array;
  5055. if ( positions ) {
  5056. var bb = this.boundingBox;
  5057. var x, y, z;
  5058. if( positions.length >= 3 ) {
  5059. bb.min.x = bb.max.x = positions[ 0 ];
  5060. bb.min.y = bb.max.y = positions[ 1 ];
  5061. bb.min.z = bb.max.z = positions[ 2 ];
  5062. }
  5063. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5064. x = positions[ i ];
  5065. y = positions[ i + 1 ];
  5066. z = positions[ i + 2 ];
  5067. // bounding box
  5068. if ( x < bb.min.x ) {
  5069. bb.min.x = x;
  5070. } else if ( x > bb.max.x ) {
  5071. bb.max.x = x;
  5072. }
  5073. if ( y < bb.min.y ) {
  5074. bb.min.y = y;
  5075. } else if ( y > bb.max.y ) {
  5076. bb.max.y = y;
  5077. }
  5078. if ( z < bb.min.z ) {
  5079. bb.min.z = z;
  5080. } else if ( z > bb.max.z ) {
  5081. bb.max.z = z;
  5082. }
  5083. }
  5084. }
  5085. if ( positions === undefined || positions.length === 0 ) {
  5086. this.boundingBox.min.set( 0, 0, 0 );
  5087. this.boundingBox.max.set( 0, 0, 0 );
  5088. }
  5089. },
  5090. computeBoundingSphere: function () {
  5091. if ( this.boundingSphere === null ) {
  5092. this.boundingSphere = new THREE.Sphere();
  5093. }
  5094. var positions = this.attributes[ "position" ].array;
  5095. if ( positions ) {
  5096. var radiusSq, maxRadiusSq = 0;
  5097. var x, y, z;
  5098. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5099. x = positions[ i ];
  5100. y = positions[ i + 1 ];
  5101. z = positions[ i + 2 ];
  5102. radiusSq = x * x + y * y + z * z;
  5103. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  5104. }
  5105. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5106. }
  5107. },
  5108. computeVertexNormals: function () {
  5109. if ( this.attributes[ "position" ] ) {
  5110. var i, il;
  5111. var j, jl;
  5112. var nVertexElements = this.attributes[ "position" ].array.length;
  5113. if ( this.attributes[ "normal" ] === undefined ) {
  5114. this.attributes[ "normal" ] = {
  5115. itemSize: 3,
  5116. array: new Float32Array( nVertexElements )
  5117. };
  5118. } else {
  5119. // reset existing normals to zero
  5120. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5121. this.attributes[ "normal" ].array[ i ] = 0;
  5122. }
  5123. }
  5124. var positions = this.attributes[ "position" ].array;
  5125. var normals = this.attributes[ "normal" ].array;
  5126. var vA, vB, vC, x, y, z,
  5127. pA = new THREE.Vector3(),
  5128. pB = new THREE.Vector3(),
  5129. pC = new THREE.Vector3(),
  5130. cb = new THREE.Vector3(),
  5131. ab = new THREE.Vector3();
  5132. // indexed elements
  5133. if ( this.attributes[ "index" ] ) {
  5134. var indices = this.attributes[ "index" ].array;
  5135. var offsets = this.offsets;
  5136. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5137. var start = offsets[ j ].start;
  5138. var count = offsets[ j ].count;
  5139. var index = offsets[ j ].index;
  5140. for ( i = start, il = start + count; i < il; i += 3 ) {
  5141. vA = index + indices[ i ];
  5142. vB = index + indices[ i + 1 ];
  5143. vC = index + indices[ i + 2 ];
  5144. x = positions[ vA * 3 ];
  5145. y = positions[ vA * 3 + 1 ];
  5146. z = positions[ vA * 3 + 2 ];
  5147. pA.set( x, y, z );
  5148. x = positions[ vB * 3 ];
  5149. y = positions[ vB * 3 + 1 ];
  5150. z = positions[ vB * 3 + 2 ];
  5151. pB.set( x, y, z );
  5152. x = positions[ vC * 3 ];
  5153. y = positions[ vC * 3 + 1 ];
  5154. z = positions[ vC * 3 + 2 ];
  5155. pC.set( x, y, z );
  5156. cb.subVectors( pC, pB );
  5157. ab.subVectors( pA, pB );
  5158. cb.cross( ab );
  5159. normals[ vA * 3 ] += cb.x;
  5160. normals[ vA * 3 + 1 ] += cb.y;
  5161. normals[ vA * 3 + 2 ] += cb.z;
  5162. normals[ vB * 3 ] += cb.x;
  5163. normals[ vB * 3 + 1 ] += cb.y;
  5164. normals[ vB * 3 + 2 ] += cb.z;
  5165. normals[ vC * 3 ] += cb.x;
  5166. normals[ vC * 3 + 1 ] += cb.y;
  5167. normals[ vC * 3 + 2 ] += cb.z;
  5168. }
  5169. }
  5170. // non-indexed elements (unconnected triangle soup)
  5171. } else {
  5172. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5173. x = positions[ i ];
  5174. y = positions[ i + 1 ];
  5175. z = positions[ i + 2 ];
  5176. pA.set( x, y, z );
  5177. x = positions[ i + 3 ];
  5178. y = positions[ i + 4 ];
  5179. z = positions[ i + 5 ];
  5180. pB.set( x, y, z );
  5181. x = positions[ i + 6 ];
  5182. y = positions[ i + 7 ];
  5183. z = positions[ i + 8 ];
  5184. pC.set( x, y, z );
  5185. cb.subVectors( pC, pB );
  5186. ab.subVectors( pA, pB );
  5187. cb.cross( ab );
  5188. normals[ i ] = cb.x;
  5189. normals[ i + 1 ] = cb.y;
  5190. normals[ i + 2 ] = cb.z;
  5191. normals[ i + 3 ] = cb.x;
  5192. normals[ i + 4 ] = cb.y;
  5193. normals[ i + 5 ] = cb.z;
  5194. normals[ i + 6 ] = cb.x;
  5195. normals[ i + 7 ] = cb.y;
  5196. normals[ i + 8 ] = cb.z;
  5197. }
  5198. }
  5199. this.normalizeNormals();
  5200. this.normalsNeedUpdate = true;
  5201. }
  5202. },
  5203. normalizeNormals: function () {
  5204. var normals = this.attributes[ "normal" ].array;
  5205. var x, y, z, n;
  5206. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5207. x = normals[ i ];
  5208. y = normals[ i + 1 ];
  5209. z = normals[ i + 2 ];
  5210. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5211. normals[ i ] *= n;
  5212. normals[ i + 1 ] *= n;
  5213. normals[ i + 2 ] *= n;
  5214. }
  5215. },
  5216. computeTangents: function () {
  5217. // based on http://www.terathon.com/code/tangent.html
  5218. // (per vertex tangents)
  5219. if ( this.attributes[ "index" ] === undefined ||
  5220. this.attributes[ "position" ] === undefined ||
  5221. this.attributes[ "normal" ] === undefined ||
  5222. this.attributes[ "uv" ] === undefined ) {
  5223. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5224. return;
  5225. }
  5226. var indices = this.attributes[ "index" ].array;
  5227. var positions = this.attributes[ "position" ].array;
  5228. var normals = this.attributes[ "normal" ].array;
  5229. var uvs = this.attributes[ "uv" ].array;
  5230. var nVertices = positions.length / 3;
  5231. if ( this.attributes[ "tangent" ] === undefined ) {
  5232. var nTangentElements = 4 * nVertices;
  5233. this.attributes[ "tangent" ] = {
  5234. itemSize: 4,
  5235. array: new Float32Array( nTangentElements )
  5236. };
  5237. }
  5238. var tangents = this.attributes[ "tangent" ].array;
  5239. var tan1 = [], tan2 = [];
  5240. for ( var k = 0; k < nVertices; k ++ ) {
  5241. tan1[ k ] = new THREE.Vector3();
  5242. tan2[ k ] = new THREE.Vector3();
  5243. }
  5244. var xA, yA, zA,
  5245. xB, yB, zB,
  5246. xC, yC, zC,
  5247. uA, vA,
  5248. uB, vB,
  5249. uC, vC,
  5250. x1, x2, y1, y2, z1, z2,
  5251. s1, s2, t1, t2, r;
  5252. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5253. function handleTriangle( a, b, c ) {
  5254. xA = positions[ a * 3 ];
  5255. yA = positions[ a * 3 + 1 ];
  5256. zA = positions[ a * 3 + 2 ];
  5257. xB = positions[ b * 3 ];
  5258. yB = positions[ b * 3 + 1 ];
  5259. zB = positions[ b * 3 + 2 ];
  5260. xC = positions[ c * 3 ];
  5261. yC = positions[ c * 3 + 1 ];
  5262. zC = positions[ c * 3 + 2 ];
  5263. uA = uvs[ a * 2 ];
  5264. vA = uvs[ a * 2 + 1 ];
  5265. uB = uvs[ b * 2 ];
  5266. vB = uvs[ b * 2 + 1 ];
  5267. uC = uvs[ c * 2 ];
  5268. vC = uvs[ c * 2 + 1 ];
  5269. x1 = xB - xA;
  5270. x2 = xC - xA;
  5271. y1 = yB - yA;
  5272. y2 = yC - yA;
  5273. z1 = zB - zA;
  5274. z2 = zC - zA;
  5275. s1 = uB - uA;
  5276. s2 = uC - uA;
  5277. t1 = vB - vA;
  5278. t2 = vC - vA;
  5279. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5280. sdir.set(
  5281. ( t2 * x1 - t1 * x2 ) * r,
  5282. ( t2 * y1 - t1 * y2 ) * r,
  5283. ( t2 * z1 - t1 * z2 ) * r
  5284. );
  5285. tdir.set(
  5286. ( s1 * x2 - s2 * x1 ) * r,
  5287. ( s1 * y2 - s2 * y1 ) * r,
  5288. ( s1 * z2 - s2 * z1 ) * r
  5289. );
  5290. tan1[ a ].add( sdir );
  5291. tan1[ b ].add( sdir );
  5292. tan1[ c ].add( sdir );
  5293. tan2[ a ].add( tdir );
  5294. tan2[ b ].add( tdir );
  5295. tan2[ c ].add( tdir );
  5296. }
  5297. var i, il;
  5298. var j, jl;
  5299. var iA, iB, iC;
  5300. var offsets = this.offsets;
  5301. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5302. var start = offsets[ j ].start;
  5303. var count = offsets[ j ].count;
  5304. var index = offsets[ j ].index;
  5305. for ( i = start, il = start + count; i < il; i += 3 ) {
  5306. iA = index + indices[ i ];
  5307. iB = index + indices[ i + 1 ];
  5308. iC = index + indices[ i + 2 ];
  5309. handleTriangle( iA, iB, iC );
  5310. }
  5311. }
  5312. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5313. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5314. var w, t, test;
  5315. function handleVertex( v ) {
  5316. n.x = normals[ v * 3 ];
  5317. n.y = normals[ v * 3 + 1 ];
  5318. n.z = normals[ v * 3 + 2 ];
  5319. n2.copy( n );
  5320. t = tan1[ v ];
  5321. // Gram-Schmidt orthogonalize
  5322. tmp.copy( t );
  5323. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5324. // Calculate handedness
  5325. tmp2.crossVectors( n2, t );
  5326. test = tmp2.dot( tan2[ v ] );
  5327. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5328. tangents[ v * 4 ] = tmp.x;
  5329. tangents[ v * 4 + 1 ] = tmp.y;
  5330. tangents[ v * 4 + 2 ] = tmp.z;
  5331. tangents[ v * 4 + 3 ] = w;
  5332. }
  5333. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5334. var start = offsets[ j ].start;
  5335. var count = offsets[ j ].count;
  5336. var index = offsets[ j ].index;
  5337. for ( i = start, il = start + count; i < il; i += 3 ) {
  5338. iA = index + indices[ i ];
  5339. iB = index + indices[ i + 1 ];
  5340. iC = index + indices[ i + 2 ];
  5341. handleVertex( iA );
  5342. handleVertex( iB );
  5343. handleVertex( iC );
  5344. }
  5345. }
  5346. this.hasTangents = true;
  5347. this.tangentsNeedUpdate = true;
  5348. },
  5349. dispose: function () {
  5350. this.dispatchEvent( { type: 'dispose' } );
  5351. }
  5352. };
  5353. /**
  5354. * @author mrdoob / http://mrdoob.com/
  5355. * @author mikael emtinger / http://gomo.se/
  5356. * @author WestLangley / http://github.com/WestLangley
  5357. */
  5358. THREE.Camera = function () {
  5359. THREE.Object3D.call( this );
  5360. this.matrixWorldInverse = new THREE.Matrix4();
  5361. this.projectionMatrix = new THREE.Matrix4();
  5362. this.projectionMatrixInverse = new THREE.Matrix4();
  5363. };
  5364. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5365. THREE.Camera.prototype.lookAt = function () {
  5366. // This routine does not support cameras with rotated and/or translated parent(s)
  5367. var m1 = new THREE.Matrix4();
  5368. return function ( vector ) {
  5369. m1.lookAt( this.position, vector, this.up );
  5370. if ( this.useQuaternion === true ) {
  5371. this.quaternion.setFromRotationMatrix( m1 );
  5372. } else {
  5373. this.rotation.setEulerFromRotationMatrix( m1, this.eulerOrder );
  5374. }
  5375. };
  5376. }();
  5377. /**
  5378. * @author alteredq / http://alteredqualia.com/
  5379. */
  5380. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5381. THREE.Camera.call( this );
  5382. this.left = left;
  5383. this.right = right;
  5384. this.top = top;
  5385. this.bottom = bottom;
  5386. this.near = ( near !== undefined ) ? near : 0.1;
  5387. this.far = ( far !== undefined ) ? far : 2000;
  5388. this.updateProjectionMatrix();
  5389. };
  5390. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5391. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5392. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5393. };
  5394. /**
  5395. * @author mrdoob / http://mrdoob.com/
  5396. * @author greggman / http://games.greggman.com/
  5397. * @author zz85 / http://www.lab4games.net/zz85/blog
  5398. */
  5399. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5400. THREE.Camera.call( this );
  5401. this.fov = fov !== undefined ? fov : 50;
  5402. this.aspect = aspect !== undefined ? aspect : 1;
  5403. this.near = near !== undefined ? near : 0.1;
  5404. this.far = far !== undefined ? far : 2000;
  5405. this.updateProjectionMatrix();
  5406. };
  5407. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5408. /**
  5409. * Uses Focal Length (in mm) to estimate and set FOV
  5410. * 35mm (fullframe) camera is used if frame size is not specified;
  5411. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5412. */
  5413. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5414. if ( frameHeight === undefined ) frameHeight = 24;
  5415. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5416. this.updateProjectionMatrix();
  5417. }
  5418. /**
  5419. * Sets an offset in a larger frustum. This is useful for multi-window or
  5420. * multi-monitor/multi-machine setups.
  5421. *
  5422. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5423. * the monitors are in grid like this
  5424. *
  5425. * +---+---+---+
  5426. * | A | B | C |
  5427. * +---+---+---+
  5428. * | D | E | F |
  5429. * +---+---+---+
  5430. *
  5431. * then for each monitor you would call it like this
  5432. *
  5433. * var w = 1920;
  5434. * var h = 1080;
  5435. * var fullWidth = w * 3;
  5436. * var fullHeight = h * 2;
  5437. *
  5438. * --A--
  5439. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5440. * --B--
  5441. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5442. * --C--
  5443. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5444. * --D--
  5445. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5446. * --E--
  5447. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5448. * --F--
  5449. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5450. *
  5451. * Note there is no reason monitors have to be the same size or in a grid.
  5452. */
  5453. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5454. this.fullWidth = fullWidth;
  5455. this.fullHeight = fullHeight;
  5456. this.x = x;
  5457. this.y = y;
  5458. this.width = width;
  5459. this.height = height;
  5460. this.updateProjectionMatrix();
  5461. };
  5462. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5463. if ( this.fullWidth ) {
  5464. var aspect = this.fullWidth / this.fullHeight;
  5465. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5466. var bottom = -top;
  5467. var left = aspect * bottom;
  5468. var right = aspect * top;
  5469. var width = Math.abs( right - left );
  5470. var height = Math.abs( top - bottom );
  5471. this.projectionMatrix.makeFrustum(
  5472. left + this.x * width / this.fullWidth,
  5473. left + ( this.x + this.width ) * width / this.fullWidth,
  5474. top - ( this.y + this.height ) * height / this.fullHeight,
  5475. top - this.y * height / this.fullHeight,
  5476. this.near,
  5477. this.far
  5478. );
  5479. } else {
  5480. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5481. }
  5482. };
  5483. /**
  5484. * @author mrdoob / http://mrdoob.com/
  5485. * @author alteredq / http://alteredqualia.com/
  5486. */
  5487. THREE.Light = function ( hex ) {
  5488. THREE.Object3D.call( this );
  5489. this.color = new THREE.Color( hex );
  5490. };
  5491. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5492. THREE.Light.prototype.clone = function ( light ) {
  5493. if ( light === undefined ) light = new THREE.Light();
  5494. THREE.Object3D.prototype.clone.call( this, light );
  5495. light.color.copy( this.color );
  5496. return light;
  5497. };
  5498. /**
  5499. * @author mrdoob / http://mrdoob.com/
  5500. */
  5501. THREE.AmbientLight = function ( hex ) {
  5502. THREE.Light.call( this, hex );
  5503. };
  5504. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5505. THREE.AmbientLight.prototype.clone = function () {
  5506. var light = new THREE.AmbientLight();
  5507. THREE.Light.prototype.clone.call( this, light );
  5508. return light;
  5509. };
  5510. /**
  5511. * @author MPanknin / http://www.redplant.de/
  5512. * @author alteredq / http://alteredqualia.com/
  5513. */
  5514. THREE.AreaLight = function ( hex, intensity ) {
  5515. THREE.Light.call( this, hex );
  5516. this.normal = new THREE.Vector3( 0, -1, 0 );
  5517. this.right = new THREE.Vector3( 1, 0, 0 );
  5518. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5519. this.width = 1.0;
  5520. this.height = 1.0;
  5521. this.constantAttenuation = 1.5;
  5522. this.linearAttenuation = 0.5;
  5523. this.quadraticAttenuation = 0.1;
  5524. };
  5525. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5526. /**
  5527. * @author mrdoob / http://mrdoob.com/
  5528. * @author alteredq / http://alteredqualia.com/
  5529. */
  5530. THREE.DirectionalLight = function ( hex, intensity ) {
  5531. THREE.Light.call( this, hex );
  5532. this.position.set( 0, 1, 0 );
  5533. this.target = new THREE.Object3D();
  5534. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5535. this.castShadow = false;
  5536. this.onlyShadow = false;
  5537. //
  5538. this.shadowCameraNear = 50;
  5539. this.shadowCameraFar = 5000;
  5540. this.shadowCameraLeft = -500;
  5541. this.shadowCameraRight = 500;
  5542. this.shadowCameraTop = 500;
  5543. this.shadowCameraBottom = -500;
  5544. this.shadowCameraVisible = false;
  5545. this.shadowBias = 0;
  5546. this.shadowDarkness = 0.5;
  5547. this.shadowMapWidth = 512;
  5548. this.shadowMapHeight = 512;
  5549. //
  5550. this.shadowCascade = false;
  5551. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5552. this.shadowCascadeCount = 2;
  5553. this.shadowCascadeBias = [ 0, 0, 0 ];
  5554. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5555. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5556. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5557. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5558. this.shadowCascadeArray = [];
  5559. //
  5560. this.shadowMap = null;
  5561. this.shadowMapSize = null;
  5562. this.shadowCamera = null;
  5563. this.shadowMatrix = null;
  5564. };
  5565. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5566. THREE.DirectionalLight.prototype.clone = function () {
  5567. var light = new THREE.DirectionalLight();
  5568. THREE.Light.prototype.clone.call( this, light );
  5569. light.target = this.target.clone();
  5570. light.intensity = this.intensity;
  5571. light.castShadow = this.castShadow;
  5572. light.onlyShadow = this.onlyShadow;
  5573. return light;
  5574. };
  5575. /**
  5576. * @author alteredq / http://alteredqualia.com/
  5577. */
  5578. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5579. THREE.Light.call( this, skyColorHex );
  5580. this.position.set( 0, 100, 0 );
  5581. this.groundColor = new THREE.Color( groundColorHex );
  5582. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5583. };
  5584. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5585. THREE.HemisphereLight.prototype.clone = function () {
  5586. var light = new THREE.PointLight();
  5587. THREE.Light.prototype.clone.call( this, light );
  5588. light.groundColor.copy( this.groundColor );
  5589. light.intensity = this.intensity;
  5590. return light;
  5591. };
  5592. /**
  5593. * @author mrdoob / http://mrdoob.com/
  5594. */
  5595. THREE.PointLight = function ( hex, intensity, distance ) {
  5596. THREE.Light.call( this, hex );
  5597. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5598. this.distance = ( distance !== undefined ) ? distance : 0;
  5599. };
  5600. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5601. THREE.PointLight.prototype.clone = function () {
  5602. var light = new THREE.PointLight();
  5603. THREE.Light.prototype.clone.call( this, light );
  5604. light.intensity = this.intensity;
  5605. light.distance = this.distance;
  5606. return light;
  5607. };
  5608. /**
  5609. * @author alteredq / http://alteredqualia.com/
  5610. */
  5611. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5612. THREE.Light.call( this, hex );
  5613. this.position.set( 0, 1, 0 );
  5614. this.target = new THREE.Object3D();
  5615. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5616. this.distance = ( distance !== undefined ) ? distance : 0;
  5617. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5618. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5619. this.castShadow = false;
  5620. this.onlyShadow = false;
  5621. //
  5622. this.shadowCameraNear = 50;
  5623. this.shadowCameraFar = 5000;
  5624. this.shadowCameraFov = 50;
  5625. this.shadowCameraVisible = false;
  5626. this.shadowBias = 0;
  5627. this.shadowDarkness = 0.5;
  5628. this.shadowMapWidth = 512;
  5629. this.shadowMapHeight = 512;
  5630. //
  5631. this.shadowMap = null;
  5632. this.shadowMapSize = null;
  5633. this.shadowCamera = null;
  5634. this.shadowMatrix = null;
  5635. };
  5636. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5637. THREE.SpotLight.prototype.clone = function () {
  5638. var light = new THREE.SpotLight();
  5639. THREE.Light.prototype.clone.call( this, light );
  5640. light.target = this.target.clone();
  5641. light.intensity = this.intensity;
  5642. light.distance = this.distance;
  5643. light.angle = this.angle;
  5644. light.exponent = this.exponent;
  5645. light.castShadow = this.castShadow;
  5646. light.onlyShadow = this.onlyShadow;
  5647. return light;
  5648. };
  5649. /**
  5650. * @author alteredq / http://alteredqualia.com/
  5651. */
  5652. THREE.Loader = function ( showStatus ) {
  5653. this.showStatus = showStatus;
  5654. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5655. this.onLoadStart = function () {};
  5656. this.onLoadProgress = function () {};
  5657. this.onLoadComplete = function () {};
  5658. };
  5659. THREE.Loader.prototype = {
  5660. constructor: THREE.Loader,
  5661. crossOrigin: 'anonymous',
  5662. addStatusElement: function () {
  5663. var e = document.createElement( "div" );
  5664. e.style.position = "absolute";
  5665. e.style.right = "0px";
  5666. e.style.top = "0px";
  5667. e.style.fontSize = "0.8em";
  5668. e.style.textAlign = "left";
  5669. e.style.background = "rgba(0,0,0,0.25)";
  5670. e.style.color = "#fff";
  5671. e.style.width = "120px";
  5672. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5673. e.style.zIndex = 1000;
  5674. e.innerHTML = "Loading ...";
  5675. return e;
  5676. },
  5677. updateProgress: function ( progress ) {
  5678. var message = "Loaded ";
  5679. if ( progress.total ) {
  5680. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5681. } else {
  5682. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5683. }
  5684. this.statusDomElement.innerHTML = message;
  5685. },
  5686. extractUrlBase: function ( url ) {
  5687. var parts = url.split( '/' );
  5688. parts.pop();
  5689. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5690. },
  5691. initMaterials: function ( materials, texturePath ) {
  5692. var array = [];
  5693. for ( var i = 0; i < materials.length; ++ i ) {
  5694. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5695. }
  5696. return array;
  5697. },
  5698. needsTangents: function ( materials ) {
  5699. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5700. var m = materials[ i ];
  5701. if ( m instanceof THREE.ShaderMaterial ) return true;
  5702. }
  5703. return false;
  5704. },
  5705. createMaterial: function ( m, texturePath ) {
  5706. var _this = this;
  5707. function is_pow2( n ) {
  5708. var l = Math.log( n ) / Math.LN2;
  5709. return Math.floor( l ) == l;
  5710. }
  5711. function nearest_pow2( n ) {
  5712. var l = Math.log( n ) / Math.LN2;
  5713. return Math.pow( 2, Math.round( l ) );
  5714. }
  5715. function load_image( where, url ) {
  5716. var image = new Image();
  5717. image.onload = function () {
  5718. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5719. var width = nearest_pow2( this.width );
  5720. var height = nearest_pow2( this.height );
  5721. where.image.width = width;
  5722. where.image.height = height;
  5723. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5724. } else {
  5725. where.image = this;
  5726. }
  5727. where.needsUpdate = true;
  5728. };
  5729. image.crossOrigin = _this.crossOrigin;
  5730. image.src = url;
  5731. }
  5732. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5733. var isCompressed = /\.dds$/i.test( sourceFile );
  5734. var fullPath = texturePath + "/" + sourceFile;
  5735. if ( isCompressed ) {
  5736. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5737. where[ name ] = texture;
  5738. } else {
  5739. var texture = document.createElement( 'canvas' );
  5740. where[ name ] = new THREE.Texture( texture );
  5741. }
  5742. where[ name ].sourceFile = sourceFile;
  5743. if( repeat ) {
  5744. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5745. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5746. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5747. }
  5748. if ( offset ) {
  5749. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5750. }
  5751. if ( wrap ) {
  5752. var wrapMap = {
  5753. "repeat": THREE.RepeatWrapping,
  5754. "mirror": THREE.MirroredRepeatWrapping
  5755. }
  5756. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5757. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5758. }
  5759. if ( anisotropy ) {
  5760. where[ name ].anisotropy = anisotropy;
  5761. }
  5762. if ( ! isCompressed ) {
  5763. load_image( where[ name ], fullPath );
  5764. }
  5765. }
  5766. function rgb2hex( rgb ) {
  5767. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5768. }
  5769. // defaults
  5770. var mtype = "MeshLambertMaterial";
  5771. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5772. // parameters from model file
  5773. if ( m.shading ) {
  5774. var shading = m.shading.toLowerCase();
  5775. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5776. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5777. }
  5778. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5779. mpars.blending = THREE[ m.blending ];
  5780. }
  5781. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5782. mpars.transparent = m.transparent;
  5783. }
  5784. if ( m.depthTest !== undefined ) {
  5785. mpars.depthTest = m.depthTest;
  5786. }
  5787. if ( m.depthWrite !== undefined ) {
  5788. mpars.depthWrite = m.depthWrite;
  5789. }
  5790. if ( m.visible !== undefined ) {
  5791. mpars.visible = m.visible;
  5792. }
  5793. if ( m.flipSided !== undefined ) {
  5794. mpars.side = THREE.BackSide;
  5795. }
  5796. if ( m.doubleSided !== undefined ) {
  5797. mpars.side = THREE.DoubleSide;
  5798. }
  5799. if ( m.wireframe !== undefined ) {
  5800. mpars.wireframe = m.wireframe;
  5801. }
  5802. if ( m.vertexColors !== undefined ) {
  5803. if ( m.vertexColors === "face" ) {
  5804. mpars.vertexColors = THREE.FaceColors;
  5805. } else if ( m.vertexColors ) {
  5806. mpars.vertexColors = THREE.VertexColors;
  5807. }
  5808. }
  5809. // colors
  5810. if ( m.colorDiffuse ) {
  5811. mpars.color = rgb2hex( m.colorDiffuse );
  5812. } else if ( m.DbgColor ) {
  5813. mpars.color = m.DbgColor;
  5814. }
  5815. if ( m.colorSpecular ) {
  5816. mpars.specular = rgb2hex( m.colorSpecular );
  5817. }
  5818. if ( m.colorAmbient ) {
  5819. mpars.ambient = rgb2hex( m.colorAmbient );
  5820. }
  5821. // modifiers
  5822. if ( m.transparency ) {
  5823. mpars.opacity = m.transparency;
  5824. }
  5825. if ( m.specularCoef ) {
  5826. mpars.shininess = m.specularCoef;
  5827. }
  5828. // textures
  5829. if ( m.mapDiffuse && texturePath ) {
  5830. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5831. }
  5832. if ( m.mapLight && texturePath ) {
  5833. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5834. }
  5835. if ( m.mapBump && texturePath ) {
  5836. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5837. }
  5838. if ( m.mapNormal && texturePath ) {
  5839. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5840. }
  5841. if ( m.mapSpecular && texturePath ) {
  5842. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5843. }
  5844. //
  5845. if ( m.mapBumpScale ) {
  5846. mpars.bumpScale = m.mapBumpScale;
  5847. }
  5848. // special case for normal mapped material
  5849. if ( m.mapNormal ) {
  5850. var shader = THREE.ShaderLib[ "normalmap" ];
  5851. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5852. uniforms[ "tNormal" ].value = mpars.normalMap;
  5853. if ( m.mapNormalFactor ) {
  5854. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5855. }
  5856. if ( mpars.map ) {
  5857. uniforms[ "tDiffuse" ].value = mpars.map;
  5858. uniforms[ "enableDiffuse" ].value = true;
  5859. }
  5860. if ( mpars.specularMap ) {
  5861. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5862. uniforms[ "enableSpecular" ].value = true;
  5863. }
  5864. if ( mpars.lightMap ) {
  5865. uniforms[ "tAO" ].value = mpars.lightMap;
  5866. uniforms[ "enableAO" ].value = true;
  5867. }
  5868. // for the moment don't handle displacement texture
  5869. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5870. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5871. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5872. uniforms[ "uShininess" ].value = mpars.shininess;
  5873. if ( mpars.opacity !== undefined ) {
  5874. uniforms[ "uOpacity" ].value = mpars.opacity;
  5875. }
  5876. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5877. var material = new THREE.ShaderMaterial( parameters );
  5878. if ( mpars.transparent ) {
  5879. material.transparent = true;
  5880. }
  5881. } else {
  5882. var material = new THREE[ mtype ]( mpars );
  5883. }
  5884. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5885. return material;
  5886. }
  5887. };
  5888. /**
  5889. * @author mrdoob / http://mrdoob.com/
  5890. */
  5891. THREE.XHRLoader = function ( manager ) {
  5892. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  5893. };
  5894. THREE.XHRLoader.prototype = {
  5895. constructor: THREE.XHRLoader,
  5896. load: function ( url, onLoad, onProgress, onError ) {
  5897. var scope = this;
  5898. var request = new XMLHttpRequest();
  5899. if ( onLoad !== undefined ) {
  5900. request.addEventListener( 'load', function ( event ) {
  5901. scope.manager.itemEnd( url );
  5902. onLoad( event.target.responseText );
  5903. }, false );
  5904. }
  5905. if ( onProgress !== undefined ) {
  5906. request.addEventListener( 'progress', function ( event ) {
  5907. onProgress( event );
  5908. }, false );
  5909. }
  5910. if ( onError !== undefined ) {
  5911. request.addEventListener( 'error', function ( event ) {
  5912. onError( event );
  5913. }, false );
  5914. }
  5915. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  5916. request.open( 'GET', url, true );
  5917. request.send( null );
  5918. scope.manager.itemStart( url );
  5919. },
  5920. setCrossOrigin: function ( value ) {
  5921. this.crossOrigin = value;
  5922. }
  5923. };
  5924. /**
  5925. * @author mrdoob / http://mrdoob.com/
  5926. */
  5927. THREE.ImageLoader = function ( manager ) {
  5928. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  5929. };
  5930. THREE.ImageLoader.prototype = {
  5931. constructor: THREE.ImageLoader,
  5932. load: function ( url, onLoad, onProgress, onError ) {
  5933. var scope = this;
  5934. var image = document.createElement( 'img' );
  5935. if ( onLoad !== undefined ) {
  5936. image.addEventListener( 'load', function ( event ) {
  5937. scope.manager.itemEnd( url );
  5938. onLoad( this );
  5939. }, false );
  5940. }
  5941. if ( onProgress !== undefined ) {
  5942. image.addEventListener( 'progress', function ( event ) {
  5943. onProgress( event );
  5944. }, false );
  5945. }
  5946. if ( onError !== undefined ) {
  5947. image.addEventListener( 'error', function ( event ) {
  5948. onError( event );
  5949. }, false );
  5950. }
  5951. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  5952. image.src = url;
  5953. scope.manager.itemStart( url );
  5954. },
  5955. setCrossOrigin: function ( value ) {
  5956. this.crossOrigin = value;
  5957. }
  5958. }
  5959. /**
  5960. * @author mrdoob / http://mrdoob.com/
  5961. * @author alteredq / http://alteredqualia.com/
  5962. */
  5963. THREE.JSONLoader = function ( showStatus ) {
  5964. THREE.Loader.call( this, showStatus );
  5965. this.withCredentials = false;
  5966. };
  5967. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5968. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5969. var scope = this;
  5970. // todo: unify load API to for easier SceneLoader use
  5971. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5972. this.onLoadStart();
  5973. this.loadAjaxJSON( this, url, callback, texturePath );
  5974. };
  5975. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5976. var xhr = new XMLHttpRequest();
  5977. var length = 0;
  5978. xhr.onreadystatechange = function () {
  5979. if ( xhr.readyState === xhr.DONE ) {
  5980. if ( xhr.status === 200 || xhr.status === 0 ) {
  5981. if ( xhr.responseText ) {
  5982. var json = JSON.parse( xhr.responseText );
  5983. var result = context.parse( json, texturePath );
  5984. callback( result.geometry, result.materials );
  5985. } else {
  5986. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5987. }
  5988. // in context of more complex asset initialization
  5989. // do not block on single failed file
  5990. // maybe should go even one more level up
  5991. context.onLoadComplete();
  5992. } else {
  5993. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5994. }
  5995. } else if ( xhr.readyState === xhr.LOADING ) {
  5996. if ( callbackProgress ) {
  5997. if ( length === 0 ) {
  5998. length = xhr.getResponseHeader( "Content-Length" );
  5999. }
  6000. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6001. }
  6002. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6003. if ( callbackProgress !== undefined ) {
  6004. length = xhr.getResponseHeader( "Content-Length" );
  6005. }
  6006. }
  6007. };
  6008. xhr.open( "GET", url, true );
  6009. xhr.withCredentials = this.withCredentials;
  6010. xhr.send( null );
  6011. };
  6012. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6013. var scope = this,
  6014. geometry = new THREE.Geometry(),
  6015. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6016. parseModel( scale );
  6017. parseSkin();
  6018. parseMorphing( scale );
  6019. geometry.computeCentroids();
  6020. geometry.computeFaceNormals();
  6021. function parseModel( scale ) {
  6022. function isBitSet( value, position ) {
  6023. return value & ( 1 << position );
  6024. }
  6025. var i, j, fi,
  6026. offset, zLength, nVertices,
  6027. colorIndex, normalIndex, uvIndex, materialIndex,
  6028. type,
  6029. isQuad,
  6030. hasMaterial,
  6031. hasFaceUv, hasFaceVertexUv,
  6032. hasFaceNormal, hasFaceVertexNormal,
  6033. hasFaceColor, hasFaceVertexColor,
  6034. vertex, face, color, normal,
  6035. uvLayer, uvs, u, v,
  6036. faces = json.faces,
  6037. vertices = json.vertices,
  6038. normals = json.normals,
  6039. colors = json.colors,
  6040. nUvLayers = 0;
  6041. // disregard empty arrays
  6042. for ( i = 0; i < json.uvs.length; i++ ) {
  6043. if ( json.uvs[ i ].length ) nUvLayers ++;
  6044. }
  6045. for ( i = 0; i < nUvLayers; i++ ) {
  6046. geometry.faceUvs[ i ] = [];
  6047. geometry.faceVertexUvs[ i ] = [];
  6048. }
  6049. offset = 0;
  6050. zLength = vertices.length;
  6051. while ( offset < zLength ) {
  6052. vertex = new THREE.Vector3();
  6053. vertex.x = vertices[ offset ++ ] * scale;
  6054. vertex.y = vertices[ offset ++ ] * scale;
  6055. vertex.z = vertices[ offset ++ ] * scale;
  6056. geometry.vertices.push( vertex );
  6057. }
  6058. offset = 0;
  6059. zLength = faces.length;
  6060. while ( offset < zLength ) {
  6061. type = faces[ offset ++ ];
  6062. isQuad = isBitSet( type, 0 );
  6063. hasMaterial = isBitSet( type, 1 );
  6064. hasFaceUv = isBitSet( type, 2 );
  6065. hasFaceVertexUv = isBitSet( type, 3 );
  6066. hasFaceNormal = isBitSet( type, 4 );
  6067. hasFaceVertexNormal = isBitSet( type, 5 );
  6068. hasFaceColor = isBitSet( type, 6 );
  6069. hasFaceVertexColor = isBitSet( type, 7 );
  6070. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6071. if ( isQuad ) {
  6072. face = new THREE.Face4();
  6073. face.a = faces[ offset ++ ];
  6074. face.b = faces[ offset ++ ];
  6075. face.c = faces[ offset ++ ];
  6076. face.d = faces[ offset ++ ];
  6077. nVertices = 4;
  6078. } else {
  6079. face = new THREE.Face3();
  6080. face.a = faces[ offset ++ ];
  6081. face.b = faces[ offset ++ ];
  6082. face.c = faces[ offset ++ ];
  6083. nVertices = 3;
  6084. }
  6085. if ( hasMaterial ) {
  6086. materialIndex = faces[ offset ++ ];
  6087. face.materialIndex = materialIndex;
  6088. }
  6089. // to get face <=> uv index correspondence
  6090. fi = geometry.faces.length;
  6091. if ( hasFaceUv ) {
  6092. for ( i = 0; i < nUvLayers; i++ ) {
  6093. uvLayer = json.uvs[ i ];
  6094. uvIndex = faces[ offset ++ ];
  6095. u = uvLayer[ uvIndex * 2 ];
  6096. v = uvLayer[ uvIndex * 2 + 1 ];
  6097. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  6098. }
  6099. }
  6100. if ( hasFaceVertexUv ) {
  6101. for ( i = 0; i < nUvLayers; i++ ) {
  6102. uvLayer = json.uvs[ i ];
  6103. uvs = [];
  6104. for ( j = 0; j < nVertices; j ++ ) {
  6105. uvIndex = faces[ offset ++ ];
  6106. u = uvLayer[ uvIndex * 2 ];
  6107. v = uvLayer[ uvIndex * 2 + 1 ];
  6108. uvs[ j ] = new THREE.Vector2( u, v );
  6109. }
  6110. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  6111. }
  6112. }
  6113. if ( hasFaceNormal ) {
  6114. normalIndex = faces[ offset ++ ] * 3;
  6115. normal = new THREE.Vector3();
  6116. normal.x = normals[ normalIndex ++ ];
  6117. normal.y = normals[ normalIndex ++ ];
  6118. normal.z = normals[ normalIndex ];
  6119. face.normal = normal;
  6120. }
  6121. if ( hasFaceVertexNormal ) {
  6122. for ( i = 0; i < nVertices; i++ ) {
  6123. normalIndex = faces[ offset ++ ] * 3;
  6124. normal = new THREE.Vector3();
  6125. normal.x = normals[ normalIndex ++ ];
  6126. normal.y = normals[ normalIndex ++ ];
  6127. normal.z = normals[ normalIndex ];
  6128. face.vertexNormals.push( normal );
  6129. }
  6130. }
  6131. if ( hasFaceColor ) {
  6132. colorIndex = faces[ offset ++ ];
  6133. color = new THREE.Color( colors[ colorIndex ] );
  6134. face.color = color;
  6135. }
  6136. if ( hasFaceVertexColor ) {
  6137. for ( i = 0; i < nVertices; i++ ) {
  6138. colorIndex = faces[ offset ++ ];
  6139. color = new THREE.Color( colors[ colorIndex ] );
  6140. face.vertexColors.push( color );
  6141. }
  6142. }
  6143. geometry.faces.push( face );
  6144. }
  6145. };
  6146. function parseSkin() {
  6147. var i, l, x, y, z, w, a, b, c, d;
  6148. if ( json.skinWeights ) {
  6149. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6150. x = json.skinWeights[ i ];
  6151. y = json.skinWeights[ i + 1 ];
  6152. z = 0;
  6153. w = 0;
  6154. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6155. }
  6156. }
  6157. if ( json.skinIndices ) {
  6158. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6159. a = json.skinIndices[ i ];
  6160. b = json.skinIndices[ i + 1 ];
  6161. c = 0;
  6162. d = 0;
  6163. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6164. }
  6165. }
  6166. geometry.bones = json.bones;
  6167. geometry.animation = json.animation;
  6168. };
  6169. function parseMorphing( scale ) {
  6170. if ( json.morphTargets !== undefined ) {
  6171. var i, l, v, vl, dstVertices, srcVertices;
  6172. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6173. geometry.morphTargets[ i ] = {};
  6174. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6175. geometry.morphTargets[ i ].vertices = [];
  6176. dstVertices = geometry.morphTargets[ i ].vertices;
  6177. srcVertices = json.morphTargets [ i ].vertices;
  6178. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6179. var vertex = new THREE.Vector3();
  6180. vertex.x = srcVertices[ v ] * scale;
  6181. vertex.y = srcVertices[ v + 1 ] * scale;
  6182. vertex.z = srcVertices[ v + 2 ] * scale;
  6183. dstVertices.push( vertex );
  6184. }
  6185. }
  6186. }
  6187. if ( json.morphColors !== undefined ) {
  6188. var i, l, c, cl, dstColors, srcColors, color;
  6189. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6190. geometry.morphColors[ i ] = {};
  6191. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6192. geometry.morphColors[ i ].colors = [];
  6193. dstColors = geometry.morphColors[ i ].colors;
  6194. srcColors = json.morphColors [ i ].colors;
  6195. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6196. color = new THREE.Color( 0xffaa00 );
  6197. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6198. dstColors.push( color );
  6199. }
  6200. }
  6201. }
  6202. };
  6203. if ( json.materials === undefined ) {
  6204. return { geometry: geometry };
  6205. } else {
  6206. var materials = this.initMaterials( json.materials, texturePath );
  6207. if ( this.needsTangents( materials ) ) {
  6208. geometry.computeTangents();
  6209. }
  6210. return { geometry: geometry, materials: materials };
  6211. }
  6212. };
  6213. /**
  6214. * @author mrdoob / http://mrdoob.com/
  6215. */
  6216. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6217. var scope = this;
  6218. var loaded = 0, total = 0;
  6219. this.onLoad = onLoad;
  6220. this.onProgress = onProgress;
  6221. this.onError = onError;
  6222. this.itemStart = function ( url ) {
  6223. total ++;
  6224. };
  6225. this.itemEnd = function ( url ) {
  6226. loaded ++;
  6227. if ( scope.onProgress !== undefined ) {
  6228. scope.onProgress( url, loaded, total );
  6229. }
  6230. if ( loaded === total && scope.onLoad !== undefined ) {
  6231. scope.onLoad();
  6232. }
  6233. };
  6234. };
  6235. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6236. /**
  6237. * @author mrdoob / http://mrdoob.com/
  6238. */
  6239. THREE.GeometryLoader = function ( manager ) {
  6240. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6241. };
  6242. THREE.GeometryLoader.prototype = {
  6243. constructor: THREE.GeometryLoader,
  6244. load: function ( url, onLoad, onProgress, onError ) {
  6245. var scope = this;
  6246. var loader = new THREE.XHRLoader();
  6247. loader.setCrossOrigin( this.crossOrigin );
  6248. loader.load( url, function ( text ) {
  6249. onLoad( scope.parse( JSON.parse( text ) ) );
  6250. } );
  6251. },
  6252. setCrossOrigin: function ( value ) {
  6253. this.crossOrigin = value;
  6254. },
  6255. parse: function ( json ) {
  6256. }
  6257. };
  6258. /**
  6259. * @author mrdoob / http://mrdoob.com/
  6260. */
  6261. THREE.MaterialLoader = function ( manager ) {
  6262. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6263. };
  6264. THREE.MaterialLoader.prototype = {
  6265. constructor: THREE.MaterialLoader,
  6266. load: function ( url, onLoad, onProgress, onError ) {
  6267. var scope = this;
  6268. var loader = new THREE.XHRLoader();
  6269. loader.setCrossOrigin( this.crossOrigin );
  6270. loader.load( url, function ( text ) {
  6271. onLoad( scope.parse( JSON.parse( text ) ) );
  6272. } );
  6273. },
  6274. setCrossOrigin: function ( value ) {
  6275. this.crossOrigin = value;
  6276. },
  6277. parse: function ( json ) {
  6278. var material;
  6279. switch ( json.type ) {
  6280. case 'MeshBasicMaterial':
  6281. material = new THREE.MeshBasicMaterial( {
  6282. color: json.color,
  6283. opacity: json.opacity,
  6284. transparent: json.transparent,
  6285. wireframe: json.wireframe
  6286. } );
  6287. break;
  6288. case 'MeshLambertMaterial':
  6289. material = new THREE.MeshLambertMaterial( {
  6290. color: json.color,
  6291. ambient: json.ambient,
  6292. emissive: json.emissive,
  6293. opacity: json.opacity,
  6294. transparent: json.transparent,
  6295. wireframe: json.wireframe
  6296. } );
  6297. break;
  6298. case 'MeshPhongMaterial':
  6299. material = new THREE.MeshPhongMaterial( {
  6300. color: json.color,
  6301. ambient: json.ambient,
  6302. emissive: json.emissive,
  6303. specular: json.specular,
  6304. shininess: json.shininess,
  6305. opacity: json.opacity,
  6306. transparent: json.transparent,
  6307. wireframe: json.wireframe
  6308. } );
  6309. break;
  6310. case 'MeshNormalMaterial':
  6311. material = new THREE.MeshNormalMaterial( {
  6312. opacity: json.opacity,
  6313. transparent: json.transparent,
  6314. wireframe: json.wireframe
  6315. } );
  6316. break;
  6317. case 'MeshDepthMaterial':
  6318. material = new THREE.MeshDepthMaterial( {
  6319. opacity: json.opacity,
  6320. transparent: json.transparent,
  6321. wireframe: json.wireframe
  6322. } );
  6323. break;
  6324. }
  6325. return material;
  6326. }
  6327. };
  6328. /**
  6329. * @author mrdoob / http://mrdoob.com/
  6330. */
  6331. THREE.ObjectLoader = function ( manager ) {
  6332. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6333. };
  6334. THREE.ObjectLoader.prototype = {
  6335. constructor: THREE.ObjectLoader,
  6336. load: function ( url, onLoad, onProgress, onError ) {
  6337. var scope = this;
  6338. var loader = new THREE.XHRLoader( scope.manager );
  6339. loader.setCrossOrigin( this.crossOrigin );
  6340. loader.load( url, function ( text ) {
  6341. onLoad( scope.parse( JSON.parse( text ) ) );
  6342. } );
  6343. },
  6344. setCrossOrigin: function ( value ) {
  6345. this.crossOrigin = value;
  6346. },
  6347. parse: function ( json ) {
  6348. var geometries = this.parseGeometries( json.geometries );
  6349. var materials = this.parseMaterials( json.materials );
  6350. var object = this.parseObject( json.object, geometries, materials );
  6351. return object;
  6352. },
  6353. parseGeometries: function ( json ) {
  6354. var geometries = {};
  6355. if ( json !== undefined ) {
  6356. var loader = new THREE.JSONLoader();
  6357. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6358. var geometry;
  6359. var data = json[ i ];
  6360. switch ( data.type ) {
  6361. case 'PlaneGeometry':
  6362. geometry = new THREE.PlaneGeometry(
  6363. data.width,
  6364. data.height,
  6365. data.widthSegments,
  6366. data.heightSegments
  6367. );
  6368. break;
  6369. case 'CubeGeometry':
  6370. geometry = new THREE.CubeGeometry(
  6371. data.width,
  6372. data.height,
  6373. data.depth,
  6374. data.widthSegments,
  6375. data.heightSegments,
  6376. data.depthSegments
  6377. );
  6378. break;
  6379. case 'CylinderGeometry':
  6380. geometry = new THREE.CylinderGeometry(
  6381. data.radiusTop,
  6382. data.radiusBottom,
  6383. data.height,
  6384. data.radiusSegments,
  6385. data.heightSegments,
  6386. data.openEnded
  6387. );
  6388. break;
  6389. case 'SphereGeometry':
  6390. geometry = new THREE.SphereGeometry(
  6391. data.radius,
  6392. data.widthSegments,
  6393. data.heightSegments,
  6394. data.phiStart,
  6395. data.phiLength,
  6396. data.thetaStart,
  6397. data.thetaLength
  6398. );
  6399. break;
  6400. case 'IcosahedronGeometry':
  6401. geometry = new THREE.IcosahedronGeometry(
  6402. data.radius,
  6403. data.detail
  6404. );
  6405. break;
  6406. case 'TorusGeometry':
  6407. geometry = new THREE.TorusGeometry(
  6408. data.radius,
  6409. data.tube,
  6410. data.radialSegments,
  6411. data.tubularSegments,
  6412. data.arc
  6413. );
  6414. break;
  6415. case 'TorusKnotGeometry':
  6416. geometry = new THREE.TorusKnotGeometry(
  6417. data.radius,
  6418. data.tube,
  6419. data.radialSegments,
  6420. data.tubularSegments,
  6421. data.p,
  6422. data.q,
  6423. data.heightScale
  6424. );
  6425. break;
  6426. case 'Geometry':
  6427. geometry = loader.parse( data.data ).geometry;
  6428. break;
  6429. }
  6430. if ( data.id !== undefined ) geometry.id = data.id;
  6431. if ( data.name !== undefined ) geometry.name = data.name;
  6432. geometries[ data.id ] = geometry;
  6433. }
  6434. }
  6435. return geometries;
  6436. },
  6437. parseMaterials: function ( json ) {
  6438. var materials = {};
  6439. if ( json !== undefined ) {
  6440. var loader = new THREE.MaterialLoader();
  6441. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6442. var data = json[ i ];
  6443. var material = loader.parse( data );
  6444. if ( data.id !== undefined ) material.id = data.id;
  6445. if ( data.name !== undefined ) material.name = data.name;
  6446. materials[ data.id ] = material;
  6447. }
  6448. }
  6449. return materials;
  6450. },
  6451. parseObject: function ( data, geometries, materials ) {
  6452. var object;
  6453. switch ( data.type ) {
  6454. case 'Scene':
  6455. object = new THREE.Scene();
  6456. break;
  6457. case 'PerspectiveCamera':
  6458. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6459. object.position.fromArray( data.position );
  6460. object.rotation.fromArray( data.rotation );
  6461. break;
  6462. case 'OrthographicCamera':
  6463. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6464. object.position.fromArray( data.position );
  6465. object.rotation.fromArray( data.rotation );
  6466. break;
  6467. case 'AmbientLight':
  6468. object = new THREE.AmbientLight( data.color );
  6469. break;
  6470. case 'DirectionalLight':
  6471. object = new THREE.DirectionalLight( data.color, data.intensity );
  6472. object.position.fromArray( data.position );
  6473. break;
  6474. case 'PointLight':
  6475. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6476. object.position.fromArray( data.position );
  6477. break;
  6478. case 'SpotLight':
  6479. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6480. object.position.fromArray( data.position );
  6481. break;
  6482. case 'HemisphereLight':
  6483. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6484. object.position.fromArray( data.position );
  6485. break;
  6486. case 'Mesh':
  6487. object = new THREE.Mesh( geometries[ data.geometry ], materials[ data.material ] );
  6488. object.position.fromArray( data.position );
  6489. object.rotation.fromArray( data.rotation );
  6490. object.scale.fromArray( data.scale );
  6491. break;
  6492. default:
  6493. object = new THREE.Object3D();
  6494. object.position.fromArray( data.position );
  6495. object.rotation.fromArray( data.rotation );
  6496. object.scale.fromArray( data.scale );
  6497. }
  6498. if ( data.id !== undefined ) object.id = data.id;
  6499. if ( data.name !== undefined ) object.name = data.name;
  6500. if ( data.visible !== undefined ) object.visible = data.visible;
  6501. if ( data.userData !== undefined ) object.userData = data.userData;
  6502. if ( data.children !== undefined ) {
  6503. for ( var child in data.children ) {
  6504. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6505. }
  6506. }
  6507. return object;
  6508. }
  6509. };
  6510. /**
  6511. * @author alteredq / http://alteredqualia.com/
  6512. */
  6513. THREE.SceneLoader = function () {
  6514. this.onLoadStart = function () {};
  6515. this.onLoadProgress = function() {};
  6516. this.onLoadComplete = function () {};
  6517. this.callbackSync = function () {};
  6518. this.callbackProgress = function () {};
  6519. this.geometryHandlers = {};
  6520. this.hierarchyHandlers = {};
  6521. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6522. };
  6523. THREE.SceneLoader.prototype = {
  6524. constructor: THREE.SceneLoader,
  6525. load: function ( url, onLoad, onProgress, onError ) {
  6526. var scope = this;
  6527. var loader = new THREE.XHRLoader( scope.manager );
  6528. loader.setCrossOrigin( this.crossOrigin );
  6529. loader.load( url, function ( text ) {
  6530. scope.parse( JSON.parse( text ), onLoad, url );
  6531. } );
  6532. },
  6533. setCrossOrigin: function ( value ) {
  6534. this.crossOrigin = value;
  6535. },
  6536. addGeometryHandler: function ( typeID, loaderClass ) {
  6537. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  6538. },
  6539. addHierarchyHandler: function ( typeID, loaderClass ) {
  6540. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  6541. },
  6542. parse: function ( json, callbackFinished, url ) {
  6543. var scope = this;
  6544. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6545. var geometry, material, camera, fog,
  6546. texture, images, color,
  6547. light, hex, intensity,
  6548. counter_models, counter_textures,
  6549. total_models, total_textures,
  6550. result;
  6551. var target_array = [];
  6552. var data = json;
  6553. // async geometry loaders
  6554. for ( var typeID in this.geometryHandlers ) {
  6555. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  6556. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6557. }
  6558. // async hierachy loaders
  6559. for ( var typeID in this.hierarchyHandlers ) {
  6560. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  6561. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6562. }
  6563. counter_models = 0;
  6564. counter_textures = 0;
  6565. result = {
  6566. scene: new THREE.Scene(),
  6567. geometries: {},
  6568. face_materials: {},
  6569. materials: {},
  6570. textures: {},
  6571. objects: {},
  6572. cameras: {},
  6573. lights: {},
  6574. fogs: {},
  6575. empties: {},
  6576. groups: {}
  6577. };
  6578. if ( data.transform ) {
  6579. var position = data.transform.position,
  6580. rotation = data.transform.rotation,
  6581. scale = data.transform.scale;
  6582. if ( position ) {
  6583. result.scene.position.fromArray( position );
  6584. }
  6585. if ( rotation ) {
  6586. result.scene.rotation.fromArray( rotation );
  6587. }
  6588. if ( scale ) {
  6589. result.scene.scale.fromArray( scale );
  6590. }
  6591. if ( position || rotation || scale ) {
  6592. result.scene.updateMatrix();
  6593. result.scene.updateMatrixWorld();
  6594. }
  6595. }
  6596. function get_url( source_url, url_type ) {
  6597. if ( url_type == "relativeToHTML" ) {
  6598. return source_url;
  6599. } else {
  6600. return urlBase + "/" + source_url;
  6601. }
  6602. };
  6603. // toplevel loader function, delegates to handle_children
  6604. function handle_objects() {
  6605. handle_children( result.scene, data.objects );
  6606. }
  6607. // handle all the children from the loaded json and attach them to given parent
  6608. function handle_children( parent, children ) {
  6609. var mat, dst, pos, rot, scl, quat;
  6610. for ( var objID in children ) {
  6611. // check by id if child has already been handled,
  6612. // if not, create new object
  6613. var object = result.objects[ objID ];
  6614. var objJSON = children[ objID ];
  6615. if ( object === undefined ) {
  6616. // meshes
  6617. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  6618. if ( objJSON.loading === undefined ) {
  6619. var reservedTypes = {
  6620. "type": 1, "url": 1, "material": 1,
  6621. "position": 1, "rotation": 1, "scale" : 1,
  6622. "visible": 1, "children": 1, "userData": 1,
  6623. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  6624. };
  6625. var loaderParameters = {};
  6626. for ( var parType in objJSON ) {
  6627. if ( ! ( parType in reservedTypes ) ) {
  6628. loaderParameters[ parType ] = objJSON[ parType ];
  6629. }
  6630. }
  6631. material = result.materials[ objJSON.material ];
  6632. objJSON.loading = true;
  6633. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  6634. // ColladaLoader
  6635. if ( loader.options ) {
  6636. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6637. // UTF8Loader
  6638. // OBJLoader
  6639. } else {
  6640. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6641. }
  6642. }
  6643. } else if ( objJSON.geometry !== undefined ) {
  6644. geometry = result.geometries[ objJSON.geometry ];
  6645. // geometry already loaded
  6646. if ( geometry ) {
  6647. var needsTangents = false;
  6648. material = result.materials[ objJSON.material ];
  6649. needsTangents = material instanceof THREE.ShaderMaterial;
  6650. pos = objJSON.position;
  6651. rot = objJSON.rotation;
  6652. scl = objJSON.scale;
  6653. mat = objJSON.matrix;
  6654. quat = objJSON.quaternion;
  6655. // use materials from the model file
  6656. // if there is no material specified in the object
  6657. if ( ! objJSON.material ) {
  6658. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6659. }
  6660. // use materials from the model file
  6661. // if there is just empty face material
  6662. // (must create new material as each model has its own face material)
  6663. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6664. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6665. }
  6666. if ( material instanceof THREE.MeshFaceMaterial ) {
  6667. for ( var i = 0; i < material.materials.length; i ++ ) {
  6668. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6669. }
  6670. }
  6671. if ( needsTangents ) {
  6672. geometry.computeTangents();
  6673. }
  6674. if ( objJSON.skin ) {
  6675. object = new THREE.SkinnedMesh( geometry, material );
  6676. } else if ( objJSON.morph ) {
  6677. object = new THREE.MorphAnimMesh( geometry, material );
  6678. if ( objJSON.duration !== undefined ) {
  6679. object.duration = objJSON.duration;
  6680. }
  6681. if ( objJSON.time !== undefined ) {
  6682. object.time = objJSON.time;
  6683. }
  6684. if ( objJSON.mirroredLoop !== undefined ) {
  6685. object.mirroredLoop = objJSON.mirroredLoop;
  6686. }
  6687. if ( material.morphNormals ) {
  6688. geometry.computeMorphNormals();
  6689. }
  6690. } else {
  6691. object = new THREE.Mesh( geometry, material );
  6692. }
  6693. object.name = objID;
  6694. if ( mat ) {
  6695. object.matrixAutoUpdate = false;
  6696. object.matrix.set(
  6697. mat[0], mat[1], mat[2], mat[3],
  6698. mat[4], mat[5], mat[6], mat[7],
  6699. mat[8], mat[9], mat[10], mat[11],
  6700. mat[12], mat[13], mat[14], mat[15]
  6701. );
  6702. } else {
  6703. object.position.fromArray( pos );
  6704. if ( quat ) {
  6705. object.quaternion.fromArray( quat );
  6706. object.useQuaternion = true;
  6707. } else {
  6708. object.rotation.fromArray( rot );
  6709. }
  6710. object.scale.fromArray( scl );
  6711. }
  6712. object.visible = objJSON.visible;
  6713. object.castShadow = objJSON.castShadow;
  6714. object.receiveShadow = objJSON.receiveShadow;
  6715. parent.add( object );
  6716. result.objects[ objID ] = object;
  6717. }
  6718. // lights
  6719. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6720. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6721. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6722. if ( objJSON.type === "DirectionalLight" ) {
  6723. pos = objJSON.direction;
  6724. light = new THREE.DirectionalLight( hex, intensity );
  6725. light.position.fromArray( pos );
  6726. if ( objJSON.target ) {
  6727. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6728. // kill existing default target
  6729. // otherwise it gets added to scene when parent gets added
  6730. light.target = null;
  6731. }
  6732. } else if ( objJSON.type === "PointLight" ) {
  6733. pos = objJSON.position;
  6734. dst = objJSON.distance;
  6735. light = new THREE.PointLight( hex, intensity, dst );
  6736. light.position.fromArray( pos );
  6737. } else if ( objJSON.type === "AmbientLight" ) {
  6738. light = new THREE.AmbientLight( hex );
  6739. }
  6740. parent.add( light );
  6741. light.name = objID;
  6742. result.lights[ objID ] = light;
  6743. result.objects[ objID ] = light;
  6744. // cameras
  6745. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6746. pos = objJSON.position;
  6747. rot = objJSON.rotation;
  6748. quat = objJSON.quaternion;
  6749. if ( objJSON.type === "PerspectiveCamera" ) {
  6750. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6751. } else if ( objJSON.type === "OrthographicCamera" ) {
  6752. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6753. }
  6754. camera.name = objID;
  6755. camera.position.fromArray( pos );
  6756. if ( quat !== undefined ) {
  6757. camera.quaternion.fromArray( quat );
  6758. camera.useQuaternion = true;
  6759. } else if ( rot !== undefined ) {
  6760. camera.rotation.fromArray( rot );
  6761. }
  6762. parent.add( camera );
  6763. result.cameras[ objID ] = camera;
  6764. result.objects[ objID ] = camera;
  6765. // pure Object3D
  6766. } else {
  6767. pos = objJSON.position;
  6768. rot = objJSON.rotation;
  6769. scl = objJSON.scale;
  6770. quat = objJSON.quaternion;
  6771. object = new THREE.Object3D();
  6772. object.name = objID;
  6773. object.position.fromArray( pos );
  6774. if ( quat ) {
  6775. object.quaternion.fromArray( quat );
  6776. object.useQuaternion = true;
  6777. } else {
  6778. object.rotation.fromArray( rot );
  6779. }
  6780. object.scale.fromArray( scl );
  6781. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6782. parent.add( object );
  6783. result.objects[ objID ] = object;
  6784. result.empties[ objID ] = object;
  6785. }
  6786. if ( object ) {
  6787. if ( objJSON.userData !== undefined ) {
  6788. for ( var key in objJSON.userData ) {
  6789. var value = objJSON.userData[ key ];
  6790. object.userData[ key ] = value;
  6791. }
  6792. }
  6793. if ( objJSON.groups !== undefined ) {
  6794. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6795. var groupID = objJSON.groups[ i ];
  6796. if ( result.groups[ groupID ] === undefined ) {
  6797. result.groups[ groupID ] = [];
  6798. }
  6799. result.groups[ groupID ].push( objID );
  6800. }
  6801. }
  6802. }
  6803. }
  6804. if ( object !== undefined && objJSON.children !== undefined ) {
  6805. handle_children( object, objJSON.children );
  6806. }
  6807. }
  6808. };
  6809. function handle_mesh( geo, mat, id ) {
  6810. result.geometries[ id ] = geo;
  6811. result.face_materials[ id ] = mat;
  6812. handle_objects();
  6813. };
  6814. function handle_hierarchy( node, id, parent, material, obj ) {
  6815. var p = obj.position;
  6816. var r = obj.rotation;
  6817. var q = obj.quaternion;
  6818. var s = obj.scale;
  6819. node.position.fromArray( p );
  6820. if ( q ) {
  6821. node.quaternion.fromArray( q );
  6822. node.useQuaternion = true;
  6823. } else {
  6824. node.rotation.fromArray( r );
  6825. }
  6826. node.scale.fromArray( s );
  6827. // override children materials
  6828. // if object material was specified in JSON explicitly
  6829. if ( material ) {
  6830. node.traverse( function ( child ) {
  6831. child.material = material;
  6832. } );
  6833. }
  6834. // override children visibility
  6835. // with root node visibility as specified in JSON
  6836. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6837. node.traverse( function ( child ) {
  6838. child.visible = visible;
  6839. } );
  6840. parent.add( node );
  6841. node.name = id;
  6842. result.objects[ id ] = node;
  6843. handle_objects();
  6844. };
  6845. function create_callback_geometry( id ) {
  6846. return function ( geo, mat ) {
  6847. geo.name = id;
  6848. handle_mesh( geo, mat, id );
  6849. counter_models -= 1;
  6850. scope.onLoadComplete();
  6851. async_callback_gate();
  6852. }
  6853. };
  6854. function create_callback_hierachy( id, parent, material, obj ) {
  6855. return function ( event ) {
  6856. var result;
  6857. // loaders which use EventDispatcher
  6858. if ( event.content ) {
  6859. result = event.content;
  6860. // ColladaLoader
  6861. } else if ( event.dae ) {
  6862. result = event.scene;
  6863. // UTF8Loader
  6864. } else {
  6865. result = event;
  6866. }
  6867. handle_hierarchy( result, id, parent, material, obj );
  6868. counter_models -= 1;
  6869. scope.onLoadComplete();
  6870. async_callback_gate();
  6871. }
  6872. };
  6873. function create_callback_embed( id ) {
  6874. return function ( geo, mat ) {
  6875. geo.name = id;
  6876. result.geometries[ id ] = geo;
  6877. result.face_materials[ id ] = mat;
  6878. }
  6879. };
  6880. function async_callback_gate() {
  6881. var progress = {
  6882. totalModels : total_models,
  6883. totalTextures : total_textures,
  6884. loadedModels : total_models - counter_models,
  6885. loadedTextures : total_textures - counter_textures
  6886. };
  6887. scope.callbackProgress( progress, result );
  6888. scope.onLoadProgress();
  6889. if ( counter_models === 0 && counter_textures === 0 ) {
  6890. finalize();
  6891. callbackFinished( result );
  6892. }
  6893. };
  6894. function finalize() {
  6895. // take care of targets which could be asynchronously loaded objects
  6896. for ( var i = 0; i < target_array.length; i ++ ) {
  6897. var ta = target_array[ i ];
  6898. var target = result.objects[ ta.targetName ];
  6899. if ( target ) {
  6900. ta.object.target = target;
  6901. } else {
  6902. // if there was error and target of specified name doesn't exist in the scene file
  6903. // create instead dummy target
  6904. // (target must be added to scene explicitly as parent is already added)
  6905. ta.object.target = new THREE.Object3D();
  6906. result.scene.add( ta.object.target );
  6907. }
  6908. ta.object.target.userData.targetInverse = ta.object;
  6909. }
  6910. };
  6911. var callbackTexture = function ( count ) {
  6912. counter_textures -= count;
  6913. async_callback_gate();
  6914. scope.onLoadComplete();
  6915. };
  6916. // must use this instead of just directly calling callbackTexture
  6917. // because of closure in the calling context loop
  6918. var generateTextureCallback = function ( count ) {
  6919. return function () {
  6920. callbackTexture( count );
  6921. };
  6922. };
  6923. function traverse_json_hierarchy( objJSON, callback ) {
  6924. callback( objJSON );
  6925. if ( objJSON.children !== undefined ) {
  6926. for ( var objChildID in objJSON.children ) {
  6927. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  6928. }
  6929. }
  6930. };
  6931. // first go synchronous elements
  6932. // fogs
  6933. var fogID, fogJSON;
  6934. for ( fogID in data.fogs ) {
  6935. fogJSON = data.fogs[ fogID ];
  6936. if ( fogJSON.type === "linear" ) {
  6937. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6938. } else if ( fogJSON.type === "exp2" ) {
  6939. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6940. }
  6941. color = fogJSON.color;
  6942. fog.color.setRGB( color[0], color[1], color[2] );
  6943. result.fogs[ fogID ] = fog;
  6944. }
  6945. // now come potentially asynchronous elements
  6946. // geometries
  6947. // count how many geometries will be loaded asynchronously
  6948. var geoID, geoJSON;
  6949. for ( geoID in data.geometries ) {
  6950. geoJSON = data.geometries[ geoID ];
  6951. if ( geoJSON.type in this.geometryHandlers ) {
  6952. counter_models += 1;
  6953. scope.onLoadStart();
  6954. }
  6955. }
  6956. // count how many hierarchies will be loaded asynchronously
  6957. for ( var objID in data.objects ) {
  6958. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  6959. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  6960. counter_models += 1;
  6961. scope.onLoadStart();
  6962. }
  6963. });
  6964. }
  6965. total_models = counter_models;
  6966. for ( geoID in data.geometries ) {
  6967. geoJSON = data.geometries[ geoID ];
  6968. if ( geoJSON.type === "cube" ) {
  6969. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6970. geometry.name = geoID;
  6971. result.geometries[ geoID ] = geometry;
  6972. } else if ( geoJSON.type === "plane" ) {
  6973. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6974. geometry.name = geoID;
  6975. result.geometries[ geoID ] = geometry;
  6976. } else if ( geoJSON.type === "sphere" ) {
  6977. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6978. geometry.name = geoID;
  6979. result.geometries[ geoID ] = geometry;
  6980. } else if ( geoJSON.type === "cylinder" ) {
  6981. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6982. geometry.name = geoID;
  6983. result.geometries[ geoID ] = geometry;
  6984. } else if ( geoJSON.type === "torus" ) {
  6985. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6986. geometry.name = geoID;
  6987. result.geometries[ geoID ] = geometry;
  6988. } else if ( geoJSON.type === "icosahedron" ) {
  6989. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6990. geometry.name = geoID;
  6991. result.geometries[ geoID ] = geometry;
  6992. } else if ( geoJSON.type in this.geometryHandlers ) {
  6993. var loaderParameters = {};
  6994. for ( var parType in geoJSON ) {
  6995. if ( parType !== "type" && parType !== "url" ) {
  6996. loaderParameters[ parType ] = geoJSON[ parType ];
  6997. }
  6998. }
  6999. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7000. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7001. } else if ( geoJSON.type === "embedded" ) {
  7002. var modelJson = data.embeds[ geoJSON.id ],
  7003. texture_path = "";
  7004. // pass metadata along to jsonLoader so it knows the format version
  7005. modelJson.metadata = data.metadata;
  7006. if ( modelJson ) {
  7007. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7008. var model = jsonLoader.parse( modelJson, texture_path );
  7009. create_callback_embed( geoID )( model.geometry, model.materials );
  7010. }
  7011. }
  7012. }
  7013. // textures
  7014. // count how many textures will be loaded asynchronously
  7015. var textureID, textureJSON;
  7016. for ( textureID in data.textures ) {
  7017. textureJSON = data.textures[ textureID ];
  7018. if ( textureJSON.url instanceof Array ) {
  7019. counter_textures += textureJSON.url.length;
  7020. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7021. scope.onLoadStart();
  7022. }
  7023. } else {
  7024. counter_textures += 1;
  7025. scope.onLoadStart();
  7026. }
  7027. }
  7028. total_textures = counter_textures;
  7029. for ( textureID in data.textures ) {
  7030. textureJSON = data.textures[ textureID ];
  7031. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7032. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7033. }
  7034. if ( textureJSON.url instanceof Array ) {
  7035. var count = textureJSON.url.length;
  7036. var url_array = [];
  7037. for( var i = 0; i < count; i ++ ) {
  7038. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7039. }
  7040. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7041. if ( isCompressed ) {
  7042. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7043. } else {
  7044. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7045. }
  7046. } else {
  7047. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7048. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7049. var textureCallback = generateTextureCallback( 1 );
  7050. if ( isCompressed ) {
  7051. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7052. } else {
  7053. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7054. }
  7055. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7056. texture.minFilter = THREE[ textureJSON.minFilter ];
  7057. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7058. texture.magFilter = THREE[ textureJSON.magFilter ];
  7059. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7060. if ( textureJSON.repeat ) {
  7061. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7062. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7063. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7064. }
  7065. if ( textureJSON.offset ) {
  7066. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7067. }
  7068. // handle wrap after repeat so that default repeat can be overriden
  7069. if ( textureJSON.wrap ) {
  7070. var wrapMap = {
  7071. "repeat": THREE.RepeatWrapping,
  7072. "mirror": THREE.MirroredRepeatWrapping
  7073. }
  7074. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7075. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7076. }
  7077. }
  7078. result.textures[ textureID ] = texture;
  7079. }
  7080. // materials
  7081. var matID, matJSON;
  7082. var parID;
  7083. for ( matID in data.materials ) {
  7084. matJSON = data.materials[ matID ];
  7085. for ( parID in matJSON.parameters ) {
  7086. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7087. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7088. } else if ( parID === "shading" ) {
  7089. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7090. } else if ( parID === "side" ) {
  7091. if ( matJSON.parameters[ parID ] == "double" ) {
  7092. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7093. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7094. matJSON.parameters[ parID ] = THREE.BackSide;
  7095. } else {
  7096. matJSON.parameters[ parID ] = THREE.FrontSide;
  7097. }
  7098. } else if ( parID === "blending" ) {
  7099. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7100. } else if ( parID === "combine" ) {
  7101. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7102. } else if ( parID === "vertexColors" ) {
  7103. if ( matJSON.parameters[ parID ] == "face" ) {
  7104. matJSON.parameters[ parID ] = THREE.FaceColors;
  7105. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7106. } else if ( matJSON.parameters[ parID ] ) {
  7107. matJSON.parameters[ parID ] = THREE.VertexColors;
  7108. }
  7109. } else if ( parID === "wrapRGB" ) {
  7110. var v3 = matJSON.parameters[ parID ];
  7111. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7112. }
  7113. }
  7114. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7115. matJSON.parameters.transparent = true;
  7116. }
  7117. if ( matJSON.parameters.normalMap ) {
  7118. var shader = THREE.ShaderLib[ "normalmap" ];
  7119. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7120. var diffuse = matJSON.parameters.color;
  7121. var specular = matJSON.parameters.specular;
  7122. var ambient = matJSON.parameters.ambient;
  7123. var shininess = matJSON.parameters.shininess;
  7124. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7125. if ( matJSON.parameters.normalScale ) {
  7126. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7127. }
  7128. if ( matJSON.parameters.map ) {
  7129. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7130. uniforms[ "enableDiffuse" ].value = true;
  7131. }
  7132. if ( matJSON.parameters.envMap ) {
  7133. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7134. uniforms[ "enableReflection" ].value = true;
  7135. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7136. }
  7137. if ( matJSON.parameters.lightMap ) {
  7138. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7139. uniforms[ "enableAO" ].value = true;
  7140. }
  7141. if ( matJSON.parameters.specularMap ) {
  7142. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7143. uniforms[ "enableSpecular" ].value = true;
  7144. }
  7145. if ( matJSON.parameters.displacementMap ) {
  7146. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7147. uniforms[ "enableDisplacement" ].value = true;
  7148. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7149. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7150. }
  7151. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7152. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7153. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7154. uniforms[ "uShininess" ].value = shininess;
  7155. if ( matJSON.parameters.opacity ) {
  7156. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7157. }
  7158. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7159. material = new THREE.ShaderMaterial( parameters );
  7160. } else {
  7161. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7162. }
  7163. material.name = matID;
  7164. result.materials[ matID ] = material;
  7165. }
  7166. // second pass through all materials to initialize MeshFaceMaterials
  7167. // that could be referring to other materials out of order
  7168. for ( matID in data.materials ) {
  7169. matJSON = data.materials[ matID ];
  7170. if ( matJSON.parameters.materials ) {
  7171. var materialArray = [];
  7172. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7173. var label = matJSON.parameters.materials[ i ];
  7174. materialArray.push( result.materials[ label ] );
  7175. }
  7176. result.materials[ matID ].materials = materialArray;
  7177. }
  7178. }
  7179. // objects ( synchronous init of procedural primitives )
  7180. handle_objects();
  7181. // defaults
  7182. if ( result.cameras && data.defaults.camera ) {
  7183. result.currentCamera = result.cameras[ data.defaults.camera ];
  7184. }
  7185. if ( result.fogs && data.defaults.fog ) {
  7186. result.scene.fog = result.fogs[ data.defaults.fog ];
  7187. }
  7188. // synchronous callback
  7189. scope.callbackSync( result );
  7190. // just in case there are no async elements
  7191. async_callback_gate();
  7192. }
  7193. }
  7194. /**
  7195. * @author mrdoob / http://mrdoob.com/
  7196. */
  7197. THREE.TextureLoader = function ( manager ) {
  7198. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7199. };
  7200. THREE.TextureLoader.prototype = {
  7201. constructor: THREE.TextureLoader,
  7202. load: function ( url, onLoad, onProgress, onError ) {
  7203. var scope = this;
  7204. var loader = new THREE.ImageLoader( scope.manager );
  7205. loader.setCrossOrigin( this.crossOrigin );
  7206. loader.load( url, function ( image ) {
  7207. var texture = new THREE.Texture( image );
  7208. texture.needsUpdate = true;
  7209. if ( onLoad !== undefined ) {
  7210. onLoad( texture );
  7211. }
  7212. } );
  7213. },
  7214. setCrossOrigin: function ( value ) {
  7215. this.crossOrigin = value;
  7216. }
  7217. };
  7218. /**
  7219. * @author mrdoob / http://mrdoob.com/
  7220. * @author alteredq / http://alteredqualia.com/
  7221. */
  7222. THREE.Material = function () {
  7223. this.id = THREE.Math.generateUUID();
  7224. this.name = '';
  7225. this.side = THREE.FrontSide;
  7226. this.opacity = 1;
  7227. this.transparent = false;
  7228. this.blending = THREE.NormalBlending;
  7229. this.blendSrc = THREE.SrcAlphaFactor;
  7230. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7231. this.blendEquation = THREE.AddEquation;
  7232. this.depthTest = true;
  7233. this.depthWrite = true;
  7234. this.polygonOffset = false;
  7235. this.polygonOffsetFactor = 0;
  7236. this.polygonOffsetUnits = 0;
  7237. this.alphaTest = 0;
  7238. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7239. this.visible = true;
  7240. this.needsUpdate = true;
  7241. };
  7242. THREE.Material.prototype = {
  7243. constructor: THREE.Material,
  7244. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  7245. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  7246. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  7247. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  7248. setValues: function ( values ) {
  7249. if ( values === undefined ) return;
  7250. for ( var key in values ) {
  7251. var newValue = values[ key ];
  7252. if ( newValue === undefined ) {
  7253. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7254. continue;
  7255. }
  7256. if ( key in this ) {
  7257. var currentValue = this[ key ];
  7258. if ( currentValue instanceof THREE.Color ) {
  7259. currentValue.set( newValue );
  7260. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7261. currentValue.copy( newValue );
  7262. } else if ( key == 'overdraw') {
  7263. // ensure overdraw is backwards-compatable with legacy boolean type
  7264. this[ key ] = Number(newValue);
  7265. } else {
  7266. this[ key ] = newValue;
  7267. }
  7268. }
  7269. }
  7270. },
  7271. clone: function ( material ) {
  7272. if ( material === undefined ) material = new THREE.Material();
  7273. material.name = this.name;
  7274. material.side = this.side;
  7275. material.opacity = this.opacity;
  7276. material.transparent = this.transparent;
  7277. material.blending = this.blending;
  7278. material.blendSrc = this.blendSrc;
  7279. material.blendDst = this.blendDst;
  7280. material.blendEquation = this.blendEquation;
  7281. material.depthTest = this.depthTest;
  7282. material.depthWrite = this.depthWrite;
  7283. material.polygonOffset = this.polygonOffset;
  7284. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7285. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7286. material.alphaTest = this.alphaTest;
  7287. material.overdraw = this.overdraw;
  7288. material.visible = this.visible;
  7289. return material;
  7290. },
  7291. dispose: function () {
  7292. this.dispatchEvent( { type: 'dispose' } );
  7293. }
  7294. };
  7295. /**
  7296. * @author mrdoob / http://mrdoob.com/
  7297. * @author alteredq / http://alteredqualia.com/
  7298. *
  7299. * parameters = {
  7300. * color: <hex>,
  7301. * opacity: <float>,
  7302. *
  7303. * blending: THREE.NormalBlending,
  7304. * depthTest: <bool>,
  7305. * depthWrite: <bool>,
  7306. *
  7307. * linewidth: <float>,
  7308. * linecap: "round",
  7309. * linejoin: "round",
  7310. *
  7311. * vertexColors: <bool>
  7312. *
  7313. * fog: <bool>
  7314. * }
  7315. */
  7316. THREE.LineBasicMaterial = function ( parameters ) {
  7317. THREE.Material.call( this );
  7318. this.color = new THREE.Color( 0xffffff );
  7319. this.linewidth = 1;
  7320. this.linecap = 'round';
  7321. this.linejoin = 'round';
  7322. this.vertexColors = false;
  7323. this.fog = true;
  7324. this.setValues( parameters );
  7325. };
  7326. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7327. THREE.LineBasicMaterial.prototype.clone = function () {
  7328. var material = new THREE.LineBasicMaterial();
  7329. THREE.Material.prototype.clone.call( this, material );
  7330. material.color.copy( this.color );
  7331. material.linewidth = this.linewidth;
  7332. material.linecap = this.linecap;
  7333. material.linejoin = this.linejoin;
  7334. material.vertexColors = this.vertexColors;
  7335. material.fog = this.fog;
  7336. return material;
  7337. };
  7338. /**
  7339. * @author alteredq / http://alteredqualia.com/
  7340. *
  7341. * parameters = {
  7342. * color: <hex>,
  7343. * opacity: <float>,
  7344. *
  7345. * blending: THREE.NormalBlending,
  7346. * depthTest: <bool>,
  7347. * depthWrite: <bool>,
  7348. *
  7349. * linewidth: <float>,
  7350. *
  7351. * scale: <float>,
  7352. * dashSize: <float>,
  7353. * gapSize: <float>,
  7354. *
  7355. * vertexColors: <bool>
  7356. *
  7357. * fog: <bool>
  7358. * }
  7359. */
  7360. THREE.LineDashedMaterial = function ( parameters ) {
  7361. THREE.Material.call( this );
  7362. this.color = new THREE.Color( 0xffffff );
  7363. this.linewidth = 1;
  7364. this.scale = 1;
  7365. this.dashSize = 3;
  7366. this.gapSize = 1;
  7367. this.vertexColors = false;
  7368. this.fog = true;
  7369. this.setValues( parameters );
  7370. };
  7371. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7372. THREE.LineDashedMaterial.prototype.clone = function () {
  7373. var material = new THREE.LineDashedMaterial();
  7374. THREE.Material.prototype.clone.call( this, material );
  7375. material.color.copy( this.color );
  7376. material.linewidth = this.linewidth;
  7377. material.scale = this.scale;
  7378. material.dashSize = this.dashSize;
  7379. material.gapSize = this.gapSize;
  7380. material.vertexColors = this.vertexColors;
  7381. material.fog = this.fog;
  7382. return material;
  7383. };
  7384. /**
  7385. * @author mrdoob / http://mrdoob.com/
  7386. * @author alteredq / http://alteredqualia.com/
  7387. *
  7388. * parameters = {
  7389. * color: <hex>,
  7390. * opacity: <float>,
  7391. * map: new THREE.Texture( <Image> ),
  7392. *
  7393. * lightMap: new THREE.Texture( <Image> ),
  7394. *
  7395. * specularMap: new THREE.Texture( <Image> ),
  7396. *
  7397. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7398. * combine: THREE.Multiply,
  7399. * reflectivity: <float>,
  7400. * refractionRatio: <float>,
  7401. *
  7402. * shading: THREE.SmoothShading,
  7403. * blending: THREE.NormalBlending,
  7404. * depthTest: <bool>,
  7405. * depthWrite: <bool>,
  7406. *
  7407. * wireframe: <boolean>,
  7408. * wireframeLinewidth: <float>,
  7409. *
  7410. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7411. *
  7412. * skinning: <bool>,
  7413. * morphTargets: <bool>,
  7414. *
  7415. * fog: <bool>
  7416. * }
  7417. */
  7418. THREE.MeshBasicMaterial = function ( parameters ) {
  7419. THREE.Material.call( this );
  7420. this.color = new THREE.Color( 0xffffff ); // emissive
  7421. this.map = null;
  7422. this.lightMap = null;
  7423. this.specularMap = null;
  7424. this.envMap = null;
  7425. this.combine = THREE.MultiplyOperation;
  7426. this.reflectivity = 1;
  7427. this.refractionRatio = 0.98;
  7428. this.fog = true;
  7429. this.shading = THREE.SmoothShading;
  7430. this.wireframe = false;
  7431. this.wireframeLinewidth = 1;
  7432. this.wireframeLinecap = 'round';
  7433. this.wireframeLinejoin = 'round';
  7434. this.vertexColors = THREE.NoColors;
  7435. this.skinning = false;
  7436. this.morphTargets = false;
  7437. this.setValues( parameters );
  7438. };
  7439. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7440. THREE.MeshBasicMaterial.prototype.clone = function () {
  7441. var material = new THREE.MeshBasicMaterial();
  7442. THREE.Material.prototype.clone.call( this, material );
  7443. material.color.copy( this.color );
  7444. material.map = this.map;
  7445. material.lightMap = this.lightMap;
  7446. material.specularMap = this.specularMap;
  7447. material.envMap = this.envMap;
  7448. material.combine = this.combine;
  7449. material.reflectivity = this.reflectivity;
  7450. material.refractionRatio = this.refractionRatio;
  7451. material.fog = this.fog;
  7452. material.shading = this.shading;
  7453. material.wireframe = this.wireframe;
  7454. material.wireframeLinewidth = this.wireframeLinewidth;
  7455. material.wireframeLinecap = this.wireframeLinecap;
  7456. material.wireframeLinejoin = this.wireframeLinejoin;
  7457. material.vertexColors = this.vertexColors;
  7458. material.skinning = this.skinning;
  7459. material.morphTargets = this.morphTargets;
  7460. return material;
  7461. };
  7462. /**
  7463. * @author mrdoob / http://mrdoob.com/
  7464. * @author alteredq / http://alteredqualia.com/
  7465. *
  7466. * parameters = {
  7467. * color: <hex>,
  7468. * ambient: <hex>,
  7469. * emissive: <hex>,
  7470. * opacity: <float>,
  7471. *
  7472. * map: new THREE.Texture( <Image> ),
  7473. *
  7474. * lightMap: new THREE.Texture( <Image> ),
  7475. *
  7476. * specularMap: new THREE.Texture( <Image> ),
  7477. *
  7478. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7479. * combine: THREE.Multiply,
  7480. * reflectivity: <float>,
  7481. * refractionRatio: <float>,
  7482. *
  7483. * shading: THREE.SmoothShading,
  7484. * blending: THREE.NormalBlending,
  7485. * depthTest: <bool>,
  7486. * depthWrite: <bool>,
  7487. *
  7488. * wireframe: <boolean>,
  7489. * wireframeLinewidth: <float>,
  7490. *
  7491. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7492. *
  7493. * skinning: <bool>,
  7494. * morphTargets: <bool>,
  7495. * morphNormals: <bool>,
  7496. *
  7497. * fog: <bool>
  7498. * }
  7499. */
  7500. THREE.MeshLambertMaterial = function ( parameters ) {
  7501. THREE.Material.call( this );
  7502. this.color = new THREE.Color( 0xffffff ); // diffuse
  7503. this.ambient = new THREE.Color( 0xffffff );
  7504. this.emissive = new THREE.Color( 0x000000 );
  7505. this.wrapAround = false;
  7506. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7507. this.map = null;
  7508. this.lightMap = null;
  7509. this.specularMap = null;
  7510. this.envMap = null;
  7511. this.combine = THREE.MultiplyOperation;
  7512. this.reflectivity = 1;
  7513. this.refractionRatio = 0.98;
  7514. this.fog = true;
  7515. this.shading = THREE.SmoothShading;
  7516. this.wireframe = false;
  7517. this.wireframeLinewidth = 1;
  7518. this.wireframeLinecap = 'round';
  7519. this.wireframeLinejoin = 'round';
  7520. this.vertexColors = THREE.NoColors;
  7521. this.skinning = false;
  7522. this.morphTargets = false;
  7523. this.morphNormals = false;
  7524. this.setValues( parameters );
  7525. };
  7526. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7527. THREE.MeshLambertMaterial.prototype.clone = function () {
  7528. var material = new THREE.MeshLambertMaterial();
  7529. THREE.Material.prototype.clone.call( this, material );
  7530. material.color.copy( this.color );
  7531. material.ambient.copy( this.ambient );
  7532. material.emissive.copy( this.emissive );
  7533. material.wrapAround = this.wrapAround;
  7534. material.wrapRGB.copy( this.wrapRGB );
  7535. material.map = this.map;
  7536. material.lightMap = this.lightMap;
  7537. material.specularMap = this.specularMap;
  7538. material.envMap = this.envMap;
  7539. material.combine = this.combine;
  7540. material.reflectivity = this.reflectivity;
  7541. material.refractionRatio = this.refractionRatio;
  7542. material.fog = this.fog;
  7543. material.shading = this.shading;
  7544. material.wireframe = this.wireframe;
  7545. material.wireframeLinewidth = this.wireframeLinewidth;
  7546. material.wireframeLinecap = this.wireframeLinecap;
  7547. material.wireframeLinejoin = this.wireframeLinejoin;
  7548. material.vertexColors = this.vertexColors;
  7549. material.skinning = this.skinning;
  7550. material.morphTargets = this.morphTargets;
  7551. material.morphNormals = this.morphNormals;
  7552. return material;
  7553. };
  7554. /**
  7555. * @author mrdoob / http://mrdoob.com/
  7556. * @author alteredq / http://alteredqualia.com/
  7557. *
  7558. * parameters = {
  7559. * color: <hex>,
  7560. * ambient: <hex>,
  7561. * emissive: <hex>,
  7562. * specular: <hex>,
  7563. * shininess: <float>,
  7564. * opacity: <float>,
  7565. *
  7566. * map: new THREE.Texture( <Image> ),
  7567. *
  7568. * lightMap: new THREE.Texture( <Image> ),
  7569. *
  7570. * bumpMap: new THREE.Texture( <Image> ),
  7571. * bumpScale: <float>,
  7572. *
  7573. * normalMap: new THREE.Texture( <Image> ),
  7574. * normalScale: <Vector2>,
  7575. *
  7576. * specularMap: new THREE.Texture( <Image> ),
  7577. *
  7578. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7579. * combine: THREE.Multiply,
  7580. * reflectivity: <float>,
  7581. * refractionRatio: <float>,
  7582. *
  7583. * shading: THREE.SmoothShading,
  7584. * blending: THREE.NormalBlending,
  7585. * depthTest: <bool>,
  7586. * depthWrite: <bool>,
  7587. *
  7588. * wireframe: <boolean>,
  7589. * wireframeLinewidth: <float>,
  7590. *
  7591. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7592. *
  7593. * skinning: <bool>,
  7594. * morphTargets: <bool>,
  7595. * morphNormals: <bool>,
  7596. *
  7597. * fog: <bool>
  7598. * }
  7599. */
  7600. THREE.MeshPhongMaterial = function ( parameters ) {
  7601. THREE.Material.call( this );
  7602. this.color = new THREE.Color( 0xffffff ); // diffuse
  7603. this.ambient = new THREE.Color( 0xffffff );
  7604. this.emissive = new THREE.Color( 0x000000 );
  7605. this.specular = new THREE.Color( 0x111111 );
  7606. this.shininess = 30;
  7607. this.metal = false;
  7608. this.perPixel = true;
  7609. this.wrapAround = false;
  7610. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7611. this.map = null;
  7612. this.lightMap = null;
  7613. this.bumpMap = null;
  7614. this.bumpScale = 1;
  7615. this.normalMap = null;
  7616. this.normalScale = new THREE.Vector2( 1, 1 );
  7617. this.specularMap = null;
  7618. this.envMap = null;
  7619. this.combine = THREE.MultiplyOperation;
  7620. this.reflectivity = 1;
  7621. this.refractionRatio = 0.98;
  7622. this.fog = true;
  7623. this.shading = THREE.SmoothShading;
  7624. this.wireframe = false;
  7625. this.wireframeLinewidth = 1;
  7626. this.wireframeLinecap = 'round';
  7627. this.wireframeLinejoin = 'round';
  7628. this.vertexColors = THREE.NoColors;
  7629. this.skinning = false;
  7630. this.morphTargets = false;
  7631. this.morphNormals = false;
  7632. this.setValues( parameters );
  7633. };
  7634. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7635. THREE.MeshPhongMaterial.prototype.clone = function () {
  7636. var material = new THREE.MeshPhongMaterial();
  7637. THREE.Material.prototype.clone.call( this, material );
  7638. material.color.copy( this.color );
  7639. material.ambient.copy( this.ambient );
  7640. material.emissive.copy( this.emissive );
  7641. material.specular.copy( this.specular );
  7642. material.shininess = this.shininess;
  7643. material.metal = this.metal;
  7644. material.perPixel = this.perPixel;
  7645. material.wrapAround = this.wrapAround;
  7646. material.wrapRGB.copy( this.wrapRGB );
  7647. material.map = this.map;
  7648. material.lightMap = this.lightMap;
  7649. material.bumpMap = this.bumpMap;
  7650. material.bumpScale = this.bumpScale;
  7651. material.normalMap = this.normalMap;
  7652. material.normalScale.copy( this.normalScale );
  7653. material.specularMap = this.specularMap;
  7654. material.envMap = this.envMap;
  7655. material.combine = this.combine;
  7656. material.reflectivity = this.reflectivity;
  7657. material.refractionRatio = this.refractionRatio;
  7658. material.fog = this.fog;
  7659. material.shading = this.shading;
  7660. material.wireframe = this.wireframe;
  7661. material.wireframeLinewidth = this.wireframeLinewidth;
  7662. material.wireframeLinecap = this.wireframeLinecap;
  7663. material.wireframeLinejoin = this.wireframeLinejoin;
  7664. material.vertexColors = this.vertexColors;
  7665. material.skinning = this.skinning;
  7666. material.morphTargets = this.morphTargets;
  7667. material.morphNormals = this.morphNormals;
  7668. return material;
  7669. };
  7670. /**
  7671. * @author mrdoob / http://mrdoob.com/
  7672. * @author alteredq / http://alteredqualia.com/
  7673. *
  7674. * parameters = {
  7675. * opacity: <float>,
  7676. *
  7677. * blending: THREE.NormalBlending,
  7678. * depthTest: <bool>,
  7679. * depthWrite: <bool>,
  7680. *
  7681. * wireframe: <boolean>,
  7682. * wireframeLinewidth: <float>
  7683. * }
  7684. */
  7685. THREE.MeshDepthMaterial = function ( parameters ) {
  7686. THREE.Material.call( this );
  7687. this.wireframe = false;
  7688. this.wireframeLinewidth = 1;
  7689. this.setValues( parameters );
  7690. };
  7691. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7692. THREE.MeshDepthMaterial.prototype.clone = function () {
  7693. var material = new THREE.MeshDepthMaterial();
  7694. THREE.Material.prototype.clone.call( this, material );
  7695. material.wireframe = this.wireframe;
  7696. material.wireframeLinewidth = this.wireframeLinewidth;
  7697. return material;
  7698. };
  7699. /**
  7700. * @author mrdoob / http://mrdoob.com/
  7701. *
  7702. * parameters = {
  7703. * opacity: <float>,
  7704. *
  7705. * shading: THREE.FlatShading,
  7706. * blending: THREE.NormalBlending,
  7707. * depthTest: <bool>,
  7708. * depthWrite: <bool>,
  7709. *
  7710. * wireframe: <boolean>,
  7711. * wireframeLinewidth: <float>
  7712. * }
  7713. */
  7714. THREE.MeshNormalMaterial = function ( parameters ) {
  7715. THREE.Material.call( this, parameters );
  7716. this.shading = THREE.FlatShading;
  7717. this.wireframe = false;
  7718. this.wireframeLinewidth = 1;
  7719. this.morphTargets = false;
  7720. this.setValues( parameters );
  7721. };
  7722. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7723. THREE.MeshNormalMaterial.prototype.clone = function () {
  7724. var material = new THREE.MeshNormalMaterial();
  7725. THREE.Material.prototype.clone.call( this, material );
  7726. material.shading = this.shading;
  7727. material.wireframe = this.wireframe;
  7728. material.wireframeLinewidth = this.wireframeLinewidth;
  7729. return material;
  7730. };
  7731. /**
  7732. * @author mrdoob / http://mrdoob.com/
  7733. */
  7734. THREE.MeshFaceMaterial = function ( materials ) {
  7735. this.materials = materials instanceof Array ? materials : [];
  7736. };
  7737. THREE.MeshFaceMaterial.prototype.clone = function () {
  7738. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7739. };
  7740. /**
  7741. * @author mrdoob / http://mrdoob.com/
  7742. * @author alteredq / http://alteredqualia.com/
  7743. *
  7744. * parameters = {
  7745. * color: <hex>,
  7746. * opacity: <float>,
  7747. * map: new THREE.Texture( <Image> ),
  7748. *
  7749. * size: <float>,
  7750. *
  7751. * blending: THREE.NormalBlending,
  7752. * depthTest: <bool>,
  7753. * depthWrite: <bool>,
  7754. *
  7755. * vertexColors: <bool>,
  7756. *
  7757. * fog: <bool>
  7758. * }
  7759. */
  7760. THREE.ParticleBasicMaterial = function ( parameters ) {
  7761. THREE.Material.call( this );
  7762. this.color = new THREE.Color( 0xffffff );
  7763. this.map = null;
  7764. this.size = 1;
  7765. this.sizeAttenuation = true;
  7766. this.vertexColors = false;
  7767. this.fog = true;
  7768. this.setValues( parameters );
  7769. };
  7770. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7771. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7772. var material = new THREE.ParticleBasicMaterial();
  7773. THREE.Material.prototype.clone.call( this, material );
  7774. material.color.copy( this.color );
  7775. material.map = this.map;
  7776. material.size = this.size;
  7777. material.sizeAttenuation = this.sizeAttenuation;
  7778. material.vertexColors = this.vertexColors;
  7779. material.fog = this.fog;
  7780. return material;
  7781. };
  7782. /**
  7783. * @author mrdoob / http://mrdoob.com/
  7784. *
  7785. * parameters = {
  7786. * color: <hex>,
  7787. * program: <function>,
  7788. * opacity: <float>,
  7789. * blending: THREE.NormalBlending
  7790. * }
  7791. */
  7792. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7793. THREE.Material.call( this );
  7794. this.color = new THREE.Color( 0xffffff );
  7795. this.program = function ( context, color ) {};
  7796. this.setValues( parameters );
  7797. };
  7798. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7799. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7800. var material = new THREE.ParticleCanvasMaterial();
  7801. THREE.Material.prototype.clone.call( this, material );
  7802. material.color.copy( this.color );
  7803. material.program = this.program;
  7804. return material;
  7805. };
  7806. /**
  7807. * @author alteredq / http://alteredqualia.com/
  7808. *
  7809. * parameters = {
  7810. * fragmentShader: <string>,
  7811. * vertexShader: <string>,
  7812. *
  7813. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7814. *
  7815. * defines: { "label" : "value" },
  7816. *
  7817. * shading: THREE.SmoothShading,
  7818. * blending: THREE.NormalBlending,
  7819. * depthTest: <bool>,
  7820. * depthWrite: <bool>,
  7821. *
  7822. * wireframe: <boolean>,
  7823. * wireframeLinewidth: <float>,
  7824. *
  7825. * lights: <bool>,
  7826. *
  7827. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7828. *
  7829. * skinning: <bool>,
  7830. * morphTargets: <bool>,
  7831. * morphNormals: <bool>,
  7832. *
  7833. * fog: <bool>
  7834. * }
  7835. */
  7836. THREE.ShaderMaterial = function ( parameters ) {
  7837. THREE.Material.call( this );
  7838. this.fragmentShader = "void main() {}";
  7839. this.vertexShader = "void main() {}";
  7840. this.uniforms = {};
  7841. this.defines = {};
  7842. this.attributes = null;
  7843. this.shading = THREE.SmoothShading;
  7844. this.linewidth = 1;
  7845. this.wireframe = false;
  7846. this.wireframeLinewidth = 1;
  7847. this.fog = false; // set to use scene fog
  7848. this.lights = false; // set to use scene lights
  7849. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7850. this.skinning = false; // set to use skinning attribute streams
  7851. this.morphTargets = false; // set to use morph targets
  7852. this.morphNormals = false; // set to use morph normals
  7853. this.setValues( parameters );
  7854. };
  7855. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7856. THREE.ShaderMaterial.prototype.clone = function () {
  7857. var material = new THREE.ShaderMaterial();
  7858. THREE.Material.prototype.clone.call( this, material );
  7859. material.fragmentShader = this.fragmentShader;
  7860. material.vertexShader = this.vertexShader;
  7861. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7862. material.attributes = this.attributes;
  7863. material.defines = this.defines;
  7864. material.shading = this.shading;
  7865. material.wireframe = this.wireframe;
  7866. material.wireframeLinewidth = this.wireframeLinewidth;
  7867. material.fog = this.fog;
  7868. material.lights = this.lights;
  7869. material.vertexColors = this.vertexColors;
  7870. material.skinning = this.skinning;
  7871. material.morphTargets = this.morphTargets;
  7872. material.morphNormals = this.morphNormals;
  7873. return material;
  7874. };
  7875. /**
  7876. * @author alteredq / http://alteredqualia.com/
  7877. *
  7878. * parameters = {
  7879. * color: <hex>,
  7880. * opacity: <float>,
  7881. * map: new THREE.Texture( <Image> ),
  7882. *
  7883. * blending: THREE.NormalBlending,
  7884. * depthTest: <bool>,
  7885. * depthWrite: <bool>,
  7886. *
  7887. * useScreenCoordinates: <bool>,
  7888. * sizeAttenuation: <bool>,
  7889. * scaleByViewport: <bool>,
  7890. * alignment: THREE.SpriteAlignment.center,
  7891. *
  7892. * uvOffset: new THREE.Vector2(),
  7893. * uvScale: new THREE.Vector2(),
  7894. *
  7895. * fog: <bool>
  7896. * }
  7897. */
  7898. THREE.SpriteMaterial = function ( parameters ) {
  7899. THREE.Material.call( this );
  7900. // defaults
  7901. this.color = new THREE.Color( 0xffffff );
  7902. this.map = new THREE.Texture();
  7903. this.useScreenCoordinates = true;
  7904. this.depthTest = !this.useScreenCoordinates;
  7905. this.sizeAttenuation = !this.useScreenCoordinates;
  7906. this.scaleByViewport = !this.sizeAttenuation;
  7907. this.alignment = THREE.SpriteAlignment.center.clone();
  7908. this.fog = false;
  7909. this.uvOffset = new THREE.Vector2( 0, 0 );
  7910. this.uvScale = new THREE.Vector2( 1, 1 );
  7911. // set parameters
  7912. this.setValues( parameters );
  7913. // override coupled defaults if not specified explicitly by parameters
  7914. parameters = parameters || {};
  7915. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7916. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7917. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7918. };
  7919. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7920. THREE.SpriteMaterial.prototype.clone = function () {
  7921. var material = new THREE.SpriteMaterial();
  7922. THREE.Material.prototype.clone.call( this, material );
  7923. material.color.copy( this.color );
  7924. material.map = this.map;
  7925. material.useScreenCoordinates = this.useScreenCoordinates;
  7926. material.sizeAttenuation = this.sizeAttenuation;
  7927. material.scaleByViewport = this.scaleByViewport;
  7928. material.alignment.copy( this.alignment );
  7929. material.uvOffset.copy( this.uvOffset );
  7930. material.uvScale.copy( this.uvScale );
  7931. material.fog = this.fog;
  7932. return material;
  7933. };
  7934. // Alignment enums
  7935. THREE.SpriteAlignment = {};
  7936. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7937. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7938. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7939. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7940. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7941. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7942. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7943. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7944. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7945. /**
  7946. * @author mrdoob / http://mrdoob.com/
  7947. * @author alteredq / http://alteredqualia.com/
  7948. * @author szimek / https://github.com/szimek/
  7949. */
  7950. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7951. this.id = THREE.Math.generateUUID();
  7952. this.name = '';
  7953. this.image = image;
  7954. this.mipmaps = [];
  7955. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7956. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7957. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7958. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7959. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7960. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7961. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7962. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7963. this.offset = new THREE.Vector2( 0, 0 );
  7964. this.repeat = new THREE.Vector2( 1, 1 );
  7965. this.generateMipmaps = true;
  7966. this.premultiplyAlpha = false;
  7967. this.flipY = true;
  7968. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7969. this.needsUpdate = false;
  7970. this.onUpdate = null;
  7971. };
  7972. THREE.Texture.prototype = {
  7973. constructor: THREE.Texture,
  7974. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  7975. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  7976. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  7977. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  7978. clone: function ( texture ) {
  7979. if ( texture === undefined ) texture = new THREE.Texture();
  7980. texture.image = this.image;
  7981. texture.mipmaps = this.mipmaps.slice(0);
  7982. texture.mapping = this.mapping;
  7983. texture.wrapS = this.wrapS;
  7984. texture.wrapT = this.wrapT;
  7985. texture.magFilter = this.magFilter;
  7986. texture.minFilter = this.minFilter;
  7987. texture.anisotropy = this.anisotropy;
  7988. texture.format = this.format;
  7989. texture.type = this.type;
  7990. texture.offset.copy( this.offset );
  7991. texture.repeat.copy( this.repeat );
  7992. texture.generateMipmaps = this.generateMipmaps;
  7993. texture.premultiplyAlpha = this.premultiplyAlpha;
  7994. texture.flipY = this.flipY;
  7995. texture.unpackAlignment = this.unpackAlignment;
  7996. return texture;
  7997. },
  7998. dispose: function () {
  7999. this.dispatchEvent( { type: 'dispose' } );
  8000. }
  8001. };
  8002. /**
  8003. * @author alteredq / http://alteredqualia.com/
  8004. */
  8005. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8006. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8007. this.image = { width: width, height: height };
  8008. this.mipmaps = mipmaps;
  8009. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8010. };
  8011. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8012. THREE.CompressedTexture.prototype.clone = function () {
  8013. var texture = new THREE.CompressedTexture();
  8014. THREE.Texture.prototype.clone.call( this, texture );
  8015. return texture;
  8016. };
  8017. /**
  8018. * @author alteredq / http://alteredqualia.com/
  8019. */
  8020. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8021. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8022. this.image = { data: data, width: width, height: height };
  8023. };
  8024. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8025. THREE.DataTexture.prototype.clone = function () {
  8026. var texture = new THREE.DataTexture();
  8027. THREE.Texture.prototype.clone.call( this, texture );
  8028. return texture;
  8029. };
  8030. /**
  8031. * @author mrdoob / http://mrdoob.com/
  8032. */
  8033. THREE.Particle = function ( material ) {
  8034. THREE.Object3D.call( this );
  8035. this.material = material;
  8036. };
  8037. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  8038. THREE.Particle.prototype.clone = function ( object ) {
  8039. if ( object === undefined ) object = new THREE.Particle( this.material );
  8040. THREE.Object3D.prototype.clone.call( this, object );
  8041. return object;
  8042. };
  8043. /**
  8044. * @author alteredq / http://alteredqualia.com/
  8045. */
  8046. THREE.ParticleSystem = function ( geometry, material ) {
  8047. THREE.Object3D.call( this );
  8048. this.geometry = geometry;
  8049. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  8050. this.sortParticles = false;
  8051. if ( this.geometry ) {
  8052. // calc bound radius
  8053. if( this.geometry.boundingSphere === null ) {
  8054. this.geometry.computeBoundingSphere();
  8055. }
  8056. }
  8057. this.frustumCulled = false;
  8058. };
  8059. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8060. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8061. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8062. object.sortParticles = this.sortParticles;
  8063. THREE.Object3D.prototype.clone.call( this, object );
  8064. return object;
  8065. };
  8066. /**
  8067. * @author mrdoob / http://mrdoob.com/
  8068. */
  8069. THREE.Line = function ( geometry, material, type ) {
  8070. THREE.Object3D.call( this );
  8071. this.geometry = geometry;
  8072. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8073. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8074. if ( this.geometry ) {
  8075. if ( ! this.geometry.boundingSphere ) {
  8076. this.geometry.computeBoundingSphere();
  8077. }
  8078. }
  8079. };
  8080. THREE.LineStrip = 0;
  8081. THREE.LinePieces = 1;
  8082. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8083. THREE.Line.prototype.clone = function ( object ) {
  8084. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8085. THREE.Object3D.prototype.clone.call( this, object );
  8086. return object;
  8087. };
  8088. /**
  8089. * @author mrdoob / http://mrdoob.com/
  8090. * @author alteredq / http://alteredqualia.com/
  8091. * @author mikael emtinger / http://gomo.se/
  8092. * @author jonobr1 / http://jonobr1.com/
  8093. */
  8094. THREE.Mesh = function ( geometry, material ) {
  8095. THREE.Object3D.call( this );
  8096. this.geometry = null;
  8097. this.material = null;
  8098. this.setGeometry( geometry );
  8099. this.setMaterial( material );
  8100. };
  8101. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8102. THREE.Mesh.prototype.setGeometry = function ( geometry ) {
  8103. if ( geometry !== undefined ) {
  8104. this.geometry = geometry;
  8105. if ( this.geometry.boundingSphere === null ) {
  8106. this.geometry.computeBoundingSphere();
  8107. }
  8108. this.updateMorphTargets();
  8109. }
  8110. };
  8111. THREE.Mesh.prototype.setMaterial = function ( material ) {
  8112. if ( material !== undefined ) {
  8113. this.material = material;
  8114. } else {
  8115. this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  8116. }
  8117. };
  8118. THREE.Mesh.prototype.updateMorphTargets = function () {
  8119. if ( this.geometry.morphTargets.length > 0 ) {
  8120. this.morphTargetBase = -1;
  8121. this.morphTargetForcedOrder = [];
  8122. this.morphTargetInfluences = [];
  8123. this.morphTargetDictionary = {};
  8124. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8125. this.morphTargetInfluences.push( 0 );
  8126. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8127. }
  8128. }
  8129. };
  8130. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8131. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8132. return this.morphTargetDictionary[ name ];
  8133. }
  8134. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8135. return 0;
  8136. };
  8137. THREE.Mesh.prototype.clone = function ( object ) {
  8138. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8139. THREE.Object3D.prototype.clone.call( this, object );
  8140. return object;
  8141. };
  8142. /**
  8143. * @author mikael emtinger / http://gomo.se/
  8144. * @author alteredq / http://alteredqualia.com/
  8145. */
  8146. THREE.Bone = function( belongsToSkin ) {
  8147. THREE.Object3D.call( this );
  8148. this.skin = belongsToSkin;
  8149. this.skinMatrix = new THREE.Matrix4();
  8150. };
  8151. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8152. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8153. // update local
  8154. if ( this.matrixAutoUpdate ) {
  8155. forceUpdate |= this.updateMatrix();
  8156. }
  8157. // update skin matrix
  8158. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8159. if( parentSkinMatrix ) {
  8160. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8161. } else {
  8162. this.skinMatrix.copy( this.matrix );
  8163. }
  8164. this.matrixWorldNeedsUpdate = false;
  8165. forceUpdate = true;
  8166. }
  8167. // update children
  8168. var child, i, l = this.children.length;
  8169. for ( i = 0; i < l; i ++ ) {
  8170. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8171. }
  8172. };
  8173. /**
  8174. * @author mikael emtinger / http://gomo.se/
  8175. * @author alteredq / http://alteredqualia.com/
  8176. */
  8177. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8178. THREE.Mesh.call( this, geometry, material );
  8179. //
  8180. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8181. // init bones
  8182. this.identityMatrix = new THREE.Matrix4();
  8183. this.bones = [];
  8184. this.boneMatrices = [];
  8185. var b, bone, gbone, p, q, s;
  8186. if ( this.geometry && this.geometry.bones !== undefined ) {
  8187. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8188. gbone = this.geometry.bones[ b ];
  8189. p = gbone.pos;
  8190. q = gbone.rotq;
  8191. s = gbone.scl;
  8192. bone = this.addBone();
  8193. bone.name = gbone.name;
  8194. bone.position.set( p[0], p[1], p[2] );
  8195. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8196. bone.useQuaternion = true;
  8197. if ( s !== undefined ) {
  8198. bone.scale.set( s[0], s[1], s[2] );
  8199. } else {
  8200. bone.scale.set( 1, 1, 1 );
  8201. }
  8202. }
  8203. for ( b = 0; b < this.bones.length; b ++ ) {
  8204. gbone = this.geometry.bones[ b ];
  8205. bone = this.bones[ b ];
  8206. if ( gbone.parent === -1 ) {
  8207. this.add( bone );
  8208. } else {
  8209. this.bones[ gbone.parent ].add( bone );
  8210. }
  8211. }
  8212. //
  8213. var nBones = this.bones.length;
  8214. if ( this.useVertexTexture ) {
  8215. // layout (1 matrix = 4 pixels)
  8216. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8217. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8218. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8219. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8220. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8221. var size;
  8222. if ( nBones > 256 )
  8223. size = 64;
  8224. else if ( nBones > 64 )
  8225. size = 32;
  8226. else if ( nBones > 16 )
  8227. size = 16;
  8228. else
  8229. size = 8;
  8230. this.boneTextureWidth = size;
  8231. this.boneTextureHeight = size;
  8232. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8233. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8234. this.boneTexture.minFilter = THREE.NearestFilter;
  8235. this.boneTexture.magFilter = THREE.NearestFilter;
  8236. this.boneTexture.generateMipmaps = false;
  8237. this.boneTexture.flipY = false;
  8238. } else {
  8239. this.boneMatrices = new Float32Array( 16 * nBones );
  8240. }
  8241. this.pose();
  8242. }
  8243. };
  8244. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8245. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8246. if ( bone === undefined ) {
  8247. bone = new THREE.Bone( this );
  8248. }
  8249. this.bones.push( bone );
  8250. return bone;
  8251. };
  8252. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8253. var offsetMatrix = new THREE.Matrix4();
  8254. return function ( force ) {
  8255. this.matrixAutoUpdate && this.updateMatrix();
  8256. // update matrixWorld
  8257. if ( this.matrixWorldNeedsUpdate || force ) {
  8258. if ( this.parent ) {
  8259. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8260. } else {
  8261. this.matrixWorld.copy( this.matrix );
  8262. }
  8263. this.matrixWorldNeedsUpdate = false;
  8264. force = true;
  8265. }
  8266. // update children
  8267. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8268. var child = this.children[ i ];
  8269. if ( child instanceof THREE.Bone ) {
  8270. child.update( this.identityMatrix, false );
  8271. } else {
  8272. child.updateMatrixWorld( true );
  8273. }
  8274. }
  8275. // make a snapshot of the bones' rest position
  8276. if ( this.boneInverses == undefined ) {
  8277. this.boneInverses = [];
  8278. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8279. var inverse = new THREE.Matrix4();
  8280. inverse.getInverse( this.bones[ b ].skinMatrix );
  8281. this.boneInverses.push( inverse );
  8282. }
  8283. }
  8284. // flatten bone matrices to array
  8285. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8286. // compute the offset between the current and the original transform;
  8287. // TODO: we could get rid of this multiplication step if the skinMatrix
  8288. // was already representing the offset; however, this requires some
  8289. // major changes to the animation system
  8290. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8291. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8292. }
  8293. if ( this.useVertexTexture ) {
  8294. this.boneTexture.needsUpdate = true;
  8295. }
  8296. };
  8297. }();
  8298. THREE.SkinnedMesh.prototype.pose = function () {
  8299. this.updateMatrixWorld( true );
  8300. this.normalizeSkinWeights();
  8301. };
  8302. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8303. if ( this.geometry instanceof THREE.Geometry ) {
  8304. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8305. var sw = this.geometry.skinWeights[ i ];
  8306. var scale = 1.0 / sw.lengthManhattan();
  8307. if ( scale !== Infinity ) {
  8308. sw.multiplyScalar( scale );
  8309. } else {
  8310. sw.set( 1 ); // this will be normalized by the shader anyway
  8311. }
  8312. }
  8313. } else {
  8314. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8315. }
  8316. };
  8317. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8318. if ( object === undefined ) {
  8319. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8320. }
  8321. THREE.Mesh.prototype.clone.call( this, object );
  8322. return object;
  8323. };
  8324. /**
  8325. * @author alteredq / http://alteredqualia.com/
  8326. */
  8327. THREE.MorphAnimMesh = function ( geometry, material ) {
  8328. THREE.Mesh.call( this, geometry, material );
  8329. // API
  8330. this.duration = 1000; // milliseconds
  8331. this.mirroredLoop = false;
  8332. this.time = 0;
  8333. // internals
  8334. this.lastKeyframe = 0;
  8335. this.currentKeyframe = 0;
  8336. this.direction = 1;
  8337. this.directionBackwards = false;
  8338. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8339. };
  8340. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8341. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8342. this.startKeyframe = start;
  8343. this.endKeyframe = end;
  8344. this.length = this.endKeyframe - this.startKeyframe + 1;
  8345. };
  8346. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8347. this.direction = 1;
  8348. this.directionBackwards = false;
  8349. };
  8350. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8351. this.direction = -1;
  8352. this.directionBackwards = true;
  8353. };
  8354. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8355. var geometry = this.geometry;
  8356. if ( ! geometry.animations ) geometry.animations = {};
  8357. var firstAnimation, animations = geometry.animations;
  8358. var pattern = /([a-z]+)(\d+)/;
  8359. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8360. var morph = geometry.morphTargets[ i ];
  8361. var parts = morph.name.match( pattern );
  8362. if ( parts && parts.length > 1 ) {
  8363. var label = parts[ 1 ];
  8364. var num = parts[ 2 ];
  8365. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8366. var animation = animations[ label ];
  8367. if ( i < animation.start ) animation.start = i;
  8368. if ( i > animation.end ) animation.end = i;
  8369. if ( ! firstAnimation ) firstAnimation = label;
  8370. }
  8371. }
  8372. geometry.firstAnimation = firstAnimation;
  8373. };
  8374. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8375. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8376. this.geometry.animations[ label ] = { start: start, end: end };
  8377. };
  8378. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8379. var animation = this.geometry.animations[ label ];
  8380. if ( animation ) {
  8381. this.setFrameRange( animation.start, animation.end );
  8382. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8383. this.time = 0;
  8384. } else {
  8385. console.warn( "animation[" + label + "] undefined" );
  8386. }
  8387. };
  8388. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8389. var frameTime = this.duration / this.length;
  8390. this.time += this.direction * delta;
  8391. if ( this.mirroredLoop ) {
  8392. if ( this.time > this.duration || this.time < 0 ) {
  8393. this.direction *= -1;
  8394. if ( this.time > this.duration ) {
  8395. this.time = this.duration;
  8396. this.directionBackwards = true;
  8397. }
  8398. if ( this.time < 0 ) {
  8399. this.time = 0;
  8400. this.directionBackwards = false;
  8401. }
  8402. }
  8403. } else {
  8404. this.time = this.time % this.duration;
  8405. if ( this.time < 0 ) this.time += this.duration;
  8406. }
  8407. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8408. if ( keyframe !== this.currentKeyframe ) {
  8409. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8410. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8411. this.morphTargetInfluences[ keyframe ] = 0;
  8412. this.lastKeyframe = this.currentKeyframe;
  8413. this.currentKeyframe = keyframe;
  8414. }
  8415. var mix = ( this.time % frameTime ) / frameTime;
  8416. if ( this.directionBackwards ) {
  8417. mix = 1 - mix;
  8418. }
  8419. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8420. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8421. };
  8422. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8423. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8424. object.duration = this.duration;
  8425. object.mirroredLoop = this.mirroredLoop;
  8426. object.time = this.time;
  8427. object.lastKeyframe = this.lastKeyframe;
  8428. object.currentKeyframe = this.currentKeyframe;
  8429. object.direction = this.direction;
  8430. object.directionBackwards = this.directionBackwards;
  8431. THREE.Mesh.prototype.clone.call( this, object );
  8432. return object;
  8433. };
  8434. /**
  8435. * @author alteredq / http://alteredqualia.com/
  8436. */
  8437. THREE.Ribbon = function ( geometry, material ) {
  8438. THREE.Object3D.call( this );
  8439. this.geometry = geometry;
  8440. this.material = material;
  8441. };
  8442. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8443. THREE.Ribbon.prototype.clone = function ( object ) {
  8444. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8445. THREE.Object3D.prototype.clone.call( this, object );
  8446. return object;
  8447. };
  8448. /**
  8449. * @author mikael emtinger / http://gomo.se/
  8450. * @author alteredq / http://alteredqualia.com/
  8451. * @author mrdoob / http://mrdoob.com/
  8452. */
  8453. THREE.LOD = function () {
  8454. THREE.Object3D.call( this );
  8455. this.objects = [];
  8456. };
  8457. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8458. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8459. if ( distance === undefined ) distance = 0;
  8460. distance = Math.abs( distance );
  8461. for ( var l = 0; l < this.objects.length; l ++ ) {
  8462. if ( distance < this.objects[ l ].distance ) {
  8463. break;
  8464. }
  8465. }
  8466. this.objects.splice( l, 0, { distance: distance, object: object } );
  8467. this.add( object );
  8468. };
  8469. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8470. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8471. if ( distance < this.objects[ i ].distance ) {
  8472. break;
  8473. }
  8474. }
  8475. return this.objects[ i - 1 ].object;
  8476. };
  8477. THREE.LOD.prototype.update = function () {
  8478. var v1 = new THREE.Vector3();
  8479. var v2 = new THREE.Vector3();
  8480. return function ( camera ) {
  8481. if ( this.objects.length > 1 ) {
  8482. v1.getPositionFromMatrix( camera.matrixWorld );
  8483. v2.getPositionFromMatrix( this.matrixWorld );
  8484. var distance = v1.distanceTo( v2 );
  8485. this.objects[ 0 ].object.visible = true;
  8486. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8487. if ( distance >= this.objects[ i ].distance ) {
  8488. this.objects[ i - 1 ].object.visible = false;
  8489. this.objects[ i ].object.visible = true;
  8490. } else {
  8491. break;
  8492. }
  8493. }
  8494. for( ; i < l; i ++ ) {
  8495. this.objects[ i ].object.visible = false;
  8496. }
  8497. }
  8498. };
  8499. }();
  8500. THREE.LOD.prototype.clone = function () {
  8501. // TODO
  8502. };
  8503. /**
  8504. * @author mikael emtinger / http://gomo.se/
  8505. * @author alteredq / http://alteredqualia.com/
  8506. */
  8507. THREE.Sprite = function ( material ) {
  8508. THREE.Object3D.call( this );
  8509. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8510. this.rotation3d = this.rotation;
  8511. this.rotation = 0;
  8512. };
  8513. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8514. /*
  8515. * Custom update matrix
  8516. */
  8517. THREE.Sprite.prototype.updateMatrix = function () {
  8518. this.rotation3d.set( 0, 0, this.rotation );
  8519. this.quaternion.setFromEuler( this.rotation3d, this.eulerOrder );
  8520. this.matrix.makeFromPositionQuaternionScale( this.position, this.quaternion, this.scale );
  8521. this.matrixWorldNeedsUpdate = true;
  8522. };
  8523. THREE.Sprite.prototype.clone = function ( object ) {
  8524. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8525. THREE.Object3D.prototype.clone.call( this, object );
  8526. return object;
  8527. };
  8528. /**
  8529. * @author mrdoob / http://mrdoob.com/
  8530. */
  8531. THREE.Scene = function () {
  8532. THREE.Object3D.call( this );
  8533. this.fog = null;
  8534. this.overrideMaterial = null;
  8535. this.autoUpdate = true; // checked by the renderer
  8536. this.matrixAutoUpdate = false;
  8537. this.__objects = [];
  8538. this.__lights = [];
  8539. this.__objectsAdded = [];
  8540. this.__objectsRemoved = [];
  8541. };
  8542. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8543. THREE.Scene.prototype.__addObject = function ( object ) {
  8544. if ( object instanceof THREE.Light ) {
  8545. if ( this.__lights.indexOf( object ) === - 1 ) {
  8546. this.__lights.push( object );
  8547. }
  8548. if ( object.target && object.target.parent === undefined ) {
  8549. this.add( object.target );
  8550. }
  8551. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8552. if ( this.__objects.indexOf( object ) === - 1 ) {
  8553. this.__objects.push( object );
  8554. this.__objectsAdded.push( object );
  8555. // check if previously removed
  8556. var i = this.__objectsRemoved.indexOf( object );
  8557. if ( i !== -1 ) {
  8558. this.__objectsRemoved.splice( i, 1 );
  8559. }
  8560. }
  8561. }
  8562. for ( var c = 0; c < object.children.length; c ++ ) {
  8563. this.__addObject( object.children[ c ] );
  8564. }
  8565. };
  8566. THREE.Scene.prototype.__removeObject = function ( object ) {
  8567. if ( object instanceof THREE.Light ) {
  8568. var i = this.__lights.indexOf( object );
  8569. if ( i !== -1 ) {
  8570. this.__lights.splice( i, 1 );
  8571. }
  8572. } else if ( !( object instanceof THREE.Camera ) ) {
  8573. var i = this.__objects.indexOf( object );
  8574. if( i !== -1 ) {
  8575. this.__objects.splice( i, 1 );
  8576. this.__objectsRemoved.push( object );
  8577. // check if previously added
  8578. var ai = this.__objectsAdded.indexOf( object );
  8579. if ( ai !== -1 ) {
  8580. this.__objectsAdded.splice( ai, 1 );
  8581. }
  8582. }
  8583. }
  8584. for ( var c = 0; c < object.children.length; c ++ ) {
  8585. this.__removeObject( object.children[ c ] );
  8586. }
  8587. };
  8588. THREE.Scene.prototype.clone = function ( object ) {
  8589. if ( object === undefined ) object = new THREE.Scene();
  8590. THREE.Object3D.prototype.clone.call(this, object);
  8591. if ( this.fog !== null ) object.fog = this.fog.clone();
  8592. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  8593. object.autoUpdate = this.autoUpdate;
  8594. object.matrixAutoUpdate = this.matrixAutoUpdate;
  8595. return object;
  8596. };
  8597. /**
  8598. * @author mrdoob / http://mrdoob.com/
  8599. * @author alteredq / http://alteredqualia.com/
  8600. */
  8601. THREE.Fog = function ( hex, near, far ) {
  8602. this.name = '';
  8603. this.color = new THREE.Color( hex );
  8604. this.near = ( near !== undefined ) ? near : 1;
  8605. this.far = ( far !== undefined ) ? far : 1000;
  8606. };
  8607. THREE.Fog.prototype.clone = function () {
  8608. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8609. };
  8610. /**
  8611. * @author mrdoob / http://mrdoob.com/
  8612. * @author alteredq / http://alteredqualia.com/
  8613. */
  8614. THREE.FogExp2 = function ( hex, density ) {
  8615. this.name = '';
  8616. this.color = new THREE.Color( hex );
  8617. this.density = ( density !== undefined ) ? density : 0.00025;
  8618. };
  8619. THREE.FogExp2.prototype.clone = function () {
  8620. return new THREE.FogExp2( this.color.getHex(), this.density );
  8621. };
  8622. /**
  8623. * @author mrdoob / http://mrdoob.com/
  8624. */
  8625. THREE.CanvasRenderer = function ( parameters ) {
  8626. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8627. var smoothstep = THREE.Math.smoothstep;
  8628. parameters = parameters || {};
  8629. var _this = this,
  8630. _renderData, _elements, _lights,
  8631. _projector = new THREE.Projector(),
  8632. _canvas = parameters.canvas !== undefined
  8633. ? parameters.canvas
  8634. : document.createElement( 'canvas' ),
  8635. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8636. _context = _canvas.getContext( '2d' ),
  8637. _clearColor = new THREE.Color( 0x000000 ),
  8638. _clearAlpha = 0,
  8639. _contextGlobalAlpha = 1,
  8640. _contextGlobalCompositeOperation = 0,
  8641. _contextStrokeStyle = null,
  8642. _contextFillStyle = null,
  8643. _contextLineWidth = null,
  8644. _contextLineCap = null,
  8645. _contextLineJoin = null,
  8646. _contextDashSize = null,
  8647. _contextGapSize = 0,
  8648. _camera,
  8649. _v1, _v2, _v3, _v4,
  8650. _v5 = new THREE.RenderableVertex(),
  8651. _v6 = new THREE.RenderableVertex(),
  8652. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8653. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8654. _color = new THREE.Color(),
  8655. _color1 = new THREE.Color(),
  8656. _color2 = new THREE.Color(),
  8657. _color3 = new THREE.Color(),
  8658. _color4 = new THREE.Color(),
  8659. _diffuseColor = new THREE.Color(),
  8660. _emissiveColor = new THREE.Color(),
  8661. _lightColor = new THREE.Color(),
  8662. _patterns = {}, _imagedatas = {},
  8663. _near, _far,
  8664. _image, _uvs,
  8665. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8666. _clipBox = new THREE.Box2(),
  8667. _clearBox = new THREE.Box2(),
  8668. _elemBox = new THREE.Box2(),
  8669. _ambientLight = new THREE.Color(),
  8670. _directionalLights = new THREE.Color(),
  8671. _pointLights = new THREE.Color(),
  8672. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8673. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8674. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8675. _pixelMap = document.createElement( 'canvas' );
  8676. _pixelMap.width = _pixelMap.height = 2;
  8677. _pixelMapContext = _pixelMap.getContext( '2d' );
  8678. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8679. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8680. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8681. _pixelMapData = _pixelMapImage.data;
  8682. _gradientMap = document.createElement( 'canvas' );
  8683. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8684. _gradientMapContext = _gradientMap.getContext( '2d' );
  8685. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8686. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8687. _gradientMapQuality --; // Fix UVs
  8688. // dash+gap fallbacks for Firefox and everything else
  8689. if ( _context.setLineDash === undefined ) {
  8690. if ( _context.mozDash !== undefined ) {
  8691. _context.setLineDash = function ( values ) {
  8692. _context.mozDash = values[ 0 ] !== null ? values : null;
  8693. }
  8694. } else {
  8695. _context.setLineDash = function () {}
  8696. }
  8697. }
  8698. this.domElement = _canvas;
  8699. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8700. ? parameters.devicePixelRatio
  8701. : window.devicePixelRatio !== undefined
  8702. ? window.devicePixelRatio
  8703. : 1;
  8704. this.autoClear = true;
  8705. this.sortObjects = true;
  8706. this.sortElements = true;
  8707. this.info = {
  8708. render: {
  8709. vertices: 0,
  8710. faces: 0
  8711. }
  8712. }
  8713. // WebGLRenderer compatibility
  8714. this.supportsVertexTextures = function () {};
  8715. this.setFaceCulling = function () {};
  8716. this.setSize = function ( width, height, updateStyle ) {
  8717. _canvasWidth = width * this.devicePixelRatio;
  8718. _canvasHeight = height * this.devicePixelRatio;
  8719. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8720. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8721. _canvas.width = _canvasWidth;
  8722. _canvas.height = _canvasHeight;
  8723. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  8724. _canvas.style.width = width + 'px';
  8725. _canvas.style.height = height + 'px';
  8726. }
  8727. _clipBox.set(
  8728. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8729. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8730. );
  8731. _clearBox.set(
  8732. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8733. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8734. );
  8735. _contextGlobalAlpha = 1;
  8736. _contextGlobalCompositeOperation = 0;
  8737. _contextStrokeStyle = null;
  8738. _contextFillStyle = null;
  8739. _contextLineWidth = null;
  8740. _contextLineCap = null;
  8741. _contextLineJoin = null;
  8742. };
  8743. this.setClearColor = function ( color, alpha ) {
  8744. _clearColor.set( color );
  8745. _clearAlpha = alpha !== undefined ? alpha : 1;
  8746. _clearBox.set(
  8747. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8748. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8749. );
  8750. };
  8751. this.setClearColorHex = function ( hex, alpha ) {
  8752. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  8753. this.setClearColor( hex, alpha );
  8754. };
  8755. this.getMaxAnisotropy = function () {
  8756. return 0;
  8757. };
  8758. this.clear = function () {
  8759. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8760. if ( _clearBox.empty() === false ) {
  8761. _clearBox.intersect( _clipBox );
  8762. _clearBox.expandByScalar( 2 );
  8763. if ( _clearAlpha < 1 ) {
  8764. _context.clearRect(
  8765. _clearBox.min.x | 0,
  8766. _clearBox.min.y | 0,
  8767. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8768. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8769. );
  8770. }
  8771. if ( _clearAlpha > 0 ) {
  8772. setBlending( THREE.NormalBlending );
  8773. setOpacity( 1 );
  8774. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  8775. _context.fillRect(
  8776. _clearBox.min.x | 0,
  8777. _clearBox.min.y | 0,
  8778. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8779. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8780. );
  8781. }
  8782. _clearBox.makeEmpty();
  8783. }
  8784. };
  8785. this.render = function ( scene, camera ) {
  8786. if ( camera instanceof THREE.Camera === false ) {
  8787. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8788. return;
  8789. }
  8790. if ( this.autoClear === true ) this.clear();
  8791. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8792. _this.info.render.vertices = 0;
  8793. _this.info.render.faces = 0;
  8794. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8795. _elements = _renderData.elements;
  8796. _lights = _renderData.lights;
  8797. _camera = camera;
  8798. /* DEBUG
  8799. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8800. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8801. */
  8802. calculateLights();
  8803. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8804. var element = _elements[ e ];
  8805. var material = element.material;
  8806. if ( material === undefined || material.visible === false ) continue;
  8807. _elemBox.makeEmpty();
  8808. if ( element instanceof THREE.RenderableParticle ) {
  8809. _v1 = element;
  8810. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8811. renderParticle( _v1, element, material );
  8812. } else if ( element instanceof THREE.RenderableLine ) {
  8813. _v1 = element.v1; _v2 = element.v2;
  8814. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8815. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8816. _elemBox.setFromPoints( [
  8817. _v1.positionScreen,
  8818. _v2.positionScreen
  8819. ] );
  8820. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8821. renderLine( _v1, _v2, element, material );
  8822. }
  8823. } else if ( element instanceof THREE.RenderableFace3 ) {
  8824. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8825. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8826. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8827. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8828. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8829. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8830. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8831. if ( material.overdraw > 0 ) {
  8832. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8833. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  8834. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  8835. }
  8836. _elemBox.setFromPoints( [
  8837. _v1.positionScreen,
  8838. _v2.positionScreen,
  8839. _v3.positionScreen
  8840. ] );
  8841. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8842. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8843. }
  8844. } else if ( element instanceof THREE.RenderableFace4 ) {
  8845. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8846. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8847. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8848. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8849. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8850. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8851. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8852. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8853. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8854. _v5.positionScreen.copy( _v2.positionScreen );
  8855. _v6.positionScreen.copy( _v4.positionScreen );
  8856. if ( material.overdraw > 0 ) {
  8857. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8858. expand( _v2.positionScreen, _v4.positionScreen, material.overdraw );
  8859. expand( _v4.positionScreen, _v1.positionScreen, material.overdraw );
  8860. expand( _v3.positionScreen, _v5.positionScreen, material.overdraw );
  8861. expand( _v3.positionScreen, _v6.positionScreen, material.overdraw );
  8862. }
  8863. _elemBox.setFromPoints( [
  8864. _v1.positionScreen,
  8865. _v2.positionScreen,
  8866. _v3.positionScreen,
  8867. _v4.positionScreen
  8868. ] );
  8869. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8870. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material );
  8871. }
  8872. }
  8873. /* DEBUG
  8874. setLineWidth( 1 );
  8875. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8876. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8877. */
  8878. _clearBox.union( _elemBox );
  8879. }
  8880. /* DEBUG
  8881. setLineWidth( 1 );
  8882. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  8883. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8884. */
  8885. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8886. };
  8887. //
  8888. function calculateLights() {
  8889. _ambientLight.setRGB( 0, 0, 0 );
  8890. _directionalLights.setRGB( 0, 0, 0 );
  8891. _pointLights.setRGB( 0, 0, 0 );
  8892. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8893. var light = _lights[ l ];
  8894. var lightColor = light.color;
  8895. if ( light instanceof THREE.AmbientLight ) {
  8896. _ambientLight.add( lightColor );
  8897. } else if ( light instanceof THREE.DirectionalLight ) {
  8898. // for particles
  8899. _directionalLights.add( lightColor );
  8900. } else if ( light instanceof THREE.PointLight ) {
  8901. // for particles
  8902. _pointLights.add( lightColor );
  8903. }
  8904. }
  8905. }
  8906. function calculateLight( position, normal, color ) {
  8907. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8908. var light = _lights[ l ];
  8909. _lightColor.copy( light.color );
  8910. if ( light instanceof THREE.DirectionalLight ) {
  8911. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  8912. var amount = normal.dot( lightPosition );
  8913. if ( amount <= 0 ) continue;
  8914. amount *= light.intensity;
  8915. color.add( _lightColor.multiplyScalar( amount ) );
  8916. } else if ( light instanceof THREE.PointLight ) {
  8917. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  8918. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8919. if ( amount <= 0 ) continue;
  8920. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8921. if ( amount == 0 ) continue;
  8922. amount *= light.intensity;
  8923. color.add( _lightColor.multiplyScalar( amount ) );
  8924. }
  8925. }
  8926. }
  8927. function renderParticle( v1, element, material ) {
  8928. setOpacity( material.opacity );
  8929. setBlending( material.blending );
  8930. var width, height, scaleX, scaleY,
  8931. bitmap, bitmapWidth, bitmapHeight;
  8932. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8933. if ( material.map === null ) {
  8934. scaleX = element.object.scale.x;
  8935. scaleY = element.object.scale.y;
  8936. // TODO: Be able to disable this
  8937. scaleX *= element.scale.x * _canvasWidthHalf;
  8938. scaleY *= element.scale.y * _canvasHeightHalf;
  8939. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8940. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8941. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8942. _elemBox.makeEmpty();
  8943. return;
  8944. }
  8945. setFillStyle( material.color.getStyle() );
  8946. _context.save();
  8947. _context.translate( v1.x, v1.y );
  8948. _context.rotate( - element.rotation );
  8949. _context.scale( scaleX, scaleY );
  8950. _context.fillRect( -1, -1, 2, 2 );
  8951. _context.restore();
  8952. } else {
  8953. bitmap = material.map.image;
  8954. bitmapWidth = bitmap.width >> 1;
  8955. bitmapHeight = bitmap.height >> 1;
  8956. scaleX = element.scale.x * _canvasWidthHalf;
  8957. scaleY = element.scale.y * _canvasHeightHalf;
  8958. width = scaleX * bitmapWidth;
  8959. height = scaleY * bitmapHeight;
  8960. // TODO: Rotations break this...
  8961. _elemBox.min.set( v1.x - width, v1.y - height );
  8962. _elemBox.max.set( v1.x + width, v1.y + height );
  8963. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8964. _elemBox.makeEmpty();
  8965. return;
  8966. }
  8967. _context.save();
  8968. _context.translate( v1.x, v1.y );
  8969. _context.rotate( - element.rotation );
  8970. _context.scale( scaleX, - scaleY );
  8971. _context.translate( - bitmapWidth, - bitmapHeight );
  8972. _context.drawImage( bitmap, 0, 0 );
  8973. _context.restore();
  8974. }
  8975. /* DEBUG
  8976. setStrokeStyle( 'rgb(255,255,0)' );
  8977. _context.beginPath();
  8978. _context.moveTo( v1.x - 10, v1.y );
  8979. _context.lineTo( v1.x + 10, v1.y );
  8980. _context.moveTo( v1.x, v1.y - 10 );
  8981. _context.lineTo( v1.x, v1.y + 10 );
  8982. _context.stroke();
  8983. */
  8984. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8985. width = element.scale.x * _canvasWidthHalf;
  8986. height = element.scale.y * _canvasHeightHalf;
  8987. _elemBox.min.set( v1.x - width, v1.y - height );
  8988. _elemBox.max.set( v1.x + width, v1.y + height );
  8989. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8990. _elemBox.makeEmpty();
  8991. return;
  8992. }
  8993. setStrokeStyle( material.color.getStyle() );
  8994. setFillStyle( material.color.getStyle() );
  8995. _context.save();
  8996. _context.translate( v1.x, v1.y );
  8997. _context.rotate( - element.rotation );
  8998. _context.scale( width, height );
  8999. material.program( _context );
  9000. _context.restore();
  9001. }
  9002. }
  9003. function renderLine( v1, v2, element, material ) {
  9004. setOpacity( material.opacity );
  9005. setBlending( material.blending );
  9006. _context.beginPath();
  9007. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9008. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9009. if ( material instanceof THREE.LineBasicMaterial ) {
  9010. setLineWidth( material.linewidth );
  9011. setLineCap( material.linecap );
  9012. setLineJoin( material.linejoin );
  9013. if ( material.vertexColors !== THREE.VertexColors ) {
  9014. setStrokeStyle( material.color.getStyle() );
  9015. } else {
  9016. var colorStyle1 = element.vertexColors[0].getStyle();
  9017. var colorStyle2 = element.vertexColors[1].getStyle();
  9018. if ( colorStyle1 === colorStyle2 ) {
  9019. setStrokeStyle( colorStyle1 );
  9020. } else {
  9021. try {
  9022. var grad = _context.createLinearGradient(
  9023. v1.positionScreen.x,
  9024. v1.positionScreen.y,
  9025. v2.positionScreen.x,
  9026. v2.positionScreen.y
  9027. );
  9028. grad.addColorStop( 0, colorStyle1 );
  9029. grad.addColorStop( 1, colorStyle2 );
  9030. } catch ( exception ) {
  9031. grad = colorStyle1;
  9032. }
  9033. setStrokeStyle( grad );
  9034. }
  9035. }
  9036. _context.stroke();
  9037. _elemBox.expandByScalar( material.linewidth * 2 );
  9038. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9039. setLineWidth( material.linewidth );
  9040. setLineCap( material.linecap );
  9041. setLineJoin( material.linejoin );
  9042. setStrokeStyle( material.color.getStyle() );
  9043. setDashAndGap( material.dashSize, material.gapSize );
  9044. _context.stroke();
  9045. _elemBox.expandByScalar( material.linewidth * 2 );
  9046. setDashAndGap( null, null );
  9047. }
  9048. }
  9049. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9050. _this.info.render.vertices += 3;
  9051. _this.info.render.faces ++;
  9052. setOpacity( material.opacity );
  9053. setBlending( material.blending );
  9054. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9055. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9056. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9057. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9058. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9059. _diffuseColor.copy( material.color );
  9060. _emissiveColor.copy( material.emissive );
  9061. if ( material.vertexColors === THREE.FaceColors ) {
  9062. _diffuseColor.multiply( element.color );
  9063. }
  9064. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  9065. _color1.copy( _ambientLight );
  9066. _color2.copy( _ambientLight );
  9067. _color3.copy( _ambientLight );
  9068. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9069. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9070. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9071. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9072. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9073. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9074. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9075. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9076. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9077. } else {
  9078. _color.copy( _ambientLight );
  9079. calculateLight( element.centroidModel, element.normalModel, _color );
  9080. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9081. material.wireframe === true
  9082. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9083. : fillPath( _color );
  9084. }
  9085. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9086. if ( material.map !== null ) {
  9087. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9088. _uvs = element.uvs[ 0 ];
  9089. 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 );
  9090. }
  9091. } else if ( material.envMap !== null ) {
  9092. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9093. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9094. _uv1x = 0.5 * _vector3.x + 0.5;
  9095. _uv1y = 0.5 * _vector3.y + 0.5;
  9096. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9097. _uv2x = 0.5 * _vector3.x + 0.5;
  9098. _uv2y = 0.5 * _vector3.y + 0.5;
  9099. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9100. _uv3x = 0.5 * _vector3.x + 0.5;
  9101. _uv3y = 0.5 * _vector3.y + 0.5;
  9102. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9103. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  9104. }*/
  9105. } else {
  9106. _color.copy( material.color );
  9107. if ( material.vertexColors === THREE.FaceColors ) {
  9108. _color.multiply( element.color );
  9109. }
  9110. material.wireframe === true
  9111. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9112. : fillPath( _color );
  9113. }
  9114. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9115. _near = _camera.near;
  9116. _far = _camera.far;
  9117. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9118. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9119. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9120. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9121. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9122. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9123. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9124. var normal;
  9125. if ( material.shading == THREE.FlatShading ) {
  9126. normal = element.normalModelView;
  9127. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9128. material.wireframe === true
  9129. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9130. : fillPath( _color );
  9131. } else if ( material.shading == THREE.SmoothShading ) {
  9132. normal = element.vertexNormalsModelView[ uv1 ];
  9133. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9134. normal = element.vertexNormalsModelView[ uv2 ];
  9135. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9136. normal = element.vertexNormalsModelView[ uv3 ];
  9137. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9138. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9139. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9140. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9141. }
  9142. }
  9143. }
  9144. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  9145. _this.info.render.vertices += 4;
  9146. _this.info.render.faces ++;
  9147. setOpacity( material.opacity );
  9148. setBlending( material.blending );
  9149. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  9150. // Let renderFace3() handle this
  9151. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  9152. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  9153. return;
  9154. }
  9155. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9156. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9157. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9158. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  9159. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  9160. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  9161. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9162. _diffuseColor.copy( material.color );
  9163. _emissiveColor.copy( material.emissive );
  9164. if ( material.vertexColors === THREE.FaceColors ) {
  9165. _diffuseColor.multiply( element.color );
  9166. }
  9167. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  9168. _color1.copy( _ambientLight );
  9169. _color2.copy( _ambientLight );
  9170. _color3.copy( _ambientLight );
  9171. _color4.copy( _ambientLight );
  9172. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9173. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9174. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  9175. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  9176. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9177. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9178. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9179. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  9180. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9181. // TODO: UVs are incorrect, v4->v3?
  9182. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9183. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9184. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9185. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9186. } else {
  9187. _color.copy( _ambientLight );
  9188. calculateLight( element.centroidModel, element.normalModel, _color );
  9189. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9190. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9191. material.wireframe === true
  9192. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9193. : fillPath( _color );
  9194. }
  9195. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  9196. _color.copy( material.color );
  9197. if ( material.vertexColors === THREE.FaceColors ) {
  9198. _color.multiply( element.color );
  9199. }
  9200. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9201. material.wireframe === true
  9202. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9203. : fillPath( _color );
  9204. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9205. var normal;
  9206. if ( material.shading == THREE.FlatShading ) {
  9207. normal = element.normalModelView;
  9208. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9209. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9210. material.wireframe === true
  9211. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9212. : fillPath( _color );
  9213. } else if ( material.shading == THREE.SmoothShading ) {
  9214. normal = element.vertexNormalsModelView[ 0 ];
  9215. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9216. normal = element.vertexNormalsModelView[ 1 ];
  9217. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9218. normal = element.vertexNormalsModelView[ 3 ];
  9219. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9220. normal = element.vertexNormalsModelView[ 2 ];
  9221. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9222. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9223. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9224. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9225. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9226. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9227. }
  9228. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9229. _near = _camera.near;
  9230. _far = _camera.far;
  9231. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9232. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9233. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  9234. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9235. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9236. // TODO: UVs are incorrect, v4->v3?
  9237. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9238. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9239. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9240. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9241. }
  9242. }
  9243. //
  9244. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9245. _context.beginPath();
  9246. _context.moveTo( x0, y0 );
  9247. _context.lineTo( x1, y1 );
  9248. _context.lineTo( x2, y2 );
  9249. _context.closePath();
  9250. }
  9251. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  9252. _context.beginPath();
  9253. _context.moveTo( x0, y0 );
  9254. _context.lineTo( x1, y1 );
  9255. _context.lineTo( x2, y2 );
  9256. _context.lineTo( x3, y3 );
  9257. _context.closePath();
  9258. }
  9259. function strokePath( color, linewidth, linecap, linejoin ) {
  9260. setLineWidth( linewidth );
  9261. setLineCap( linecap );
  9262. setLineJoin( linejoin );
  9263. setStrokeStyle( color.getStyle() );
  9264. _context.stroke();
  9265. _elemBox.expandByScalar( linewidth * 2 );
  9266. }
  9267. function fillPath( color ) {
  9268. setFillStyle( color.getStyle() );
  9269. _context.fill();
  9270. }
  9271. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9272. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  9273. if ( texture.needsUpdate === true ) {
  9274. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  9275. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  9276. _patterns[ texture.id ] = _context.createPattern(
  9277. texture.image, repeatX === true && repeatY === true
  9278. ? 'repeat'
  9279. : repeatX === true && repeatY === false
  9280. ? 'repeat-x'
  9281. : repeatX === false && repeatY === true
  9282. ? 'repeat-y'
  9283. : 'no-repeat'
  9284. );
  9285. texture.needsUpdate = false;
  9286. }
  9287. _patterns[ texture.id ] === undefined
  9288. ? setFillStyle( 'rgba(0,0,0,1)' )
  9289. : setFillStyle( _patterns[ texture.id ] );
  9290. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9291. var a, b, c, d, e, f, det, idet,
  9292. offsetX = texture.offset.x / texture.repeat.x,
  9293. offsetY = texture.offset.y / texture.repeat.y,
  9294. width = texture.image.width * texture.repeat.x,
  9295. height = texture.image.height * texture.repeat.y;
  9296. u0 = ( u0 + offsetX ) * width;
  9297. v0 = ( 1.0 - v0 + offsetY ) * height;
  9298. u1 = ( u1 + offsetX ) * width;
  9299. v1 = ( 1.0 - v1 + offsetY ) * height;
  9300. u2 = ( u2 + offsetX ) * width;
  9301. v2 = ( 1.0 - v2 + offsetY ) * height;
  9302. x1 -= x0; y1 -= y0;
  9303. x2 -= x0; y2 -= y0;
  9304. u1 -= u0; v1 -= v0;
  9305. u2 -= u0; v2 -= v0;
  9306. det = u1 * v2 - u2 * v1;
  9307. if ( det === 0 ) {
  9308. if ( _imagedatas[ texture.id ] === undefined ) {
  9309. var canvas = document.createElement( 'canvas' )
  9310. canvas.width = texture.image.width;
  9311. canvas.height = texture.image.height;
  9312. var context = canvas.getContext( '2d' );
  9313. context.drawImage( texture.image, 0, 0 );
  9314. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9315. }
  9316. var data = _imagedatas[ texture.id ];
  9317. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9318. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9319. fillPath( _color );
  9320. return;
  9321. }
  9322. idet = 1 / det;
  9323. a = ( v2 * x1 - v1 * x2 ) * idet;
  9324. b = ( v2 * y1 - v1 * y2 ) * idet;
  9325. c = ( u1 * x2 - u2 * x1 ) * idet;
  9326. d = ( u1 * y2 - u2 * y1 ) * idet;
  9327. e = x0 - a * u0 - c * v0;
  9328. f = y0 - b * u0 - d * v0;
  9329. _context.save();
  9330. _context.transform( a, b, c, d, e, f );
  9331. _context.fill();
  9332. _context.restore();
  9333. }
  9334. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9335. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9336. var a, b, c, d, e, f, det, idet,
  9337. width = image.width - 1,
  9338. height = image.height - 1;
  9339. u0 *= width; v0 *= height;
  9340. u1 *= width; v1 *= height;
  9341. u2 *= width; v2 *= height;
  9342. x1 -= x0; y1 -= y0;
  9343. x2 -= x0; y2 -= y0;
  9344. u1 -= u0; v1 -= v0;
  9345. u2 -= u0; v2 -= v0;
  9346. det = u1 * v2 - u2 * v1;
  9347. idet = 1 / det;
  9348. a = ( v2 * x1 - v1 * x2 ) * idet;
  9349. b = ( v2 * y1 - v1 * y2 ) * idet;
  9350. c = ( u1 * x2 - u2 * x1 ) * idet;
  9351. d = ( u1 * y2 - u2 * y1 ) * idet;
  9352. e = x0 - a * u0 - c * v0;
  9353. f = y0 - b * u0 - d * v0;
  9354. _context.save();
  9355. _context.transform( a, b, c, d, e, f );
  9356. _context.clip();
  9357. _context.drawImage( image, 0, 0 );
  9358. _context.restore();
  9359. }
  9360. function getGradientTexture( color1, color2, color3, color4 ) {
  9361. // http://mrdoob.com/blog/post/710
  9362. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9363. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9364. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9365. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9366. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9367. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9368. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9369. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9370. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9371. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9372. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9373. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9374. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9375. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9376. return _gradientMap;
  9377. }
  9378. // Hide anti-alias gaps
  9379. function expand( v1, v2, pixels ) {
  9380. var x = v2.x - v1.x, y = v2.y - v1.y,
  9381. det = x * x + y * y, idet;
  9382. if ( det === 0 ) return;
  9383. idet = pixels / Math.sqrt( det );
  9384. x *= idet; y *= idet;
  9385. v2.x += x; v2.y += y;
  9386. v1.x -= x; v1.y -= y;
  9387. }
  9388. // Context cached methods.
  9389. function setOpacity( value ) {
  9390. if ( _contextGlobalAlpha !== value ) {
  9391. _context.globalAlpha = value;
  9392. _contextGlobalAlpha = value;
  9393. }
  9394. }
  9395. function setBlending( value ) {
  9396. if ( _contextGlobalCompositeOperation !== value ) {
  9397. if ( value === THREE.NormalBlending ) {
  9398. _context.globalCompositeOperation = 'source-over';
  9399. } else if ( value === THREE.AdditiveBlending ) {
  9400. _context.globalCompositeOperation = 'lighter';
  9401. } else if ( value === THREE.SubtractiveBlending ) {
  9402. _context.globalCompositeOperation = 'darker';
  9403. }
  9404. _contextGlobalCompositeOperation = value;
  9405. }
  9406. }
  9407. function setLineWidth( value ) {
  9408. if ( _contextLineWidth !== value ) {
  9409. _context.lineWidth = value;
  9410. _contextLineWidth = value;
  9411. }
  9412. }
  9413. function setLineCap( value ) {
  9414. // "butt", "round", "square"
  9415. if ( _contextLineCap !== value ) {
  9416. _context.lineCap = value;
  9417. _contextLineCap = value;
  9418. }
  9419. }
  9420. function setLineJoin( value ) {
  9421. // "round", "bevel", "miter"
  9422. if ( _contextLineJoin !== value ) {
  9423. _context.lineJoin = value;
  9424. _contextLineJoin = value;
  9425. }
  9426. }
  9427. function setStrokeStyle( value ) {
  9428. if ( _contextStrokeStyle !== value ) {
  9429. _context.strokeStyle = value;
  9430. _contextStrokeStyle = value;
  9431. }
  9432. }
  9433. function setFillStyle( value ) {
  9434. if ( _contextFillStyle !== value ) {
  9435. _context.fillStyle = value;
  9436. _contextFillStyle = value;
  9437. }
  9438. }
  9439. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9440. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9441. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9442. _contextDashSize = dashSizeValue;
  9443. _contextGapSize = gapSizeValue;
  9444. }
  9445. }
  9446. };
  9447. /**
  9448. * @author alteredq / http://alteredqualia.com/
  9449. * @author mrdoob / http://mrdoob.com/
  9450. * @author mikael emtinger / http://gomo.se/
  9451. */
  9452. THREE.ShaderChunk = {
  9453. // FOG
  9454. fog_pars_fragment: [
  9455. "#ifdef USE_FOG",
  9456. "uniform vec3 fogColor;",
  9457. "#ifdef FOG_EXP2",
  9458. "uniform float fogDensity;",
  9459. "#else",
  9460. "uniform float fogNear;",
  9461. "uniform float fogFar;",
  9462. "#endif",
  9463. "#endif"
  9464. ].join("\n"),
  9465. fog_fragment: [
  9466. "#ifdef USE_FOG",
  9467. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9468. "#ifdef FOG_EXP2",
  9469. "const float LOG2 = 1.442695;",
  9470. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9471. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9472. "#else",
  9473. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9474. "#endif",
  9475. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9476. "#endif"
  9477. ].join("\n"),
  9478. // ENVIRONMENT MAP
  9479. envmap_pars_fragment: [
  9480. "#ifdef USE_ENVMAP",
  9481. "uniform float reflectivity;",
  9482. "uniform samplerCube envMap;",
  9483. "uniform float flipEnvMap;",
  9484. "uniform int combine;",
  9485. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9486. "uniform bool useRefract;",
  9487. "uniform float refractionRatio;",
  9488. "#else",
  9489. "varying vec3 vReflect;",
  9490. "#endif",
  9491. "#endif"
  9492. ].join("\n"),
  9493. envmap_fragment: [
  9494. "#ifdef USE_ENVMAP",
  9495. "vec3 reflectVec;",
  9496. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9497. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9498. "if ( useRefract ) {",
  9499. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9500. "} else { ",
  9501. "reflectVec = reflect( cameraToVertex, normal );",
  9502. "}",
  9503. "#else",
  9504. "reflectVec = vReflect;",
  9505. "#endif",
  9506. "#ifdef DOUBLE_SIDED",
  9507. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9508. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9509. "#else",
  9510. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9511. "#endif",
  9512. "#ifdef GAMMA_INPUT",
  9513. "cubeColor.xyz *= cubeColor.xyz;",
  9514. "#endif",
  9515. "if ( combine == 1 ) {",
  9516. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9517. "} else if ( combine == 2 ) {",
  9518. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9519. "} else {",
  9520. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9521. "}",
  9522. "#endif"
  9523. ].join("\n"),
  9524. envmap_pars_vertex: [
  9525. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9526. "varying vec3 vReflect;",
  9527. "uniform float refractionRatio;",
  9528. "uniform bool useRefract;",
  9529. "#endif"
  9530. ].join("\n"),
  9531. worldpos_vertex : [
  9532. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9533. "#ifdef USE_SKINNING",
  9534. "vec4 worldPosition = modelMatrix * skinned;",
  9535. "#endif",
  9536. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9537. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9538. "#endif",
  9539. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9540. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9541. "#endif",
  9542. "#endif"
  9543. ].join("\n"),
  9544. envmap_vertex : [
  9545. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9546. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9547. "worldNormal = normalize( worldNormal );",
  9548. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9549. "if ( useRefract ) {",
  9550. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9551. "} else {",
  9552. "vReflect = reflect( cameraToVertex, worldNormal );",
  9553. "}",
  9554. "#endif"
  9555. ].join("\n"),
  9556. // COLOR MAP (particles)
  9557. map_particle_pars_fragment: [
  9558. "#ifdef USE_MAP",
  9559. "uniform sampler2D map;",
  9560. "#endif"
  9561. ].join("\n"),
  9562. map_particle_fragment: [
  9563. "#ifdef USE_MAP",
  9564. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9565. "#endif"
  9566. ].join("\n"),
  9567. // COLOR MAP (triangles)
  9568. map_pars_vertex: [
  9569. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9570. "varying vec2 vUv;",
  9571. "uniform vec4 offsetRepeat;",
  9572. "#endif"
  9573. ].join("\n"),
  9574. map_pars_fragment: [
  9575. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9576. "varying vec2 vUv;",
  9577. "#endif",
  9578. "#ifdef USE_MAP",
  9579. "uniform sampler2D map;",
  9580. "#endif"
  9581. ].join("\n"),
  9582. map_vertex: [
  9583. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9584. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9585. "#endif"
  9586. ].join("\n"),
  9587. map_fragment: [
  9588. "#ifdef USE_MAP",
  9589. "vec4 texelColor = texture2D( map, vUv );",
  9590. "#ifdef GAMMA_INPUT",
  9591. "texelColor.xyz *= texelColor.xyz;",
  9592. "#endif",
  9593. "gl_FragColor = gl_FragColor * texelColor;",
  9594. "#endif"
  9595. ].join("\n"),
  9596. // LIGHT MAP
  9597. lightmap_pars_fragment: [
  9598. "#ifdef USE_LIGHTMAP",
  9599. "varying vec2 vUv2;",
  9600. "uniform sampler2D lightMap;",
  9601. "#endif"
  9602. ].join("\n"),
  9603. lightmap_pars_vertex: [
  9604. "#ifdef USE_LIGHTMAP",
  9605. "varying vec2 vUv2;",
  9606. "#endif"
  9607. ].join("\n"),
  9608. lightmap_fragment: [
  9609. "#ifdef USE_LIGHTMAP",
  9610. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9611. "#endif"
  9612. ].join("\n"),
  9613. lightmap_vertex: [
  9614. "#ifdef USE_LIGHTMAP",
  9615. "vUv2 = uv2;",
  9616. "#endif"
  9617. ].join("\n"),
  9618. // BUMP MAP
  9619. bumpmap_pars_fragment: [
  9620. "#ifdef USE_BUMPMAP",
  9621. "uniform sampler2D bumpMap;",
  9622. "uniform float bumpScale;",
  9623. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9624. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9625. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9626. "vec2 dHdxy_fwd() {",
  9627. "vec2 dSTdx = dFdx( vUv );",
  9628. "vec2 dSTdy = dFdy( vUv );",
  9629. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9630. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9631. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9632. "return vec2( dBx, dBy );",
  9633. "}",
  9634. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9635. "vec3 vSigmaX = dFdx( surf_pos );",
  9636. "vec3 vSigmaY = dFdy( surf_pos );",
  9637. "vec3 vN = surf_norm;", // normalized
  9638. "vec3 R1 = cross( vSigmaY, vN );",
  9639. "vec3 R2 = cross( vN, vSigmaX );",
  9640. "float fDet = dot( vSigmaX, R1 );",
  9641. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9642. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9643. "}",
  9644. "#endif"
  9645. ].join("\n"),
  9646. // NORMAL MAP
  9647. normalmap_pars_fragment: [
  9648. "#ifdef USE_NORMALMAP",
  9649. "uniform sampler2D normalMap;",
  9650. "uniform vec2 normalScale;",
  9651. // Per-Pixel Tangent Space Normal Mapping
  9652. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9653. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9654. "vec3 q0 = dFdx( eye_pos.xyz );",
  9655. "vec3 q1 = dFdy( eye_pos.xyz );",
  9656. "vec2 st0 = dFdx( vUv.st );",
  9657. "vec2 st1 = dFdy( vUv.st );",
  9658. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9659. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9660. "vec3 N = normalize( surf_norm );",
  9661. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9662. "mapN.xy = normalScale * mapN.xy;",
  9663. "mat3 tsn = mat3( S, T, N );",
  9664. "return normalize( tsn * mapN );",
  9665. "}",
  9666. "#endif"
  9667. ].join("\n"),
  9668. // SPECULAR MAP
  9669. specularmap_pars_fragment: [
  9670. "#ifdef USE_SPECULARMAP",
  9671. "uniform sampler2D specularMap;",
  9672. "#endif"
  9673. ].join("\n"),
  9674. specularmap_fragment: [
  9675. "float specularStrength;",
  9676. "#ifdef USE_SPECULARMAP",
  9677. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9678. "specularStrength = texelSpecular.r;",
  9679. "#else",
  9680. "specularStrength = 1.0;",
  9681. "#endif"
  9682. ].join("\n"),
  9683. // LIGHTS LAMBERT
  9684. lights_lambert_pars_vertex: [
  9685. "uniform vec3 ambient;",
  9686. "uniform vec3 diffuse;",
  9687. "uniform vec3 emissive;",
  9688. "uniform vec3 ambientLightColor;",
  9689. "#if MAX_DIR_LIGHTS > 0",
  9690. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9691. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9692. "#endif",
  9693. "#if MAX_HEMI_LIGHTS > 0",
  9694. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9695. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9696. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9697. "#endif",
  9698. "#if MAX_POINT_LIGHTS > 0",
  9699. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9700. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9701. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9702. "#endif",
  9703. "#if MAX_SPOT_LIGHTS > 0",
  9704. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9705. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9706. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9707. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9708. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9709. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9710. "#endif",
  9711. "#ifdef WRAP_AROUND",
  9712. "uniform vec3 wrapRGB;",
  9713. "#endif"
  9714. ].join("\n"),
  9715. lights_lambert_vertex: [
  9716. "vLightFront = vec3( 0.0 );",
  9717. "#ifdef DOUBLE_SIDED",
  9718. "vLightBack = vec3( 0.0 );",
  9719. "#endif",
  9720. "transformedNormal = normalize( transformedNormal );",
  9721. "#if MAX_DIR_LIGHTS > 0",
  9722. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9723. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9724. "vec3 dirVector = normalize( lDirection.xyz );",
  9725. "float dotProduct = dot( transformedNormal, dirVector );",
  9726. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9727. "#ifdef DOUBLE_SIDED",
  9728. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9729. "#ifdef WRAP_AROUND",
  9730. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9731. "#endif",
  9732. "#endif",
  9733. "#ifdef WRAP_AROUND",
  9734. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9735. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9736. "#ifdef DOUBLE_SIDED",
  9737. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9738. "#endif",
  9739. "#endif",
  9740. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9741. "#ifdef DOUBLE_SIDED",
  9742. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9743. "#endif",
  9744. "}",
  9745. "#endif",
  9746. "#if MAX_POINT_LIGHTS > 0",
  9747. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9748. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9749. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9750. "float lDistance = 1.0;",
  9751. "if ( pointLightDistance[ i ] > 0.0 )",
  9752. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9753. "lVector = normalize( lVector );",
  9754. "float dotProduct = dot( transformedNormal, lVector );",
  9755. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9756. "#ifdef DOUBLE_SIDED",
  9757. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9758. "#ifdef WRAP_AROUND",
  9759. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9760. "#endif",
  9761. "#endif",
  9762. "#ifdef WRAP_AROUND",
  9763. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9764. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9765. "#ifdef DOUBLE_SIDED",
  9766. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9767. "#endif",
  9768. "#endif",
  9769. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9770. "#ifdef DOUBLE_SIDED",
  9771. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9772. "#endif",
  9773. "}",
  9774. "#endif",
  9775. "#if MAX_SPOT_LIGHTS > 0",
  9776. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9777. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9778. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9779. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9780. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9781. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9782. "float lDistance = 1.0;",
  9783. "if ( spotLightDistance[ i ] > 0.0 )",
  9784. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9785. "lVector = normalize( lVector );",
  9786. "float dotProduct = dot( transformedNormal, lVector );",
  9787. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9788. "#ifdef DOUBLE_SIDED",
  9789. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9790. "#ifdef WRAP_AROUND",
  9791. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9792. "#endif",
  9793. "#endif",
  9794. "#ifdef WRAP_AROUND",
  9795. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9796. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9797. "#ifdef DOUBLE_SIDED",
  9798. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9799. "#endif",
  9800. "#endif",
  9801. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9802. "#ifdef DOUBLE_SIDED",
  9803. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9804. "#endif",
  9805. "}",
  9806. "}",
  9807. "#endif",
  9808. "#if MAX_HEMI_LIGHTS > 0",
  9809. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9810. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9811. "vec3 lVector = normalize( lDirection.xyz );",
  9812. "float dotProduct = dot( transformedNormal, lVector );",
  9813. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9814. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9815. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9816. "#ifdef DOUBLE_SIDED",
  9817. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9818. "#endif",
  9819. "}",
  9820. "#endif",
  9821. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9822. "#ifdef DOUBLE_SIDED",
  9823. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9824. "#endif"
  9825. ].join("\n"),
  9826. // LIGHTS PHONG
  9827. lights_phong_pars_vertex: [
  9828. "#ifndef PHONG_PER_PIXEL",
  9829. "#if MAX_POINT_LIGHTS > 0",
  9830. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9831. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9832. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9833. "#endif",
  9834. "#if MAX_SPOT_LIGHTS > 0",
  9835. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9836. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9837. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9838. "#endif",
  9839. "#endif",
  9840. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9841. "varying vec3 vWorldPosition;",
  9842. "#endif"
  9843. ].join("\n"),
  9844. lights_phong_vertex: [
  9845. "#ifndef PHONG_PER_PIXEL",
  9846. "#if MAX_POINT_LIGHTS > 0",
  9847. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9848. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9849. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9850. "float lDistance = 1.0;",
  9851. "if ( pointLightDistance[ i ] > 0.0 )",
  9852. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9853. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9854. "}",
  9855. "#endif",
  9856. "#if MAX_SPOT_LIGHTS > 0",
  9857. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9858. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9859. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9860. "float lDistance = 1.0;",
  9861. "if ( spotLightDistance[ i ] > 0.0 )",
  9862. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9863. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9864. "}",
  9865. "#endif",
  9866. "#endif",
  9867. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9868. "vWorldPosition = worldPosition.xyz;",
  9869. "#endif"
  9870. ].join("\n"),
  9871. lights_phong_pars_fragment: [
  9872. "uniform vec3 ambientLightColor;",
  9873. "#if MAX_DIR_LIGHTS > 0",
  9874. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9875. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9876. "#endif",
  9877. "#if MAX_HEMI_LIGHTS > 0",
  9878. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9879. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9880. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9881. "#endif",
  9882. "#if MAX_POINT_LIGHTS > 0",
  9883. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9884. "#ifdef PHONG_PER_PIXEL",
  9885. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9886. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9887. "#else",
  9888. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9889. "#endif",
  9890. "#endif",
  9891. "#if MAX_SPOT_LIGHTS > 0",
  9892. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9893. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9894. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9895. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9896. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9897. "#ifdef PHONG_PER_PIXEL",
  9898. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9899. "#else",
  9900. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9901. "#endif",
  9902. "#endif",
  9903. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9904. "varying vec3 vWorldPosition;",
  9905. "#endif",
  9906. "#ifdef WRAP_AROUND",
  9907. "uniform vec3 wrapRGB;",
  9908. "#endif",
  9909. "varying vec3 vViewPosition;",
  9910. "varying vec3 vNormal;"
  9911. ].join("\n"),
  9912. lights_phong_fragment: [
  9913. "vec3 normal = normalize( vNormal );",
  9914. "vec3 viewPosition = normalize( vViewPosition );",
  9915. "#ifdef DOUBLE_SIDED",
  9916. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9917. "#endif",
  9918. "#ifdef USE_NORMALMAP",
  9919. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  9920. "#elif defined( USE_BUMPMAP )",
  9921. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9922. "#endif",
  9923. "#if MAX_POINT_LIGHTS > 0",
  9924. "vec3 pointDiffuse = vec3( 0.0 );",
  9925. "vec3 pointSpecular = vec3( 0.0 );",
  9926. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9927. "#ifdef PHONG_PER_PIXEL",
  9928. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9929. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9930. "float lDistance = 1.0;",
  9931. "if ( pointLightDistance[ i ] > 0.0 )",
  9932. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9933. "lVector = normalize( lVector );",
  9934. "#else",
  9935. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9936. "float lDistance = vPointLight[ i ].w;",
  9937. "#endif",
  9938. // diffuse
  9939. "float dotProduct = dot( normal, lVector );",
  9940. "#ifdef WRAP_AROUND",
  9941. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9942. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9943. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9944. "#else",
  9945. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9946. "#endif",
  9947. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9948. // specular
  9949. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9950. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9951. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9952. "#ifdef PHYSICALLY_BASED_SHADING",
  9953. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9954. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9955. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9956. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9957. "#else",
  9958. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9959. "#endif",
  9960. "}",
  9961. "#endif",
  9962. "#if MAX_SPOT_LIGHTS > 0",
  9963. "vec3 spotDiffuse = vec3( 0.0 );",
  9964. "vec3 spotSpecular = vec3( 0.0 );",
  9965. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9966. "#ifdef PHONG_PER_PIXEL",
  9967. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9968. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9969. "float lDistance = 1.0;",
  9970. "if ( spotLightDistance[ i ] > 0.0 )",
  9971. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9972. "lVector = normalize( lVector );",
  9973. "#else",
  9974. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9975. "float lDistance = vSpotLight[ i ].w;",
  9976. "#endif",
  9977. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9978. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9979. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9980. // diffuse
  9981. "float dotProduct = dot( normal, lVector );",
  9982. "#ifdef WRAP_AROUND",
  9983. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9984. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9985. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9986. "#else",
  9987. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9988. "#endif",
  9989. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9990. // specular
  9991. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9992. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9993. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9994. "#ifdef PHYSICALLY_BASED_SHADING",
  9995. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9996. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9997. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9998. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9999. "#else",
  10000. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10001. "#endif",
  10002. "}",
  10003. "}",
  10004. "#endif",
  10005. "#if MAX_DIR_LIGHTS > 0",
  10006. "vec3 dirDiffuse = vec3( 0.0 );",
  10007. "vec3 dirSpecular = vec3( 0.0 );" ,
  10008. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10009. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10010. "vec3 dirVector = normalize( lDirection.xyz );",
  10011. // diffuse
  10012. "float dotProduct = dot( normal, dirVector );",
  10013. "#ifdef WRAP_AROUND",
  10014. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10015. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10016. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10017. "#else",
  10018. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10019. "#endif",
  10020. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10021. // specular
  10022. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10023. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10024. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10025. "#ifdef PHYSICALLY_BASED_SHADING",
  10026. /*
  10027. // fresnel term from skin shader
  10028. "const float F0 = 0.128;",
  10029. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10030. "float exponential = pow( base, 5.0 );",
  10031. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10032. */
  10033. /*
  10034. // fresnel term from fresnel shader
  10035. "const float mFresnelBias = 0.08;",
  10036. "const float mFresnelScale = 0.3;",
  10037. "const float mFresnelPower = 5.0;",
  10038. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10039. */
  10040. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10041. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10042. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10043. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10044. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10045. "#else",
  10046. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10047. "#endif",
  10048. "}",
  10049. "#endif",
  10050. "#if MAX_HEMI_LIGHTS > 0",
  10051. "vec3 hemiDiffuse = vec3( 0.0 );",
  10052. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10053. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10054. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10055. "vec3 lVector = normalize( lDirection.xyz );",
  10056. // diffuse
  10057. "float dotProduct = dot( normal, lVector );",
  10058. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10059. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10060. "hemiDiffuse += diffuse * hemiColor;",
  10061. // specular (sky light)
  10062. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10063. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10064. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10065. // specular (ground light)
  10066. "vec3 lVectorGround = -lVector;",
  10067. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10068. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10069. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10070. "#ifdef PHYSICALLY_BASED_SHADING",
  10071. "float dotProductGround = dot( normal, lVectorGround );",
  10072. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10073. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10074. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10075. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10076. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10077. "#else",
  10078. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10079. "#endif",
  10080. "}",
  10081. "#endif",
  10082. "vec3 totalDiffuse = vec3( 0.0 );",
  10083. "vec3 totalSpecular = vec3( 0.0 );",
  10084. "#if MAX_DIR_LIGHTS > 0",
  10085. "totalDiffuse += dirDiffuse;",
  10086. "totalSpecular += dirSpecular;",
  10087. "#endif",
  10088. "#if MAX_HEMI_LIGHTS > 0",
  10089. "totalDiffuse += hemiDiffuse;",
  10090. "totalSpecular += hemiSpecular;",
  10091. "#endif",
  10092. "#if MAX_POINT_LIGHTS > 0",
  10093. "totalDiffuse += pointDiffuse;",
  10094. "totalSpecular += pointSpecular;",
  10095. "#endif",
  10096. "#if MAX_SPOT_LIGHTS > 0",
  10097. "totalDiffuse += spotDiffuse;",
  10098. "totalSpecular += spotSpecular;",
  10099. "#endif",
  10100. "#ifdef METAL",
  10101. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10102. "#else",
  10103. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10104. "#endif"
  10105. ].join("\n"),
  10106. // VERTEX COLORS
  10107. color_pars_fragment: [
  10108. "#ifdef USE_COLOR",
  10109. "varying vec3 vColor;",
  10110. "#endif"
  10111. ].join("\n"),
  10112. color_fragment: [
  10113. "#ifdef USE_COLOR",
  10114. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  10115. "#endif"
  10116. ].join("\n"),
  10117. color_pars_vertex: [
  10118. "#ifdef USE_COLOR",
  10119. "varying vec3 vColor;",
  10120. "#endif"
  10121. ].join("\n"),
  10122. color_vertex: [
  10123. "#ifdef USE_COLOR",
  10124. "#ifdef GAMMA_INPUT",
  10125. "vColor = color * color;",
  10126. "#else",
  10127. "vColor = color;",
  10128. "#endif",
  10129. "#endif"
  10130. ].join("\n"),
  10131. // SKINNING
  10132. skinning_pars_vertex: [
  10133. "#ifdef USE_SKINNING",
  10134. "#ifdef BONE_TEXTURE",
  10135. "uniform sampler2D boneTexture;",
  10136. "mat4 getBoneMatrix( const in float i ) {",
  10137. "float j = i * 4.0;",
  10138. "float x = mod( j, N_BONE_PIXEL_X );",
  10139. "float y = floor( j / N_BONE_PIXEL_X );",
  10140. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  10141. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  10142. "y = dy * ( y + 0.5 );",
  10143. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10144. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10145. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10146. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10147. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10148. "return bone;",
  10149. "}",
  10150. "#else",
  10151. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10152. "mat4 getBoneMatrix( const in float i ) {",
  10153. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10154. "return bone;",
  10155. "}",
  10156. "#endif",
  10157. "#endif"
  10158. ].join("\n"),
  10159. skinbase_vertex: [
  10160. "#ifdef USE_SKINNING",
  10161. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10162. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10163. "#endif"
  10164. ].join("\n"),
  10165. skinning_vertex: [
  10166. "#ifdef USE_SKINNING",
  10167. "#ifdef USE_MORPHTARGETS",
  10168. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10169. "#else",
  10170. "vec4 skinVertex = vec4( position, 1.0 );",
  10171. "#endif",
  10172. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10173. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10174. "#endif"
  10175. ].join("\n"),
  10176. // MORPHING
  10177. morphtarget_pars_vertex: [
  10178. "#ifdef USE_MORPHTARGETS",
  10179. "#ifndef USE_MORPHNORMALS",
  10180. "uniform float morphTargetInfluences[ 8 ];",
  10181. "#else",
  10182. "uniform float morphTargetInfluences[ 4 ];",
  10183. "#endif",
  10184. "#endif"
  10185. ].join("\n"),
  10186. morphtarget_vertex: [
  10187. "#ifdef USE_MORPHTARGETS",
  10188. "vec3 morphed = vec3( 0.0 );",
  10189. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10190. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10191. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10192. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10193. "#ifndef USE_MORPHNORMALS",
  10194. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10195. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10196. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10197. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10198. "#endif",
  10199. "morphed += position;",
  10200. "#endif"
  10201. ].join("\n"),
  10202. default_vertex : [
  10203. "vec4 mvPosition;",
  10204. "#ifdef USE_SKINNING",
  10205. "mvPosition = modelViewMatrix * skinned;",
  10206. "#endif",
  10207. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10208. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10209. "#endif",
  10210. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10211. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10212. "#endif",
  10213. "gl_Position = projectionMatrix * mvPosition;"
  10214. ].join("\n"),
  10215. morphnormal_vertex: [
  10216. "#ifdef USE_MORPHNORMALS",
  10217. "vec3 morphedNormal = vec3( 0.0 );",
  10218. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10219. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10220. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10221. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10222. "morphedNormal += normal;",
  10223. "#endif"
  10224. ].join("\n"),
  10225. skinnormal_vertex: [
  10226. "#ifdef USE_SKINNING",
  10227. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10228. "skinMatrix += skinWeight.y * boneMatY;",
  10229. "#ifdef USE_MORPHNORMALS",
  10230. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10231. "#else",
  10232. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10233. "#endif",
  10234. "#endif"
  10235. ].join("\n"),
  10236. defaultnormal_vertex: [
  10237. "vec3 objectNormal;",
  10238. "#ifdef USE_SKINNING",
  10239. "objectNormal = skinnedNormal.xyz;",
  10240. "#endif",
  10241. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10242. "objectNormal = morphedNormal;",
  10243. "#endif",
  10244. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10245. "objectNormal = normal;",
  10246. "#endif",
  10247. "#ifdef FLIP_SIDED",
  10248. "objectNormal = -objectNormal;",
  10249. "#endif",
  10250. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10251. ].join("\n"),
  10252. // SHADOW MAP
  10253. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10254. // http://spidergl.org/example.php?id=6
  10255. // http://fabiensanglard.net/shadowmapping
  10256. shadowmap_pars_fragment: [
  10257. "#ifdef USE_SHADOWMAP",
  10258. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10259. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10260. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10261. "uniform float shadowBias[ MAX_SHADOWS ];",
  10262. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10263. "float unpackDepth( const in vec4 rgba_depth ) {",
  10264. "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 );",
  10265. "float depth = dot( rgba_depth, bit_shift );",
  10266. "return depth;",
  10267. "}",
  10268. "#endif"
  10269. ].join("\n"),
  10270. shadowmap_fragment: [
  10271. "#ifdef USE_SHADOWMAP",
  10272. "#ifdef SHADOWMAP_DEBUG",
  10273. "vec3 frustumColors[3];",
  10274. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10275. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10276. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10277. "#endif",
  10278. "#ifdef SHADOWMAP_CASCADE",
  10279. "int inFrustumCount = 0;",
  10280. "#endif",
  10281. "float fDepth;",
  10282. "vec3 shadowColor = vec3( 1.0 );",
  10283. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10284. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10285. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10286. // "if ( all( something, something ) )" using this instead
  10287. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10288. "bool inFrustum = all( inFrustumVec );",
  10289. // don't shadow pixels outside of light frustum
  10290. // use just first frustum (for cascades)
  10291. // don't shadow pixels behind far plane of light frustum
  10292. "#ifdef SHADOWMAP_CASCADE",
  10293. "inFrustumCount += int( inFrustum );",
  10294. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10295. "#else",
  10296. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10297. "#endif",
  10298. "bool frustumTest = all( frustumTestVec );",
  10299. "if ( frustumTest ) {",
  10300. "shadowCoord.z += shadowBias[ i ];",
  10301. "#if defined( SHADOWMAP_TYPE_PCF )",
  10302. // Percentage-close filtering
  10303. // (9 pixel kernel)
  10304. // http://fabiensanglard.net/shadowmappingPCF/
  10305. "float shadow = 0.0;",
  10306. /*
  10307. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10308. // must enroll loop manually
  10309. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10310. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10311. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10312. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10313. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10314. "float fDepth = unpackDepth( rgbaDepth );",
  10315. "if ( fDepth < shadowCoord.z )",
  10316. "shadow += 1.0;",
  10317. "}",
  10318. "shadow /= 9.0;",
  10319. */
  10320. "const float shadowDelta = 1.0 / 9.0;",
  10321. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10322. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10323. "float dx0 = -1.25 * xPixelOffset;",
  10324. "float dy0 = -1.25 * yPixelOffset;",
  10325. "float dx1 = 1.25 * xPixelOffset;",
  10326. "float dy1 = 1.25 * yPixelOffset;",
  10327. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10328. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10329. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10330. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10331. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10332. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10333. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10334. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10335. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10336. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10337. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10338. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10339. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10340. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10341. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10342. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10343. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10344. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10345. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10346. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10347. // Percentage-close filtering
  10348. // (9 pixel kernel)
  10349. // http://fabiensanglard.net/shadowmappingPCF/
  10350. "float shadow = 0.0;",
  10351. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10352. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10353. "float dx0 = -1.0 * xPixelOffset;",
  10354. "float dy0 = -1.0 * yPixelOffset;",
  10355. "float dx1 = 1.0 * xPixelOffset;",
  10356. "float dy1 = 1.0 * yPixelOffset;",
  10357. "mat3 shadowKernel;",
  10358. "mat3 depthKernel;",
  10359. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10360. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10361. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10362. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10363. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10364. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10365. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10366. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10367. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10368. "vec3 shadowZ = vec3( shadowCoord.z );",
  10369. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10370. "shadowKernel[0] *= vec3(0.25);",
  10371. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10372. "shadowKernel[1] *= vec3(0.25);",
  10373. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10374. "shadowKernel[2] *= vec3(0.25);",
  10375. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10376. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10377. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10378. "vec4 shadowValues;",
  10379. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10380. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10381. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10382. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10383. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10384. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10385. "#else",
  10386. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10387. "float fDepth = unpackDepth( rgbaDepth );",
  10388. "if ( fDepth < shadowCoord.z )",
  10389. // spot with multiple shadows is darker
  10390. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10391. // spot with multiple shadows has the same color as single shadow spot
  10392. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10393. "#endif",
  10394. "}",
  10395. "#ifdef SHADOWMAP_DEBUG",
  10396. "#ifdef SHADOWMAP_CASCADE",
  10397. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10398. "#else",
  10399. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10400. "#endif",
  10401. "#endif",
  10402. "}",
  10403. "#ifdef GAMMA_OUTPUT",
  10404. "shadowColor *= shadowColor;",
  10405. "#endif",
  10406. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10407. "#endif"
  10408. ].join("\n"),
  10409. shadowmap_pars_vertex: [
  10410. "#ifdef USE_SHADOWMAP",
  10411. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10412. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10413. "#endif"
  10414. ].join("\n"),
  10415. shadowmap_vertex: [
  10416. "#ifdef USE_SHADOWMAP",
  10417. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10418. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10419. "}",
  10420. "#endif"
  10421. ].join("\n"),
  10422. // ALPHATEST
  10423. alphatest_fragment: [
  10424. "#ifdef ALPHATEST",
  10425. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10426. "#endif"
  10427. ].join("\n"),
  10428. // LINEAR SPACE
  10429. linear_to_gamma_fragment: [
  10430. "#ifdef GAMMA_OUTPUT",
  10431. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10432. "#endif"
  10433. ].join("\n")
  10434. };
  10435. THREE.UniformsUtils = {
  10436. merge: function ( uniforms ) {
  10437. var u, p, tmp, merged = {};
  10438. for ( u = 0; u < uniforms.length; u ++ ) {
  10439. tmp = this.clone( uniforms[ u ] );
  10440. for ( p in tmp ) {
  10441. merged[ p ] = tmp[ p ];
  10442. }
  10443. }
  10444. return merged;
  10445. },
  10446. clone: function ( uniforms_src ) {
  10447. var u, p, parameter, parameter_src, uniforms_dst = {};
  10448. for ( u in uniforms_src ) {
  10449. uniforms_dst[ u ] = {};
  10450. for ( p in uniforms_src[ u ] ) {
  10451. parameter_src = uniforms_src[ u ][ p ];
  10452. if ( parameter_src instanceof THREE.Color ||
  10453. parameter_src instanceof THREE.Vector2 ||
  10454. parameter_src instanceof THREE.Vector3 ||
  10455. parameter_src instanceof THREE.Vector4 ||
  10456. parameter_src instanceof THREE.Matrix4 ||
  10457. parameter_src instanceof THREE.Texture ) {
  10458. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10459. } else if ( parameter_src instanceof Array ) {
  10460. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10461. } else {
  10462. uniforms_dst[ u ][ p ] = parameter_src;
  10463. }
  10464. }
  10465. }
  10466. return uniforms_dst;
  10467. }
  10468. };
  10469. THREE.UniformsLib = {
  10470. common: {
  10471. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10472. "opacity" : { type: "f", value: 1.0 },
  10473. "map" : { type: "t", value: null },
  10474. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10475. "lightMap" : { type: "t", value: null },
  10476. "specularMap" : { type: "t", value: null },
  10477. "envMap" : { type: "t", value: null },
  10478. "flipEnvMap" : { type: "f", value: -1 },
  10479. "useRefract" : { type: "i", value: 0 },
  10480. "reflectivity" : { type: "f", value: 1.0 },
  10481. "refractionRatio" : { type: "f", value: 0.98 },
  10482. "combine" : { type: "i", value: 0 },
  10483. "morphTargetInfluences" : { type: "f", value: 0 }
  10484. },
  10485. bump: {
  10486. "bumpMap" : { type: "t", value: null },
  10487. "bumpScale" : { type: "f", value: 1 }
  10488. },
  10489. normalmap: {
  10490. "normalMap" : { type: "t", value: null },
  10491. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10492. },
  10493. fog : {
  10494. "fogDensity" : { type: "f", value: 0.00025 },
  10495. "fogNear" : { type: "f", value: 1 },
  10496. "fogFar" : { type: "f", value: 2000 },
  10497. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10498. },
  10499. lights: {
  10500. "ambientLightColor" : { type: "fv", value: [] },
  10501. "directionalLightDirection" : { type: "fv", value: [] },
  10502. "directionalLightColor" : { type: "fv", value: [] },
  10503. "hemisphereLightDirection" : { type: "fv", value: [] },
  10504. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10505. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10506. "pointLightColor" : { type: "fv", value: [] },
  10507. "pointLightPosition" : { type: "fv", value: [] },
  10508. "pointLightDistance" : { type: "fv1", value: [] },
  10509. "spotLightColor" : { type: "fv", value: [] },
  10510. "spotLightPosition" : { type: "fv", value: [] },
  10511. "spotLightDirection" : { type: "fv", value: [] },
  10512. "spotLightDistance" : { type: "fv1", value: [] },
  10513. "spotLightAngleCos" : { type: "fv1", value: [] },
  10514. "spotLightExponent" : { type: "fv1", value: [] }
  10515. },
  10516. particle: {
  10517. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10518. "opacity" : { type: "f", value: 1.0 },
  10519. "size" : { type: "f", value: 1.0 },
  10520. "scale" : { type: "f", value: 1.0 },
  10521. "map" : { type: "t", value: null },
  10522. "fogDensity" : { type: "f", value: 0.00025 },
  10523. "fogNear" : { type: "f", value: 1 },
  10524. "fogFar" : { type: "f", value: 2000 },
  10525. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10526. },
  10527. shadowmap: {
  10528. "shadowMap": { type: "tv", value: [] },
  10529. "shadowMapSize": { type: "v2v", value: [] },
  10530. "shadowBias" : { type: "fv1", value: [] },
  10531. "shadowDarkness": { type: "fv1", value: [] },
  10532. "shadowMatrix" : { type: "m4v", value: [] }
  10533. }
  10534. };
  10535. THREE.ShaderLib = {
  10536. 'basic': {
  10537. uniforms: THREE.UniformsUtils.merge( [
  10538. THREE.UniformsLib[ "common" ],
  10539. THREE.UniformsLib[ "fog" ],
  10540. THREE.UniformsLib[ "shadowmap" ]
  10541. ] ),
  10542. vertexShader: [
  10543. THREE.ShaderChunk[ "map_pars_vertex" ],
  10544. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10545. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10546. THREE.ShaderChunk[ "color_pars_vertex" ],
  10547. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10548. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10549. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10550. "void main() {",
  10551. THREE.ShaderChunk[ "map_vertex" ],
  10552. THREE.ShaderChunk[ "lightmap_vertex" ],
  10553. THREE.ShaderChunk[ "color_vertex" ],
  10554. THREE.ShaderChunk[ "skinbase_vertex" ],
  10555. "#ifdef USE_ENVMAP",
  10556. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10557. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10558. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10559. "#endif",
  10560. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10561. THREE.ShaderChunk[ "skinning_vertex" ],
  10562. THREE.ShaderChunk[ "default_vertex" ],
  10563. THREE.ShaderChunk[ "worldpos_vertex" ],
  10564. THREE.ShaderChunk[ "envmap_vertex" ],
  10565. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10566. "}"
  10567. ].join("\n"),
  10568. fragmentShader: [
  10569. "uniform vec3 diffuse;",
  10570. "uniform float opacity;",
  10571. THREE.ShaderChunk[ "color_pars_fragment" ],
  10572. THREE.ShaderChunk[ "map_pars_fragment" ],
  10573. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10574. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10575. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10576. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10577. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10578. "void main() {",
  10579. "gl_FragColor = vec4( diffuse, opacity );",
  10580. THREE.ShaderChunk[ "map_fragment" ],
  10581. THREE.ShaderChunk[ "alphatest_fragment" ],
  10582. THREE.ShaderChunk[ "specularmap_fragment" ],
  10583. THREE.ShaderChunk[ "lightmap_fragment" ],
  10584. THREE.ShaderChunk[ "color_fragment" ],
  10585. THREE.ShaderChunk[ "envmap_fragment" ],
  10586. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10587. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10588. THREE.ShaderChunk[ "fog_fragment" ],
  10589. "}"
  10590. ].join("\n")
  10591. },
  10592. 'lambert': {
  10593. uniforms: THREE.UniformsUtils.merge( [
  10594. THREE.UniformsLib[ "common" ],
  10595. THREE.UniformsLib[ "fog" ],
  10596. THREE.UniformsLib[ "lights" ],
  10597. THREE.UniformsLib[ "shadowmap" ],
  10598. {
  10599. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10600. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10601. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10602. }
  10603. ] ),
  10604. vertexShader: [
  10605. "#define LAMBERT",
  10606. "varying vec3 vLightFront;",
  10607. "#ifdef DOUBLE_SIDED",
  10608. "varying vec3 vLightBack;",
  10609. "#endif",
  10610. THREE.ShaderChunk[ "map_pars_vertex" ],
  10611. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10612. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10613. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10614. THREE.ShaderChunk[ "color_pars_vertex" ],
  10615. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10616. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10617. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10618. "void main() {",
  10619. THREE.ShaderChunk[ "map_vertex" ],
  10620. THREE.ShaderChunk[ "lightmap_vertex" ],
  10621. THREE.ShaderChunk[ "color_vertex" ],
  10622. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10623. THREE.ShaderChunk[ "skinbase_vertex" ],
  10624. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10625. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10626. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10627. THREE.ShaderChunk[ "skinning_vertex" ],
  10628. THREE.ShaderChunk[ "default_vertex" ],
  10629. THREE.ShaderChunk[ "worldpos_vertex" ],
  10630. THREE.ShaderChunk[ "envmap_vertex" ],
  10631. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10632. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10633. "}"
  10634. ].join("\n"),
  10635. fragmentShader: [
  10636. "uniform float opacity;",
  10637. "varying vec3 vLightFront;",
  10638. "#ifdef DOUBLE_SIDED",
  10639. "varying vec3 vLightBack;",
  10640. "#endif",
  10641. THREE.ShaderChunk[ "color_pars_fragment" ],
  10642. THREE.ShaderChunk[ "map_pars_fragment" ],
  10643. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10644. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10645. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10646. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10647. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10648. "void main() {",
  10649. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10650. THREE.ShaderChunk[ "map_fragment" ],
  10651. THREE.ShaderChunk[ "alphatest_fragment" ],
  10652. THREE.ShaderChunk[ "specularmap_fragment" ],
  10653. "#ifdef DOUBLE_SIDED",
  10654. //"float isFront = float( gl_FrontFacing );",
  10655. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10656. "if ( gl_FrontFacing )",
  10657. "gl_FragColor.xyz *= vLightFront;",
  10658. "else",
  10659. "gl_FragColor.xyz *= vLightBack;",
  10660. "#else",
  10661. "gl_FragColor.xyz *= vLightFront;",
  10662. "#endif",
  10663. THREE.ShaderChunk[ "lightmap_fragment" ],
  10664. THREE.ShaderChunk[ "color_fragment" ],
  10665. THREE.ShaderChunk[ "envmap_fragment" ],
  10666. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10667. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10668. THREE.ShaderChunk[ "fog_fragment" ],
  10669. "}"
  10670. ].join("\n")
  10671. },
  10672. 'phong': {
  10673. uniforms: THREE.UniformsUtils.merge( [
  10674. THREE.UniformsLib[ "common" ],
  10675. THREE.UniformsLib[ "bump" ],
  10676. THREE.UniformsLib[ "normalmap" ],
  10677. THREE.UniformsLib[ "fog" ],
  10678. THREE.UniformsLib[ "lights" ],
  10679. THREE.UniformsLib[ "shadowmap" ],
  10680. {
  10681. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10682. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10683. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10684. "shininess": { type: "f", value: 30 },
  10685. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10686. }
  10687. ] ),
  10688. vertexShader: [
  10689. "#define PHONG",
  10690. "varying vec3 vViewPosition;",
  10691. "varying vec3 vNormal;",
  10692. THREE.ShaderChunk[ "map_pars_vertex" ],
  10693. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10694. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10695. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10696. THREE.ShaderChunk[ "color_pars_vertex" ],
  10697. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10698. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10699. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10700. "void main() {",
  10701. THREE.ShaderChunk[ "map_vertex" ],
  10702. THREE.ShaderChunk[ "lightmap_vertex" ],
  10703. THREE.ShaderChunk[ "color_vertex" ],
  10704. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10705. THREE.ShaderChunk[ "skinbase_vertex" ],
  10706. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10707. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10708. "vNormal = normalize( transformedNormal );",
  10709. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10710. THREE.ShaderChunk[ "skinning_vertex" ],
  10711. THREE.ShaderChunk[ "default_vertex" ],
  10712. "vViewPosition = -mvPosition.xyz;",
  10713. THREE.ShaderChunk[ "worldpos_vertex" ],
  10714. THREE.ShaderChunk[ "envmap_vertex" ],
  10715. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10716. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10717. "}"
  10718. ].join("\n"),
  10719. fragmentShader: [
  10720. "uniform vec3 diffuse;",
  10721. "uniform float opacity;",
  10722. "uniform vec3 ambient;",
  10723. "uniform vec3 emissive;",
  10724. "uniform vec3 specular;",
  10725. "uniform float shininess;",
  10726. THREE.ShaderChunk[ "color_pars_fragment" ],
  10727. THREE.ShaderChunk[ "map_pars_fragment" ],
  10728. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10729. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10730. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10731. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10732. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10733. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10734. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10735. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10736. "void main() {",
  10737. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10738. THREE.ShaderChunk[ "map_fragment" ],
  10739. THREE.ShaderChunk[ "alphatest_fragment" ],
  10740. THREE.ShaderChunk[ "specularmap_fragment" ],
  10741. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10742. THREE.ShaderChunk[ "lightmap_fragment" ],
  10743. THREE.ShaderChunk[ "color_fragment" ],
  10744. THREE.ShaderChunk[ "envmap_fragment" ],
  10745. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10746. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10747. THREE.ShaderChunk[ "fog_fragment" ],
  10748. "}"
  10749. ].join("\n")
  10750. },
  10751. 'particle_basic': {
  10752. uniforms: THREE.UniformsUtils.merge( [
  10753. THREE.UniformsLib[ "particle" ],
  10754. THREE.UniformsLib[ "shadowmap" ]
  10755. ] ),
  10756. vertexShader: [
  10757. "uniform float size;",
  10758. "uniform float scale;",
  10759. THREE.ShaderChunk[ "color_pars_vertex" ],
  10760. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10761. "void main() {",
  10762. THREE.ShaderChunk[ "color_vertex" ],
  10763. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10764. "#ifdef USE_SIZEATTENUATION",
  10765. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10766. "#else",
  10767. "gl_PointSize = size;",
  10768. "#endif",
  10769. "gl_Position = projectionMatrix * mvPosition;",
  10770. THREE.ShaderChunk[ "worldpos_vertex" ],
  10771. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10772. "}"
  10773. ].join("\n"),
  10774. fragmentShader: [
  10775. "uniform vec3 psColor;",
  10776. "uniform float opacity;",
  10777. THREE.ShaderChunk[ "color_pars_fragment" ],
  10778. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10779. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10780. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10781. "void main() {",
  10782. "gl_FragColor = vec4( psColor, opacity );",
  10783. THREE.ShaderChunk[ "map_particle_fragment" ],
  10784. THREE.ShaderChunk[ "alphatest_fragment" ],
  10785. THREE.ShaderChunk[ "color_fragment" ],
  10786. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10787. THREE.ShaderChunk[ "fog_fragment" ],
  10788. "}"
  10789. ].join("\n")
  10790. },
  10791. 'dashed': {
  10792. uniforms: THREE.UniformsUtils.merge( [
  10793. THREE.UniformsLib[ "common" ],
  10794. THREE.UniformsLib[ "fog" ],
  10795. {
  10796. "scale": { type: "f", value: 1 },
  10797. "dashSize": { type: "f", value: 1 },
  10798. "totalSize": { type: "f", value: 2 }
  10799. }
  10800. ] ),
  10801. vertexShader: [
  10802. "uniform float scale;",
  10803. "attribute float lineDistance;",
  10804. "varying float vLineDistance;",
  10805. THREE.ShaderChunk[ "color_pars_vertex" ],
  10806. "void main() {",
  10807. THREE.ShaderChunk[ "color_vertex" ],
  10808. "vLineDistance = scale * lineDistance;",
  10809. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10810. "gl_Position = projectionMatrix * mvPosition;",
  10811. "}"
  10812. ].join("\n"),
  10813. fragmentShader: [
  10814. "uniform vec3 diffuse;",
  10815. "uniform float opacity;",
  10816. "uniform float dashSize;",
  10817. "uniform float totalSize;",
  10818. "varying float vLineDistance;",
  10819. THREE.ShaderChunk[ "color_pars_fragment" ],
  10820. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10821. "void main() {",
  10822. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10823. "discard;",
  10824. "}",
  10825. "gl_FragColor = vec4( diffuse, opacity );",
  10826. THREE.ShaderChunk[ "color_fragment" ],
  10827. THREE.ShaderChunk[ "fog_fragment" ],
  10828. "}"
  10829. ].join("\n")
  10830. },
  10831. 'depth': {
  10832. uniforms: {
  10833. "mNear": { type: "f", value: 1.0 },
  10834. "mFar" : { type: "f", value: 2000.0 },
  10835. "opacity" : { type: "f", value: 1.0 }
  10836. },
  10837. vertexShader: [
  10838. "void main() {",
  10839. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10840. "}"
  10841. ].join("\n"),
  10842. fragmentShader: [
  10843. "uniform float mNear;",
  10844. "uniform float mFar;",
  10845. "uniform float opacity;",
  10846. "void main() {",
  10847. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10848. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10849. "gl_FragColor = vec4( vec3( color ), opacity );",
  10850. "}"
  10851. ].join("\n")
  10852. },
  10853. 'normal': {
  10854. uniforms: {
  10855. "opacity" : { type: "f", value: 1.0 }
  10856. },
  10857. vertexShader: [
  10858. "varying vec3 vNormal;",
  10859. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10860. "void main() {",
  10861. "vNormal = normalize( normalMatrix * normal );",
  10862. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10863. THREE.ShaderChunk[ "default_vertex" ],
  10864. "}"
  10865. ].join("\n"),
  10866. fragmentShader: [
  10867. "uniform float opacity;",
  10868. "varying vec3 vNormal;",
  10869. "void main() {",
  10870. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10871. "}"
  10872. ].join("\n")
  10873. },
  10874. /* -------------------------------------------------------------------------
  10875. // Normal map shader
  10876. // - Blinn-Phong
  10877. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10878. // - point and directional lights (use with "lights: true" material option)
  10879. ------------------------------------------------------------------------- */
  10880. 'normalmap' : {
  10881. uniforms: THREE.UniformsUtils.merge( [
  10882. THREE.UniformsLib[ "fog" ],
  10883. THREE.UniformsLib[ "lights" ],
  10884. THREE.UniformsLib[ "shadowmap" ],
  10885. {
  10886. "enableAO" : { type: "i", value: 0 },
  10887. "enableDiffuse" : { type: "i", value: 0 },
  10888. "enableSpecular" : { type: "i", value: 0 },
  10889. "enableReflection": { type: "i", value: 0 },
  10890. "enableDisplacement": { type: "i", value: 0 },
  10891. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  10892. "tDiffuse" : { type: "t", value: null },
  10893. "tCube" : { type: "t", value: null },
  10894. "tNormal" : { type: "t", value: null },
  10895. "tSpecular" : { type: "t", value: null },
  10896. "tAO" : { type: "t", value: null },
  10897. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10898. "uDisplacementBias": { type: "f", value: 0.0 },
  10899. "uDisplacementScale": { type: "f", value: 1.0 },
  10900. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10901. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10902. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10903. "uShininess": { type: "f", value: 30 },
  10904. "uOpacity": { type: "f", value: 1 },
  10905. "useRefract": { type: "i", value: 0 },
  10906. "uRefractionRatio": { type: "f", value: 0.98 },
  10907. "uReflectivity": { type: "f", value: 0.5 },
  10908. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  10909. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10910. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10911. }
  10912. ] ),
  10913. fragmentShader: [
  10914. "uniform vec3 uAmbientColor;",
  10915. "uniform vec3 uDiffuseColor;",
  10916. "uniform vec3 uSpecularColor;",
  10917. "uniform float uShininess;",
  10918. "uniform float uOpacity;",
  10919. "uniform bool enableDiffuse;",
  10920. "uniform bool enableSpecular;",
  10921. "uniform bool enableAO;",
  10922. "uniform bool enableReflection;",
  10923. "uniform sampler2D tDiffuse;",
  10924. "uniform sampler2D tNormal;",
  10925. "uniform sampler2D tSpecular;",
  10926. "uniform sampler2D tAO;",
  10927. "uniform samplerCube tCube;",
  10928. "uniform vec2 uNormalScale;",
  10929. "uniform bool useRefract;",
  10930. "uniform float uRefractionRatio;",
  10931. "uniform float uReflectivity;",
  10932. "varying vec3 vTangent;",
  10933. "varying vec3 vBinormal;",
  10934. "varying vec3 vNormal;",
  10935. "varying vec2 vUv;",
  10936. "uniform vec3 ambientLightColor;",
  10937. "#if MAX_DIR_LIGHTS > 0",
  10938. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10939. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10940. "#endif",
  10941. "#if MAX_HEMI_LIGHTS > 0",
  10942. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10943. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10944. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10945. "#endif",
  10946. "#if MAX_POINT_LIGHTS > 0",
  10947. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10948. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10949. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10950. "#endif",
  10951. "#if MAX_SPOT_LIGHTS > 0",
  10952. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10953. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10954. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10955. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10956. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10957. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10958. "#endif",
  10959. "#ifdef WRAP_AROUND",
  10960. "uniform vec3 wrapRGB;",
  10961. "#endif",
  10962. "varying vec3 vWorldPosition;",
  10963. "varying vec3 vViewPosition;",
  10964. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10965. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10966. "void main() {",
  10967. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  10968. "vec3 specularTex = vec3( 1.0 );",
  10969. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  10970. "normalTex.xy *= uNormalScale;",
  10971. "normalTex = normalize( normalTex );",
  10972. "if( enableDiffuse ) {",
  10973. "#ifdef GAMMA_INPUT",
  10974. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  10975. "texelColor.xyz *= texelColor.xyz;",
  10976. "gl_FragColor = gl_FragColor * texelColor;",
  10977. "#else",
  10978. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  10979. "#endif",
  10980. "}",
  10981. "if( enableAO ) {",
  10982. "#ifdef GAMMA_INPUT",
  10983. "vec4 aoColor = texture2D( tAO, vUv );",
  10984. "aoColor.xyz *= aoColor.xyz;",
  10985. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  10986. "#else",
  10987. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  10988. "#endif",
  10989. "}",
  10990. "if( enableSpecular )",
  10991. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  10992. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  10993. "vec3 finalNormal = tsb * normalTex;",
  10994. "#ifdef FLIP_SIDED",
  10995. "finalNormal = -finalNormal;",
  10996. "#endif",
  10997. "vec3 normal = normalize( finalNormal );",
  10998. "vec3 viewPosition = normalize( vViewPosition );",
  10999. // point lights
  11000. "#if MAX_POINT_LIGHTS > 0",
  11001. "vec3 pointDiffuse = vec3( 0.0 );",
  11002. "vec3 pointSpecular = vec3( 0.0 );",
  11003. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11004. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11005. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11006. "float pointDistance = 1.0;",
  11007. "if ( pointLightDistance[ i ] > 0.0 )",
  11008. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11009. "pointVector = normalize( pointVector );",
  11010. // diffuse
  11011. "#ifdef WRAP_AROUND",
  11012. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11013. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11014. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11015. "#else",
  11016. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11017. "#endif",
  11018. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11019. // specular
  11020. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11021. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11022. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11023. "#ifdef PHYSICALLY_BASED_SHADING",
  11024. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11025. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11026. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11027. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11028. "#else",
  11029. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11030. "#endif",
  11031. "}",
  11032. "#endif",
  11033. // spot lights
  11034. "#if MAX_SPOT_LIGHTS > 0",
  11035. "vec3 spotDiffuse = vec3( 0.0 );",
  11036. "vec3 spotSpecular = vec3( 0.0 );",
  11037. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11038. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11039. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11040. "float spotDistance = 1.0;",
  11041. "if ( spotLightDistance[ i ] > 0.0 )",
  11042. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11043. "spotVector = normalize( spotVector );",
  11044. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11045. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11046. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11047. // diffuse
  11048. "#ifdef WRAP_AROUND",
  11049. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11050. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11051. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11052. "#else",
  11053. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11054. "#endif",
  11055. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11056. // specular
  11057. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11058. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11059. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11060. "#ifdef PHYSICALLY_BASED_SHADING",
  11061. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11062. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11063. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11064. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11065. "#else",
  11066. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11067. "#endif",
  11068. "}",
  11069. "}",
  11070. "#endif",
  11071. // directional lights
  11072. "#if MAX_DIR_LIGHTS > 0",
  11073. "vec3 dirDiffuse = vec3( 0.0 );",
  11074. "vec3 dirSpecular = vec3( 0.0 );",
  11075. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11076. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11077. "vec3 dirVector = normalize( lDirection.xyz );",
  11078. // diffuse
  11079. "#ifdef WRAP_AROUND",
  11080. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11081. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11082. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11083. "#else",
  11084. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11085. "#endif",
  11086. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11087. // specular
  11088. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11089. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11090. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11091. "#ifdef PHYSICALLY_BASED_SHADING",
  11092. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11093. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11094. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11095. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11096. "#else",
  11097. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11098. "#endif",
  11099. "}",
  11100. "#endif",
  11101. // hemisphere lights
  11102. "#if MAX_HEMI_LIGHTS > 0",
  11103. "vec3 hemiDiffuse = vec3( 0.0 );",
  11104. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11105. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11106. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11107. "vec3 lVector = normalize( lDirection.xyz );",
  11108. // diffuse
  11109. "float dotProduct = dot( normal, lVector );",
  11110. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11111. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11112. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11113. // specular (sky light)
  11114. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11115. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11116. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11117. // specular (ground light)
  11118. "vec3 lVectorGround = -lVector;",
  11119. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11120. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11121. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11122. "#ifdef PHYSICALLY_BASED_SHADING",
  11123. "float dotProductGround = dot( normal, lVectorGround );",
  11124. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11125. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11126. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11127. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11128. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11129. "#else",
  11130. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11131. "#endif",
  11132. "}",
  11133. "#endif",
  11134. // all lights contribution summation
  11135. "vec3 totalDiffuse = vec3( 0.0 );",
  11136. "vec3 totalSpecular = vec3( 0.0 );",
  11137. "#if MAX_DIR_LIGHTS > 0",
  11138. "totalDiffuse += dirDiffuse;",
  11139. "totalSpecular += dirSpecular;",
  11140. "#endif",
  11141. "#if MAX_HEMI_LIGHTS > 0",
  11142. "totalDiffuse += hemiDiffuse;",
  11143. "totalSpecular += hemiSpecular;",
  11144. "#endif",
  11145. "#if MAX_POINT_LIGHTS > 0",
  11146. "totalDiffuse += pointDiffuse;",
  11147. "totalSpecular += pointSpecular;",
  11148. "#endif",
  11149. "#if MAX_SPOT_LIGHTS > 0",
  11150. "totalDiffuse += spotDiffuse;",
  11151. "totalSpecular += spotSpecular;",
  11152. "#endif",
  11153. "#ifdef METAL",
  11154. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11155. "#else",
  11156. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11157. "#endif",
  11158. "if ( enableReflection ) {",
  11159. "vec3 vReflect;",
  11160. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11161. "if ( useRefract ) {",
  11162. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11163. "} else {",
  11164. "vReflect = reflect( cameraToVertex, normal );",
  11165. "}",
  11166. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11167. "#ifdef GAMMA_INPUT",
  11168. "cubeColor.xyz *= cubeColor.xyz;",
  11169. "#endif",
  11170. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11171. "}",
  11172. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11173. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11174. THREE.ShaderChunk[ "fog_fragment" ],
  11175. "}"
  11176. ].join("\n"),
  11177. vertexShader: [
  11178. "attribute vec4 tangent;",
  11179. "uniform vec2 uOffset;",
  11180. "uniform vec2 uRepeat;",
  11181. "uniform bool enableDisplacement;",
  11182. "#ifdef VERTEX_TEXTURES",
  11183. "uniform sampler2D tDisplacement;",
  11184. "uniform float uDisplacementScale;",
  11185. "uniform float uDisplacementBias;",
  11186. "#endif",
  11187. "varying vec3 vTangent;",
  11188. "varying vec3 vBinormal;",
  11189. "varying vec3 vNormal;",
  11190. "varying vec2 vUv;",
  11191. "varying vec3 vWorldPosition;",
  11192. "varying vec3 vViewPosition;",
  11193. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11194. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11195. "void main() {",
  11196. THREE.ShaderChunk[ "skinbase_vertex" ],
  11197. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11198. // normal, tangent and binormal vectors
  11199. "#ifdef USE_SKINNING",
  11200. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11201. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11202. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11203. "#else",
  11204. "vNormal = normalize( normalMatrix * normal );",
  11205. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11206. "#endif",
  11207. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11208. "vUv = uv * uRepeat + uOffset;",
  11209. // displacement mapping
  11210. "vec3 displacedPosition;",
  11211. "#ifdef VERTEX_TEXTURES",
  11212. "if ( enableDisplacement ) {",
  11213. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11214. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11215. "displacedPosition = position + normalize( normal ) * df;",
  11216. "} else {",
  11217. "#ifdef USE_SKINNING",
  11218. "vec4 skinVertex = vec4( position, 1.0 );",
  11219. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11220. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11221. "displacedPosition = skinned.xyz;",
  11222. "#else",
  11223. "displacedPosition = position;",
  11224. "#endif",
  11225. "}",
  11226. "#else",
  11227. "#ifdef USE_SKINNING",
  11228. "vec4 skinVertex = vec4( position, 1.0 );",
  11229. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11230. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11231. "displacedPosition = skinned.xyz;",
  11232. "#else",
  11233. "displacedPosition = position;",
  11234. "#endif",
  11235. "#endif",
  11236. //
  11237. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11238. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11239. "gl_Position = projectionMatrix * mvPosition;",
  11240. //
  11241. "vWorldPosition = worldPosition.xyz;",
  11242. "vViewPosition = -mvPosition.xyz;",
  11243. // shadows
  11244. "#ifdef USE_SHADOWMAP",
  11245. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11246. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11247. "}",
  11248. "#endif",
  11249. "}"
  11250. ].join("\n")
  11251. },
  11252. /* -------------------------------------------------------------------------
  11253. // Cube map shader
  11254. ------------------------------------------------------------------------- */
  11255. 'cube': {
  11256. uniforms: { "tCube": { type: "t", value: null },
  11257. "tFlip": { type: "f", value: -1 } },
  11258. vertexShader: [
  11259. "varying vec3 vWorldPosition;",
  11260. "void main() {",
  11261. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11262. "vWorldPosition = worldPosition.xyz;",
  11263. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11264. "}"
  11265. ].join("\n"),
  11266. fragmentShader: [
  11267. "uniform samplerCube tCube;",
  11268. "uniform float tFlip;",
  11269. "varying vec3 vWorldPosition;",
  11270. "void main() {",
  11271. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11272. "}"
  11273. ].join("\n")
  11274. },
  11275. // Depth encoding into RGBA texture
  11276. // based on SpiderGL shadow map example
  11277. // http://spidergl.org/example.php?id=6
  11278. // originally from
  11279. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11280. // see also here:
  11281. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11282. 'depthRGBA': {
  11283. uniforms: {},
  11284. vertexShader: [
  11285. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11286. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11287. "void main() {",
  11288. THREE.ShaderChunk[ "skinbase_vertex" ],
  11289. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11290. THREE.ShaderChunk[ "skinning_vertex" ],
  11291. THREE.ShaderChunk[ "default_vertex" ],
  11292. "}"
  11293. ].join("\n"),
  11294. fragmentShader: [
  11295. "vec4 pack_depth( const in float depth ) {",
  11296. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11297. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11298. "vec4 res = fract( depth * bit_shift );",
  11299. "res -= res.xxyz * bit_mask;",
  11300. "return res;",
  11301. "}",
  11302. "void main() {",
  11303. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11304. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11305. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11306. //"gl_FragData[ 0 ] = pack_depth( z );",
  11307. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11308. "}"
  11309. ].join("\n")
  11310. }
  11311. };
  11312. /**
  11313. * @author supereggbert / http://www.paulbrunt.co.uk/
  11314. * @author mrdoob / http://mrdoob.com/
  11315. * @author alteredq / http://alteredqualia.com/
  11316. * @author szimek / https://github.com/szimek/
  11317. */
  11318. THREE.WebGLRenderer = function ( parameters ) {
  11319. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11320. parameters = parameters || {};
  11321. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11322. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11323. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  11324. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11325. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11326. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11327. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11328. _clearColor = new THREE.Color( 0x000000 ),
  11329. _clearAlpha = 0;
  11330. if ( parameters.clearColor !== undefined ) {
  11331. console.warn( 'DEPRECATED: clearColor in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11332. _clearColor.setHex( parameters.clearColor );
  11333. }
  11334. if ( parameters.clearAlpha !== undefined ) {
  11335. console.warn( 'DEPRECATED: clearAlpha in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11336. _clearAlpha = parameters.clearAlpha;
  11337. }
  11338. // public properties
  11339. this.domElement = _canvas;
  11340. this.context = null;
  11341. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11342. ? parameters.devicePixelRatio
  11343. : window.devicePixelRatio !== undefined
  11344. ? window.devicePixelRatio
  11345. : 1;
  11346. // clearing
  11347. this.autoClear = true;
  11348. this.autoClearColor = true;
  11349. this.autoClearDepth = true;
  11350. this.autoClearStencil = true;
  11351. // scene graph
  11352. this.sortObjects = true;
  11353. this.autoUpdateObjects = true;
  11354. // physically based shading
  11355. this.gammaInput = false;
  11356. this.gammaOutput = false;
  11357. this.physicallyBasedShading = false;
  11358. // shadow map
  11359. this.shadowMapEnabled = false;
  11360. this.shadowMapAutoUpdate = true;
  11361. this.shadowMapType = THREE.PCFShadowMap;
  11362. this.shadowMapCullFace = THREE.CullFaceFront;
  11363. this.shadowMapDebug = false;
  11364. this.shadowMapCascade = false;
  11365. // morphs
  11366. this.maxMorphTargets = 8;
  11367. this.maxMorphNormals = 4;
  11368. // flags
  11369. this.autoScaleCubemaps = true;
  11370. // custom render plugins
  11371. this.renderPluginsPre = [];
  11372. this.renderPluginsPost = [];
  11373. // info
  11374. this.info = {
  11375. memory: {
  11376. programs: 0,
  11377. geometries: 0,
  11378. textures: 0
  11379. },
  11380. render: {
  11381. calls: 0,
  11382. vertices: 0,
  11383. faces: 0,
  11384. points: 0
  11385. }
  11386. };
  11387. // internal properties
  11388. var _this = this,
  11389. _programs = [],
  11390. _programs_counter = 0,
  11391. // internal state cache
  11392. _currentProgram = null,
  11393. _currentFramebuffer = null,
  11394. _currentMaterialId = -1,
  11395. _currentGeometryGroupHash = null,
  11396. _currentCamera = null,
  11397. _geometryGroupCounter = 0,
  11398. _usedTextureUnits = 0,
  11399. // GL state cache
  11400. _oldDoubleSided = -1,
  11401. _oldFlipSided = -1,
  11402. _oldBlending = -1,
  11403. _oldBlendEquation = -1,
  11404. _oldBlendSrc = -1,
  11405. _oldBlendDst = -1,
  11406. _oldDepthTest = -1,
  11407. _oldDepthWrite = -1,
  11408. _oldPolygonOffset = null,
  11409. _oldPolygonOffsetFactor = null,
  11410. _oldPolygonOffsetUnits = null,
  11411. _oldLineWidth = null,
  11412. _viewportX = 0,
  11413. _viewportY = 0,
  11414. _viewportWidth = 0,
  11415. _viewportHeight = 0,
  11416. _currentWidth = 0,
  11417. _currentHeight = 0,
  11418. _enabledAttributes = {},
  11419. // frustum
  11420. _frustum = new THREE.Frustum(),
  11421. // camera matrices cache
  11422. _projScreenMatrix = new THREE.Matrix4(),
  11423. _projScreenMatrixPS = new THREE.Matrix4(),
  11424. _vector3 = new THREE.Vector3(),
  11425. // light arrays cache
  11426. _direction = new THREE.Vector3(),
  11427. _lightsNeedUpdate = true,
  11428. _lights = {
  11429. ambient: [ 0, 0, 0 ],
  11430. directional: { length: 0, colors: new Array(), positions: new Array() },
  11431. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11432. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11433. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11434. };
  11435. // initialize
  11436. var _gl;
  11437. var _glExtensionTextureFloat;
  11438. var _glExtensionTextureFloatLinear;
  11439. var _glExtensionStandardDerivatives;
  11440. var _glExtensionTextureFilterAnisotropic;
  11441. var _glExtensionCompressedTextureS3TC;
  11442. initGL();
  11443. setDefaultGLState();
  11444. this.context = _gl;
  11445. // GPU capabilities
  11446. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11447. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11448. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11449. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11450. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11451. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11452. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11453. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11454. //
  11455. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11456. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11457. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11458. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11459. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11460. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11461. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11462. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11463. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11464. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11465. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11466. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11467. // clamp precision to maximum available
  11468. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11469. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11470. if ( _precision === "highp" && ! highpAvailable ) {
  11471. if ( mediumpAvailable ) {
  11472. _precision = "mediump";
  11473. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11474. } else {
  11475. _precision = "lowp";
  11476. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11477. }
  11478. }
  11479. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11480. _precision = "lowp";
  11481. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11482. }
  11483. // API
  11484. this.getContext = function () {
  11485. return _gl;
  11486. };
  11487. this.supportsVertexTextures = function () {
  11488. return _supportsVertexTextures;
  11489. };
  11490. this.supportsFloatTextures = function () {
  11491. return _glExtensionTextureFloat;
  11492. };
  11493. this.supportsStandardDerivatives = function () {
  11494. return _glExtensionStandardDerivatives;
  11495. };
  11496. this.supportsCompressedTextureS3TC = function () {
  11497. return _glExtensionCompressedTextureS3TC;
  11498. };
  11499. this.getMaxAnisotropy = function () {
  11500. return _maxAnisotropy;
  11501. };
  11502. this.getPrecision = function () {
  11503. return _precision;
  11504. };
  11505. this.setSize = function ( width, height, updateStyle ) {
  11506. _canvas.width = width * this.devicePixelRatio;
  11507. _canvas.height = height * this.devicePixelRatio;
  11508. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11509. _canvas.style.width = width + 'px';
  11510. _canvas.style.height = height + 'px';
  11511. }
  11512. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11513. };
  11514. this.setViewport = function ( x, y, width, height ) {
  11515. _viewportX = x !== undefined ? x : 0;
  11516. _viewportY = y !== undefined ? y : 0;
  11517. _viewportWidth = width !== undefined ? width : _canvas.width;
  11518. _viewportHeight = height !== undefined ? height : _canvas.height;
  11519. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11520. };
  11521. this.setScissor = function ( x, y, width, height ) {
  11522. _gl.scissor( x, y, width, height );
  11523. };
  11524. this.enableScissorTest = function ( enable ) {
  11525. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11526. };
  11527. // Clearing
  11528. this.setClearColor = function ( color, alpha ) {
  11529. _clearColor.set( color );
  11530. _clearAlpha = alpha !== undefined ? alpha : 1;
  11531. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11532. };
  11533. this.setClearColorHex = function ( hex, alpha ) {
  11534. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11535. this.setClearColor( hex, alpha );
  11536. };
  11537. this.getClearColor = function () {
  11538. return _clearColor;
  11539. };
  11540. this.getClearAlpha = function () {
  11541. return _clearAlpha;
  11542. };
  11543. this.clear = function ( color, depth, stencil ) {
  11544. var bits = 0;
  11545. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11546. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11547. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11548. _gl.clear( bits );
  11549. };
  11550. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11551. this.setRenderTarget( renderTarget );
  11552. this.clear( color, depth, stencil );
  11553. };
  11554. // Plugins
  11555. this.addPostPlugin = function ( plugin ) {
  11556. plugin.init( this );
  11557. this.renderPluginsPost.push( plugin );
  11558. };
  11559. this.addPrePlugin = function ( plugin ) {
  11560. plugin.init( this );
  11561. this.renderPluginsPre.push( plugin );
  11562. };
  11563. // Rendering
  11564. this.updateShadowMap = function ( scene, camera ) {
  11565. _currentProgram = null;
  11566. _oldBlending = -1;
  11567. _oldDepthTest = -1;
  11568. _oldDepthWrite = -1;
  11569. _currentGeometryGroupHash = -1;
  11570. _currentMaterialId = -1;
  11571. _lightsNeedUpdate = true;
  11572. _oldDoubleSided = -1;
  11573. _oldFlipSided = -1;
  11574. this.shadowMapPlugin.update( scene, camera );
  11575. };
  11576. // Internal functions
  11577. // Buffer allocation
  11578. function createParticleBuffers ( geometry ) {
  11579. geometry.__webglVertexBuffer = _gl.createBuffer();
  11580. geometry.__webglColorBuffer = _gl.createBuffer();
  11581. _this.info.memory.geometries ++;
  11582. };
  11583. function createLineBuffers ( geometry ) {
  11584. geometry.__webglVertexBuffer = _gl.createBuffer();
  11585. geometry.__webglColorBuffer = _gl.createBuffer();
  11586. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11587. _this.info.memory.geometries ++;
  11588. };
  11589. function createRibbonBuffers ( geometry ) {
  11590. geometry.__webglVertexBuffer = _gl.createBuffer();
  11591. geometry.__webglColorBuffer = _gl.createBuffer();
  11592. geometry.__webglNormalBuffer = _gl.createBuffer();
  11593. _this.info.memory.geometries ++;
  11594. };
  11595. function createMeshBuffers ( geometryGroup ) {
  11596. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11597. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11598. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11599. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11600. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11601. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11602. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11603. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11604. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11605. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11606. var m, ml;
  11607. if ( geometryGroup.numMorphTargets ) {
  11608. geometryGroup.__webglMorphTargetsBuffers = [];
  11609. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11610. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11611. }
  11612. }
  11613. if ( geometryGroup.numMorphNormals ) {
  11614. geometryGroup.__webglMorphNormalsBuffers = [];
  11615. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11616. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11617. }
  11618. }
  11619. _this.info.memory.geometries ++;
  11620. };
  11621. // Events
  11622. var onGeometryDispose = function ( event ) {
  11623. var geometry = event.target;
  11624. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11625. deallocateGeometry( geometry );
  11626. _this.info.memory.geometries --;
  11627. };
  11628. var onTextureDispose = function ( event ) {
  11629. var texture = event.target;
  11630. texture.removeEventListener( 'dispose', onTextureDispose );
  11631. deallocateTexture( texture );
  11632. _this.info.memory.textures --;
  11633. };
  11634. var onRenderTargetDispose = function ( event ) {
  11635. var renderTarget = event.target;
  11636. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11637. deallocateRenderTarget( renderTarget );
  11638. _this.info.memory.textures --;
  11639. };
  11640. var onMaterialDispose = function ( event ) {
  11641. var material = event.target;
  11642. material.removeEventListener( 'dispose', onMaterialDispose );
  11643. deallocateMaterial( material );
  11644. };
  11645. // Buffer deallocation
  11646. var deallocateGeometry = function ( geometry ) {
  11647. geometry.__webglInit = undefined;
  11648. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11649. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11650. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11651. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11652. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11653. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11654. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11655. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11656. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11657. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11658. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11659. // geometry groups
  11660. if ( geometry.geometryGroups !== undefined ) {
  11661. for ( var g in geometry.geometryGroups ) {
  11662. var geometryGroup = geometry.geometryGroups[ g ];
  11663. if ( geometryGroup.numMorphTargets !== undefined ) {
  11664. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11665. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11666. }
  11667. }
  11668. if ( geometryGroup.numMorphNormals !== undefined ) {
  11669. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11670. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11671. }
  11672. }
  11673. deleteCustomAttributesBuffers( geometryGroup );
  11674. }
  11675. }
  11676. deleteCustomAttributesBuffers( geometry );
  11677. };
  11678. var deallocateTexture = function ( texture ) {
  11679. if ( texture.image && texture.image.__webglTextureCube ) {
  11680. // cube texture
  11681. _gl.deleteTexture( texture.image.__webglTextureCube );
  11682. } else {
  11683. // 2D texture
  11684. if ( ! texture.__webglInit ) return;
  11685. texture.__webglInit = false;
  11686. _gl.deleteTexture( texture.__webglTexture );
  11687. }
  11688. };
  11689. var deallocateRenderTarget = function ( renderTarget ) {
  11690. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11691. _gl.deleteTexture( renderTarget.__webglTexture );
  11692. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11693. for ( var i = 0; i < 6; i ++ ) {
  11694. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11695. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11696. }
  11697. } else {
  11698. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11699. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11700. }
  11701. };
  11702. var deallocateMaterial = function ( material ) {
  11703. var program = material.program;
  11704. if ( program === undefined ) return;
  11705. material.program = undefined;
  11706. // only deallocate GL program if this was the last use of shared program
  11707. // assumed there is only single copy of any program in the _programs list
  11708. // (that's how it's constructed)
  11709. var i, il, programInfo;
  11710. var deleteProgram = false;
  11711. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11712. programInfo = _programs[ i ];
  11713. if ( programInfo.program === program ) {
  11714. programInfo.usedTimes --;
  11715. if ( programInfo.usedTimes === 0 ) {
  11716. deleteProgram = true;
  11717. }
  11718. break;
  11719. }
  11720. }
  11721. if ( deleteProgram === true ) {
  11722. // avoid using array.splice, this is costlier than creating new array from scratch
  11723. var newPrograms = [];
  11724. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11725. programInfo = _programs[ i ];
  11726. if ( programInfo.program !== program ) {
  11727. newPrograms.push( programInfo );
  11728. }
  11729. }
  11730. _programs = newPrograms;
  11731. _gl.deleteProgram( program );
  11732. _this.info.memory.programs --;
  11733. }
  11734. };
  11735. //
  11736. function deleteCustomAttributesBuffers( geometry ) {
  11737. if ( geometry.__webglCustomAttributesList ) {
  11738. for ( var id in geometry.__webglCustomAttributesList ) {
  11739. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11740. }
  11741. }
  11742. };
  11743. // Buffer initialization
  11744. function initCustomAttributes ( geometry, object ) {
  11745. var nvertices = geometry.vertices.length;
  11746. var material = object.material;
  11747. if ( material.attributes ) {
  11748. if ( geometry.__webglCustomAttributesList === undefined ) {
  11749. geometry.__webglCustomAttributesList = [];
  11750. }
  11751. for ( var a in material.attributes ) {
  11752. var attribute = material.attributes[ a ];
  11753. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11754. attribute.__webglInitialized = true;
  11755. var size = 1; // "f" and "i"
  11756. if ( attribute.type === "v2" ) size = 2;
  11757. else if ( attribute.type === "v3" ) size = 3;
  11758. else if ( attribute.type === "v4" ) size = 4;
  11759. else if ( attribute.type === "c" ) size = 3;
  11760. attribute.size = size;
  11761. attribute.array = new Float32Array( nvertices * size );
  11762. attribute.buffer = _gl.createBuffer();
  11763. attribute.buffer.belongsToAttribute = a;
  11764. attribute.needsUpdate = true;
  11765. }
  11766. geometry.__webglCustomAttributesList.push( attribute );
  11767. }
  11768. }
  11769. };
  11770. function initParticleBuffers ( geometry, object ) {
  11771. var nvertices = geometry.vertices.length;
  11772. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11773. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11774. geometry.__sortArray = [];
  11775. geometry.__webglParticleCount = nvertices;
  11776. initCustomAttributes ( geometry, object );
  11777. };
  11778. function initLineBuffers ( geometry, object ) {
  11779. var nvertices = geometry.vertices.length;
  11780. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11781. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11782. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11783. geometry.__webglLineCount = nvertices;
  11784. initCustomAttributes ( geometry, object );
  11785. };
  11786. function initRibbonBuffers ( geometry, object ) {
  11787. var nvertices = geometry.vertices.length;
  11788. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11789. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11790. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11791. geometry.__webglVertexCount = nvertices;
  11792. initCustomAttributes ( geometry, object );
  11793. };
  11794. function initMeshBuffers ( geometryGroup, object ) {
  11795. var geometry = object.geometry,
  11796. faces3 = geometryGroup.faces3,
  11797. faces4 = geometryGroup.faces4,
  11798. nvertices = faces3.length * 3 + faces4.length * 4,
  11799. ntris = faces3.length * 1 + faces4.length * 2,
  11800. nlines = faces3.length * 3 + faces4.length * 4,
  11801. material = getBufferMaterial( object, geometryGroup ),
  11802. uvType = bufferGuessUVType( material ),
  11803. normalType = bufferGuessNormalType( material ),
  11804. vertexColorType = bufferGuessVertexColorType( material );
  11805. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11806. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11807. if ( normalType ) {
  11808. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11809. }
  11810. if ( geometry.hasTangents ) {
  11811. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11812. }
  11813. if ( vertexColorType ) {
  11814. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11815. }
  11816. if ( uvType ) {
  11817. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11818. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11819. }
  11820. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11821. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11822. }
  11823. }
  11824. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11825. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11826. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11827. }
  11828. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11829. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11830. var m, ml;
  11831. if ( geometryGroup.numMorphTargets ) {
  11832. geometryGroup.__morphTargetsArrays = [];
  11833. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11834. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11835. }
  11836. }
  11837. if ( geometryGroup.numMorphNormals ) {
  11838. geometryGroup.__morphNormalsArrays = [];
  11839. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11840. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11841. }
  11842. }
  11843. geometryGroup.__webglFaceCount = ntris * 3;
  11844. geometryGroup.__webglLineCount = nlines * 2;
  11845. // custom attributes
  11846. if ( material.attributes ) {
  11847. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11848. geometryGroup.__webglCustomAttributesList = [];
  11849. }
  11850. for ( var a in material.attributes ) {
  11851. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11852. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11853. var originalAttribute = material.attributes[ a ];
  11854. var attribute = {};
  11855. for ( var property in originalAttribute ) {
  11856. attribute[ property ] = originalAttribute[ property ];
  11857. }
  11858. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11859. attribute.__webglInitialized = true;
  11860. var size = 1; // "f" and "i"
  11861. if( attribute.type === "v2" ) size = 2;
  11862. else if( attribute.type === "v3" ) size = 3;
  11863. else if( attribute.type === "v4" ) size = 4;
  11864. else if( attribute.type === "c" ) size = 3;
  11865. attribute.size = size;
  11866. attribute.array = new Float32Array( nvertices * size );
  11867. attribute.buffer = _gl.createBuffer();
  11868. attribute.buffer.belongsToAttribute = a;
  11869. originalAttribute.needsUpdate = true;
  11870. attribute.__original = originalAttribute;
  11871. }
  11872. geometryGroup.__webglCustomAttributesList.push( attribute );
  11873. }
  11874. }
  11875. geometryGroup.__inittedArrays = true;
  11876. };
  11877. function getBufferMaterial( object, geometryGroup ) {
  11878. return object.material instanceof THREE.MeshFaceMaterial
  11879. ? object.material.materials[ geometryGroup.materialIndex ]
  11880. : object.material;
  11881. };
  11882. function materialNeedsSmoothNormals ( material ) {
  11883. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11884. };
  11885. function bufferGuessNormalType ( material ) {
  11886. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  11887. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  11888. return false;
  11889. }
  11890. if ( materialNeedsSmoothNormals( material ) ) {
  11891. return THREE.SmoothShading;
  11892. } else {
  11893. return THREE.FlatShading;
  11894. }
  11895. };
  11896. function bufferGuessVertexColorType( material ) {
  11897. if ( material.vertexColors ) {
  11898. return material.vertexColors;
  11899. }
  11900. return false;
  11901. };
  11902. function bufferGuessUVType( material ) {
  11903. // material must use some texture to require uvs
  11904. if ( material.map ||
  11905. material.lightMap ||
  11906. material.bumpMap ||
  11907. material.normalMap ||
  11908. material.specularMap ||
  11909. material instanceof THREE.ShaderMaterial ) {
  11910. return true;
  11911. }
  11912. return false;
  11913. };
  11914. //
  11915. function initDirectBuffers( geometry ) {
  11916. var a, attribute, type;
  11917. for ( a in geometry.attributes ) {
  11918. if ( a === "index" ) {
  11919. type = _gl.ELEMENT_ARRAY_BUFFER;
  11920. } else {
  11921. type = _gl.ARRAY_BUFFER;
  11922. }
  11923. attribute = geometry.attributes[ a ];
  11924. if ( attribute.numItems === undefined ) {
  11925. attribute.numItems = attribute.array.length;
  11926. }
  11927. attribute.buffer = _gl.createBuffer();
  11928. _gl.bindBuffer( type, attribute.buffer );
  11929. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  11930. }
  11931. };
  11932. // Buffer setting
  11933. function setParticleBuffers ( geometry, hint, object ) {
  11934. var v, c, vertex, offset, index, color,
  11935. vertices = geometry.vertices,
  11936. vl = vertices.length,
  11937. colors = geometry.colors,
  11938. cl = colors.length,
  11939. vertexArray = geometry.__vertexArray,
  11940. colorArray = geometry.__colorArray,
  11941. sortArray = geometry.__sortArray,
  11942. dirtyVertices = geometry.verticesNeedUpdate,
  11943. dirtyElements = geometry.elementsNeedUpdate,
  11944. dirtyColors = geometry.colorsNeedUpdate,
  11945. customAttributes = geometry.__webglCustomAttributesList,
  11946. i, il,
  11947. a, ca, cal, value,
  11948. customAttribute;
  11949. if ( object.sortParticles ) {
  11950. _projScreenMatrixPS.copy( _projScreenMatrix );
  11951. _projScreenMatrixPS.multiply( object.matrixWorld );
  11952. for ( v = 0; v < vl; v ++ ) {
  11953. vertex = vertices[ v ];
  11954. _vector3.copy( vertex );
  11955. _vector3.applyProjection( _projScreenMatrixPS );
  11956. sortArray[ v ] = [ _vector3.z, v ];
  11957. }
  11958. sortArray.sort( numericalSort );
  11959. for ( v = 0; v < vl; v ++ ) {
  11960. vertex = vertices[ sortArray[v][1] ];
  11961. offset = v * 3;
  11962. vertexArray[ offset ] = vertex.x;
  11963. vertexArray[ offset + 1 ] = vertex.y;
  11964. vertexArray[ offset + 2 ] = vertex.z;
  11965. }
  11966. for ( c = 0; c < cl; c ++ ) {
  11967. offset = c * 3;
  11968. color = colors[ sortArray[c][1] ];
  11969. colorArray[ offset ] = color.r;
  11970. colorArray[ offset + 1 ] = color.g;
  11971. colorArray[ offset + 2 ] = color.b;
  11972. }
  11973. if ( customAttributes ) {
  11974. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11975. customAttribute = customAttributes[ i ];
  11976. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  11977. offset = 0;
  11978. cal = customAttribute.value.length;
  11979. if ( customAttribute.size === 1 ) {
  11980. for ( ca = 0; ca < cal; ca ++ ) {
  11981. index = sortArray[ ca ][ 1 ];
  11982. customAttribute.array[ ca ] = customAttribute.value[ index ];
  11983. }
  11984. } else if ( customAttribute.size === 2 ) {
  11985. for ( ca = 0; ca < cal; ca ++ ) {
  11986. index = sortArray[ ca ][ 1 ];
  11987. value = customAttribute.value[ index ];
  11988. customAttribute.array[ offset ] = value.x;
  11989. customAttribute.array[ offset + 1 ] = value.y;
  11990. offset += 2;
  11991. }
  11992. } else if ( customAttribute.size === 3 ) {
  11993. if ( customAttribute.type === "c" ) {
  11994. for ( ca = 0; ca < cal; ca ++ ) {
  11995. index = sortArray[ ca ][ 1 ];
  11996. value = customAttribute.value[ index ];
  11997. customAttribute.array[ offset ] = value.r;
  11998. customAttribute.array[ offset + 1 ] = value.g;
  11999. customAttribute.array[ offset + 2 ] = value.b;
  12000. offset += 3;
  12001. }
  12002. } else {
  12003. for ( ca = 0; ca < cal; ca ++ ) {
  12004. index = sortArray[ ca ][ 1 ];
  12005. value = customAttribute.value[ index ];
  12006. customAttribute.array[ offset ] = value.x;
  12007. customAttribute.array[ offset + 1 ] = value.y;
  12008. customAttribute.array[ offset + 2 ] = value.z;
  12009. offset += 3;
  12010. }
  12011. }
  12012. } else if ( customAttribute.size === 4 ) {
  12013. for ( ca = 0; ca < cal; ca ++ ) {
  12014. index = sortArray[ ca ][ 1 ];
  12015. value = customAttribute.value[ index ];
  12016. customAttribute.array[ offset ] = value.x;
  12017. customAttribute.array[ offset + 1 ] = value.y;
  12018. customAttribute.array[ offset + 2 ] = value.z;
  12019. customAttribute.array[ offset + 3 ] = value.w;
  12020. offset += 4;
  12021. }
  12022. }
  12023. }
  12024. }
  12025. } else {
  12026. if ( dirtyVertices ) {
  12027. for ( v = 0; v < vl; v ++ ) {
  12028. vertex = vertices[ v ];
  12029. offset = v * 3;
  12030. vertexArray[ offset ] = vertex.x;
  12031. vertexArray[ offset + 1 ] = vertex.y;
  12032. vertexArray[ offset + 2 ] = vertex.z;
  12033. }
  12034. }
  12035. if ( dirtyColors ) {
  12036. for ( c = 0; c < cl; c ++ ) {
  12037. color = colors[ c ];
  12038. offset = c * 3;
  12039. colorArray[ offset ] = color.r;
  12040. colorArray[ offset + 1 ] = color.g;
  12041. colorArray[ offset + 2 ] = color.b;
  12042. }
  12043. }
  12044. if ( customAttributes ) {
  12045. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12046. customAttribute = customAttributes[ i ];
  12047. if ( customAttribute.needsUpdate &&
  12048. ( customAttribute.boundTo === undefined ||
  12049. customAttribute.boundTo === "vertices") ) {
  12050. cal = customAttribute.value.length;
  12051. offset = 0;
  12052. if ( customAttribute.size === 1 ) {
  12053. for ( ca = 0; ca < cal; ca ++ ) {
  12054. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12055. }
  12056. } else if ( customAttribute.size === 2 ) {
  12057. for ( ca = 0; ca < cal; ca ++ ) {
  12058. value = customAttribute.value[ ca ];
  12059. customAttribute.array[ offset ] = value.x;
  12060. customAttribute.array[ offset + 1 ] = value.y;
  12061. offset += 2;
  12062. }
  12063. } else if ( customAttribute.size === 3 ) {
  12064. if ( customAttribute.type === "c" ) {
  12065. for ( ca = 0; ca < cal; ca ++ ) {
  12066. value = customAttribute.value[ ca ];
  12067. customAttribute.array[ offset ] = value.r;
  12068. customAttribute.array[ offset + 1 ] = value.g;
  12069. customAttribute.array[ offset + 2 ] = value.b;
  12070. offset += 3;
  12071. }
  12072. } else {
  12073. for ( ca = 0; ca < cal; ca ++ ) {
  12074. value = customAttribute.value[ ca ];
  12075. customAttribute.array[ offset ] = value.x;
  12076. customAttribute.array[ offset + 1 ] = value.y;
  12077. customAttribute.array[ offset + 2 ] = value.z;
  12078. offset += 3;
  12079. }
  12080. }
  12081. } else if ( customAttribute.size === 4 ) {
  12082. for ( ca = 0; ca < cal; ca ++ ) {
  12083. value = customAttribute.value[ ca ];
  12084. customAttribute.array[ offset ] = value.x;
  12085. customAttribute.array[ offset + 1 ] = value.y;
  12086. customAttribute.array[ offset + 2 ] = value.z;
  12087. customAttribute.array[ offset + 3 ] = value.w;
  12088. offset += 4;
  12089. }
  12090. }
  12091. }
  12092. }
  12093. }
  12094. }
  12095. if ( dirtyVertices || object.sortParticles ) {
  12096. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12097. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12098. }
  12099. if ( dirtyColors || object.sortParticles ) {
  12100. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12101. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12102. }
  12103. if ( customAttributes ) {
  12104. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12105. customAttribute = customAttributes[ i ];
  12106. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12107. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12108. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12109. }
  12110. }
  12111. }
  12112. };
  12113. function setLineBuffers ( geometry, hint ) {
  12114. var v, c, d, vertex, offset, color,
  12115. vertices = geometry.vertices,
  12116. colors = geometry.colors,
  12117. lineDistances = geometry.lineDistances,
  12118. vl = vertices.length,
  12119. cl = colors.length,
  12120. dl = lineDistances.length,
  12121. vertexArray = geometry.__vertexArray,
  12122. colorArray = geometry.__colorArray,
  12123. lineDistanceArray = geometry.__lineDistanceArray,
  12124. dirtyVertices = geometry.verticesNeedUpdate,
  12125. dirtyColors = geometry.colorsNeedUpdate,
  12126. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12127. customAttributes = geometry.__webglCustomAttributesList,
  12128. i, il,
  12129. a, ca, cal, value,
  12130. customAttribute;
  12131. if ( dirtyVertices ) {
  12132. for ( v = 0; v < vl; v ++ ) {
  12133. vertex = vertices[ v ];
  12134. offset = v * 3;
  12135. vertexArray[ offset ] = vertex.x;
  12136. vertexArray[ offset + 1 ] = vertex.y;
  12137. vertexArray[ offset + 2 ] = vertex.z;
  12138. }
  12139. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12140. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12141. }
  12142. if ( dirtyColors ) {
  12143. for ( c = 0; c < cl; c ++ ) {
  12144. color = colors[ c ];
  12145. offset = c * 3;
  12146. colorArray[ offset ] = color.r;
  12147. colorArray[ offset + 1 ] = color.g;
  12148. colorArray[ offset + 2 ] = color.b;
  12149. }
  12150. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12151. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12152. }
  12153. if ( dirtyLineDistances ) {
  12154. for ( d = 0; d < dl; d ++ ) {
  12155. lineDistanceArray[ d ] = lineDistances[ d ];
  12156. }
  12157. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12158. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12159. }
  12160. if ( customAttributes ) {
  12161. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12162. customAttribute = customAttributes[ i ];
  12163. if ( customAttribute.needsUpdate &&
  12164. ( customAttribute.boundTo === undefined ||
  12165. customAttribute.boundTo === "vertices" ) ) {
  12166. offset = 0;
  12167. cal = customAttribute.value.length;
  12168. if ( customAttribute.size === 1 ) {
  12169. for ( ca = 0; ca < cal; ca ++ ) {
  12170. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12171. }
  12172. } else if ( customAttribute.size === 2 ) {
  12173. for ( ca = 0; ca < cal; ca ++ ) {
  12174. value = customAttribute.value[ ca ];
  12175. customAttribute.array[ offset ] = value.x;
  12176. customAttribute.array[ offset + 1 ] = value.y;
  12177. offset += 2;
  12178. }
  12179. } else if ( customAttribute.size === 3 ) {
  12180. if ( customAttribute.type === "c" ) {
  12181. for ( ca = 0; ca < cal; ca ++ ) {
  12182. value = customAttribute.value[ ca ];
  12183. customAttribute.array[ offset ] = value.r;
  12184. customAttribute.array[ offset + 1 ] = value.g;
  12185. customAttribute.array[ offset + 2 ] = value.b;
  12186. offset += 3;
  12187. }
  12188. } else {
  12189. for ( ca = 0; ca < cal; ca ++ ) {
  12190. value = customAttribute.value[ ca ];
  12191. customAttribute.array[ offset ] = value.x;
  12192. customAttribute.array[ offset + 1 ] = value.y;
  12193. customAttribute.array[ offset + 2 ] = value.z;
  12194. offset += 3;
  12195. }
  12196. }
  12197. } else if ( customAttribute.size === 4 ) {
  12198. for ( ca = 0; ca < cal; ca ++ ) {
  12199. value = customAttribute.value[ ca ];
  12200. customAttribute.array[ offset ] = value.x;
  12201. customAttribute.array[ offset + 1 ] = value.y;
  12202. customAttribute.array[ offset + 2 ] = value.z;
  12203. customAttribute.array[ offset + 3 ] = value.w;
  12204. offset += 4;
  12205. }
  12206. }
  12207. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12208. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12209. }
  12210. }
  12211. }
  12212. };
  12213. function setRibbonBuffers ( geometry, hint ) {
  12214. var v, c, n, vertex, offset, color, normal,
  12215. i, il, ca, cal, customAttribute, value,
  12216. vertices = geometry.vertices,
  12217. colors = geometry.colors,
  12218. normals = geometry.normals,
  12219. vl = vertices.length,
  12220. cl = colors.length,
  12221. nl = normals.length,
  12222. vertexArray = geometry.__vertexArray,
  12223. colorArray = geometry.__colorArray,
  12224. normalArray = geometry.__normalArray,
  12225. dirtyVertices = geometry.verticesNeedUpdate,
  12226. dirtyColors = geometry.colorsNeedUpdate,
  12227. dirtyNormals = geometry.normalsNeedUpdate,
  12228. customAttributes = geometry.__webglCustomAttributesList;
  12229. if ( dirtyVertices ) {
  12230. for ( v = 0; v < vl; v ++ ) {
  12231. vertex = vertices[ v ];
  12232. offset = v * 3;
  12233. vertexArray[ offset ] = vertex.x;
  12234. vertexArray[ offset + 1 ] = vertex.y;
  12235. vertexArray[ offset + 2 ] = vertex.z;
  12236. }
  12237. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12238. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12239. }
  12240. if ( dirtyColors ) {
  12241. for ( c = 0; c < cl; c ++ ) {
  12242. color = colors[ c ];
  12243. offset = c * 3;
  12244. colorArray[ offset ] = color.r;
  12245. colorArray[ offset + 1 ] = color.g;
  12246. colorArray[ offset + 2 ] = color.b;
  12247. }
  12248. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12249. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12250. }
  12251. if ( dirtyNormals ) {
  12252. for ( n = 0; n < nl; n ++ ) {
  12253. normal = normals[ n ];
  12254. offset = n * 3;
  12255. normalArray[ offset ] = normal.x;
  12256. normalArray[ offset + 1 ] = normal.y;
  12257. normalArray[ offset + 2 ] = normal.z;
  12258. }
  12259. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  12260. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12261. }
  12262. if ( customAttributes ) {
  12263. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12264. customAttribute = customAttributes[ i ];
  12265. if ( customAttribute.needsUpdate &&
  12266. ( customAttribute.boundTo === undefined ||
  12267. customAttribute.boundTo === "vertices" ) ) {
  12268. offset = 0;
  12269. cal = customAttribute.value.length;
  12270. if ( customAttribute.size === 1 ) {
  12271. for ( ca = 0; ca < cal; ca ++ ) {
  12272. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12273. }
  12274. } else if ( customAttribute.size === 2 ) {
  12275. for ( ca = 0; ca < cal; ca ++ ) {
  12276. value = customAttribute.value[ ca ];
  12277. customAttribute.array[ offset ] = value.x;
  12278. customAttribute.array[ offset + 1 ] = value.y;
  12279. offset += 2;
  12280. }
  12281. } else if ( customAttribute.size === 3 ) {
  12282. if ( customAttribute.type === "c" ) {
  12283. for ( ca = 0; ca < cal; ca ++ ) {
  12284. value = customAttribute.value[ ca ];
  12285. customAttribute.array[ offset ] = value.r;
  12286. customAttribute.array[ offset + 1 ] = value.g;
  12287. customAttribute.array[ offset + 2 ] = value.b;
  12288. offset += 3;
  12289. }
  12290. } else {
  12291. for ( ca = 0; ca < cal; ca ++ ) {
  12292. value = customAttribute.value[ ca ];
  12293. customAttribute.array[ offset ] = value.x;
  12294. customAttribute.array[ offset + 1 ] = value.y;
  12295. customAttribute.array[ offset + 2 ] = value.z;
  12296. offset += 3;
  12297. }
  12298. }
  12299. } else if ( customAttribute.size === 4 ) {
  12300. for ( ca = 0; ca < cal; ca ++ ) {
  12301. value = customAttribute.value[ ca ];
  12302. customAttribute.array[ offset ] = value.x;
  12303. customAttribute.array[ offset + 1 ] = value.y;
  12304. customAttribute.array[ offset + 2 ] = value.z;
  12305. customAttribute.array[ offset + 3 ] = value.w;
  12306. offset += 4;
  12307. }
  12308. }
  12309. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12310. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12311. }
  12312. }
  12313. }
  12314. };
  12315. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12316. if ( ! geometryGroup.__inittedArrays ) {
  12317. return;
  12318. }
  12319. var normalType = bufferGuessNormalType( material ),
  12320. vertexColorType = bufferGuessVertexColorType( material ),
  12321. uvType = bufferGuessUVType( material ),
  12322. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12323. var f, fl, fi, face,
  12324. vertexNormals, faceNormal, normal,
  12325. vertexColors, faceColor,
  12326. vertexTangents,
  12327. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12328. c1, c2, c3, c4,
  12329. sw1, sw2, sw3, sw4,
  12330. si1, si2, si3, si4,
  12331. sa1, sa2, sa3, sa4,
  12332. sb1, sb2, sb3, sb4,
  12333. m, ml, i, il,
  12334. vn, uvi, uv2i,
  12335. vk, vkl, vka,
  12336. nka, chf, faceVertexNormals,
  12337. a,
  12338. vertexIndex = 0,
  12339. offset = 0,
  12340. offset_uv = 0,
  12341. offset_uv2 = 0,
  12342. offset_face = 0,
  12343. offset_normal = 0,
  12344. offset_tangent = 0,
  12345. offset_line = 0,
  12346. offset_color = 0,
  12347. offset_skin = 0,
  12348. offset_morphTarget = 0,
  12349. offset_custom = 0,
  12350. offset_customSrc = 0,
  12351. value,
  12352. vertexArray = geometryGroup.__vertexArray,
  12353. uvArray = geometryGroup.__uvArray,
  12354. uv2Array = geometryGroup.__uv2Array,
  12355. normalArray = geometryGroup.__normalArray,
  12356. tangentArray = geometryGroup.__tangentArray,
  12357. colorArray = geometryGroup.__colorArray,
  12358. skinIndexArray = geometryGroup.__skinIndexArray,
  12359. skinWeightArray = geometryGroup.__skinWeightArray,
  12360. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12361. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12362. customAttributes = geometryGroup.__webglCustomAttributesList,
  12363. customAttribute,
  12364. faceArray = geometryGroup.__faceArray,
  12365. lineArray = geometryGroup.__lineArray,
  12366. geometry = object.geometry, // this is shared for all chunks
  12367. dirtyVertices = geometry.verticesNeedUpdate,
  12368. dirtyElements = geometry.elementsNeedUpdate,
  12369. dirtyUvs = geometry.uvsNeedUpdate,
  12370. dirtyNormals = geometry.normalsNeedUpdate,
  12371. dirtyTangents = geometry.tangentsNeedUpdate,
  12372. dirtyColors = geometry.colorsNeedUpdate,
  12373. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12374. vertices = geometry.vertices,
  12375. chunk_faces3 = geometryGroup.faces3,
  12376. chunk_faces4 = geometryGroup.faces4,
  12377. obj_faces = geometry.faces,
  12378. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12379. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12380. obj_colors = geometry.colors,
  12381. obj_skinIndices = geometry.skinIndices,
  12382. obj_skinWeights = geometry.skinWeights,
  12383. morphTargets = geometry.morphTargets,
  12384. morphNormals = geometry.morphNormals;
  12385. if ( dirtyVertices ) {
  12386. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12387. face = obj_faces[ chunk_faces3[ f ] ];
  12388. v1 = vertices[ face.a ];
  12389. v2 = vertices[ face.b ];
  12390. v3 = vertices[ face.c ];
  12391. vertexArray[ offset ] = v1.x;
  12392. vertexArray[ offset + 1 ] = v1.y;
  12393. vertexArray[ offset + 2 ] = v1.z;
  12394. vertexArray[ offset + 3 ] = v2.x;
  12395. vertexArray[ offset + 4 ] = v2.y;
  12396. vertexArray[ offset + 5 ] = v2.z;
  12397. vertexArray[ offset + 6 ] = v3.x;
  12398. vertexArray[ offset + 7 ] = v3.y;
  12399. vertexArray[ offset + 8 ] = v3.z;
  12400. offset += 9;
  12401. }
  12402. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12403. face = obj_faces[ chunk_faces4[ f ] ];
  12404. v1 = vertices[ face.a ];
  12405. v2 = vertices[ face.b ];
  12406. v3 = vertices[ face.c ];
  12407. v4 = vertices[ face.d ];
  12408. vertexArray[ offset ] = v1.x;
  12409. vertexArray[ offset + 1 ] = v1.y;
  12410. vertexArray[ offset + 2 ] = v1.z;
  12411. vertexArray[ offset + 3 ] = v2.x;
  12412. vertexArray[ offset + 4 ] = v2.y;
  12413. vertexArray[ offset + 5 ] = v2.z;
  12414. vertexArray[ offset + 6 ] = v3.x;
  12415. vertexArray[ offset + 7 ] = v3.y;
  12416. vertexArray[ offset + 8 ] = v3.z;
  12417. vertexArray[ offset + 9 ] = v4.x;
  12418. vertexArray[ offset + 10 ] = v4.y;
  12419. vertexArray[ offset + 11 ] = v4.z;
  12420. offset += 12;
  12421. }
  12422. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12423. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12424. }
  12425. if ( dirtyMorphTargets ) {
  12426. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12427. offset_morphTarget = 0;
  12428. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12429. chf = chunk_faces3[ f ];
  12430. face = obj_faces[ chf ];
  12431. // morph positions
  12432. v1 = morphTargets[ vk ].vertices[ face.a ];
  12433. v2 = morphTargets[ vk ].vertices[ face.b ];
  12434. v3 = morphTargets[ vk ].vertices[ face.c ];
  12435. vka = morphTargetsArrays[ vk ];
  12436. vka[ offset_morphTarget ] = v1.x;
  12437. vka[ offset_morphTarget + 1 ] = v1.y;
  12438. vka[ offset_morphTarget + 2 ] = v1.z;
  12439. vka[ offset_morphTarget + 3 ] = v2.x;
  12440. vka[ offset_morphTarget + 4 ] = v2.y;
  12441. vka[ offset_morphTarget + 5 ] = v2.z;
  12442. vka[ offset_morphTarget + 6 ] = v3.x;
  12443. vka[ offset_morphTarget + 7 ] = v3.y;
  12444. vka[ offset_morphTarget + 8 ] = v3.z;
  12445. // morph normals
  12446. if ( material.morphNormals ) {
  12447. if ( needsSmoothNormals ) {
  12448. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12449. n1 = faceVertexNormals.a;
  12450. n2 = faceVertexNormals.b;
  12451. n3 = faceVertexNormals.c;
  12452. } else {
  12453. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12454. n2 = n1;
  12455. n3 = n1;
  12456. }
  12457. nka = morphNormalsArrays[ vk ];
  12458. nka[ offset_morphTarget ] = n1.x;
  12459. nka[ offset_morphTarget + 1 ] = n1.y;
  12460. nka[ offset_morphTarget + 2 ] = n1.z;
  12461. nka[ offset_morphTarget + 3 ] = n2.x;
  12462. nka[ offset_morphTarget + 4 ] = n2.y;
  12463. nka[ offset_morphTarget + 5 ] = n2.z;
  12464. nka[ offset_morphTarget + 6 ] = n3.x;
  12465. nka[ offset_morphTarget + 7 ] = n3.y;
  12466. nka[ offset_morphTarget + 8 ] = n3.z;
  12467. }
  12468. //
  12469. offset_morphTarget += 9;
  12470. }
  12471. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12472. chf = chunk_faces4[ f ];
  12473. face = obj_faces[ chf ];
  12474. // morph positions
  12475. v1 = morphTargets[ vk ].vertices[ face.a ];
  12476. v2 = morphTargets[ vk ].vertices[ face.b ];
  12477. v3 = morphTargets[ vk ].vertices[ face.c ];
  12478. v4 = morphTargets[ vk ].vertices[ face.d ];
  12479. vka = morphTargetsArrays[ vk ];
  12480. vka[ offset_morphTarget ] = v1.x;
  12481. vka[ offset_morphTarget + 1 ] = v1.y;
  12482. vka[ offset_morphTarget + 2 ] = v1.z;
  12483. vka[ offset_morphTarget + 3 ] = v2.x;
  12484. vka[ offset_morphTarget + 4 ] = v2.y;
  12485. vka[ offset_morphTarget + 5 ] = v2.z;
  12486. vka[ offset_morphTarget + 6 ] = v3.x;
  12487. vka[ offset_morphTarget + 7 ] = v3.y;
  12488. vka[ offset_morphTarget + 8 ] = v3.z;
  12489. vka[ offset_morphTarget + 9 ] = v4.x;
  12490. vka[ offset_morphTarget + 10 ] = v4.y;
  12491. vka[ offset_morphTarget + 11 ] = v4.z;
  12492. // morph normals
  12493. if ( material.morphNormals ) {
  12494. if ( needsSmoothNormals ) {
  12495. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12496. n1 = faceVertexNormals.a;
  12497. n2 = faceVertexNormals.b;
  12498. n3 = faceVertexNormals.c;
  12499. n4 = faceVertexNormals.d;
  12500. } else {
  12501. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12502. n2 = n1;
  12503. n3 = n1;
  12504. n4 = n1;
  12505. }
  12506. nka = morphNormalsArrays[ vk ];
  12507. nka[ offset_morphTarget ] = n1.x;
  12508. nka[ offset_morphTarget + 1 ] = n1.y;
  12509. nka[ offset_morphTarget + 2 ] = n1.z;
  12510. nka[ offset_morphTarget + 3 ] = n2.x;
  12511. nka[ offset_morphTarget + 4 ] = n2.y;
  12512. nka[ offset_morphTarget + 5 ] = n2.z;
  12513. nka[ offset_morphTarget + 6 ] = n3.x;
  12514. nka[ offset_morphTarget + 7 ] = n3.y;
  12515. nka[ offset_morphTarget + 8 ] = n3.z;
  12516. nka[ offset_morphTarget + 9 ] = n4.x;
  12517. nka[ offset_morphTarget + 10 ] = n4.y;
  12518. nka[ offset_morphTarget + 11 ] = n4.z;
  12519. }
  12520. //
  12521. offset_morphTarget += 12;
  12522. }
  12523. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12524. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12525. if ( material.morphNormals ) {
  12526. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12527. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12528. }
  12529. }
  12530. }
  12531. if ( obj_skinWeights.length ) {
  12532. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12533. face = obj_faces[ chunk_faces3[ f ] ];
  12534. // weights
  12535. sw1 = obj_skinWeights[ face.a ];
  12536. sw2 = obj_skinWeights[ face.b ];
  12537. sw3 = obj_skinWeights[ face.c ];
  12538. skinWeightArray[ offset_skin ] = sw1.x;
  12539. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12540. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12541. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12542. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12543. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12544. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12545. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12546. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12547. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12548. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12549. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12550. // indices
  12551. si1 = obj_skinIndices[ face.a ];
  12552. si2 = obj_skinIndices[ face.b ];
  12553. si3 = obj_skinIndices[ face.c ];
  12554. skinIndexArray[ offset_skin ] = si1.x;
  12555. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12556. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12557. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12558. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12559. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12560. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12561. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12562. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12563. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12564. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12565. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12566. offset_skin += 12;
  12567. }
  12568. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12569. face = obj_faces[ chunk_faces4[ f ] ];
  12570. // weights
  12571. sw1 = obj_skinWeights[ face.a ];
  12572. sw2 = obj_skinWeights[ face.b ];
  12573. sw3 = obj_skinWeights[ face.c ];
  12574. sw4 = obj_skinWeights[ face.d ];
  12575. skinWeightArray[ offset_skin ] = sw1.x;
  12576. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12577. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12578. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12579. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12580. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12581. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12582. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12583. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12584. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12585. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12586. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12587. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  12588. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  12589. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  12590. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  12591. // indices
  12592. si1 = obj_skinIndices[ face.a ];
  12593. si2 = obj_skinIndices[ face.b ];
  12594. si3 = obj_skinIndices[ face.c ];
  12595. si4 = obj_skinIndices[ face.d ];
  12596. skinIndexArray[ offset_skin ] = si1.x;
  12597. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12598. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12599. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12600. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12601. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12602. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12603. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12604. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12605. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12606. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12607. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12608. skinIndexArray[ offset_skin + 12 ] = si4.x;
  12609. skinIndexArray[ offset_skin + 13 ] = si4.y;
  12610. skinIndexArray[ offset_skin + 14 ] = si4.z;
  12611. skinIndexArray[ offset_skin + 15 ] = si4.w;
  12612. offset_skin += 16;
  12613. }
  12614. if ( offset_skin > 0 ) {
  12615. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12616. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12617. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12618. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12619. }
  12620. }
  12621. if ( dirtyColors && vertexColorType ) {
  12622. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12623. face = obj_faces[ chunk_faces3[ f ] ];
  12624. vertexColors = face.vertexColors;
  12625. faceColor = face.color;
  12626. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12627. c1 = vertexColors[ 0 ];
  12628. c2 = vertexColors[ 1 ];
  12629. c3 = vertexColors[ 2 ];
  12630. } else {
  12631. c1 = faceColor;
  12632. c2 = faceColor;
  12633. c3 = faceColor;
  12634. }
  12635. colorArray[ offset_color ] = c1.r;
  12636. colorArray[ offset_color + 1 ] = c1.g;
  12637. colorArray[ offset_color + 2 ] = c1.b;
  12638. colorArray[ offset_color + 3 ] = c2.r;
  12639. colorArray[ offset_color + 4 ] = c2.g;
  12640. colorArray[ offset_color + 5 ] = c2.b;
  12641. colorArray[ offset_color + 6 ] = c3.r;
  12642. colorArray[ offset_color + 7 ] = c3.g;
  12643. colorArray[ offset_color + 8 ] = c3.b;
  12644. offset_color += 9;
  12645. }
  12646. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12647. face = obj_faces[ chunk_faces4[ f ] ];
  12648. vertexColors = face.vertexColors;
  12649. faceColor = face.color;
  12650. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12651. c1 = vertexColors[ 0 ];
  12652. c2 = vertexColors[ 1 ];
  12653. c3 = vertexColors[ 2 ];
  12654. c4 = vertexColors[ 3 ];
  12655. } else {
  12656. c1 = faceColor;
  12657. c2 = faceColor;
  12658. c3 = faceColor;
  12659. c4 = faceColor;
  12660. }
  12661. colorArray[ offset_color ] = c1.r;
  12662. colorArray[ offset_color + 1 ] = c1.g;
  12663. colorArray[ offset_color + 2 ] = c1.b;
  12664. colorArray[ offset_color + 3 ] = c2.r;
  12665. colorArray[ offset_color + 4 ] = c2.g;
  12666. colorArray[ offset_color + 5 ] = c2.b;
  12667. colorArray[ offset_color + 6 ] = c3.r;
  12668. colorArray[ offset_color + 7 ] = c3.g;
  12669. colorArray[ offset_color + 8 ] = c3.b;
  12670. colorArray[ offset_color + 9 ] = c4.r;
  12671. colorArray[ offset_color + 10 ] = c4.g;
  12672. colorArray[ offset_color + 11 ] = c4.b;
  12673. offset_color += 12;
  12674. }
  12675. if ( offset_color > 0 ) {
  12676. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12677. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12678. }
  12679. }
  12680. if ( dirtyTangents && geometry.hasTangents ) {
  12681. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12682. face = obj_faces[ chunk_faces3[ f ] ];
  12683. vertexTangents = face.vertexTangents;
  12684. t1 = vertexTangents[ 0 ];
  12685. t2 = vertexTangents[ 1 ];
  12686. t3 = vertexTangents[ 2 ];
  12687. tangentArray[ offset_tangent ] = t1.x;
  12688. tangentArray[ offset_tangent + 1 ] = t1.y;
  12689. tangentArray[ offset_tangent + 2 ] = t1.z;
  12690. tangentArray[ offset_tangent + 3 ] = t1.w;
  12691. tangentArray[ offset_tangent + 4 ] = t2.x;
  12692. tangentArray[ offset_tangent + 5 ] = t2.y;
  12693. tangentArray[ offset_tangent + 6 ] = t2.z;
  12694. tangentArray[ offset_tangent + 7 ] = t2.w;
  12695. tangentArray[ offset_tangent + 8 ] = t3.x;
  12696. tangentArray[ offset_tangent + 9 ] = t3.y;
  12697. tangentArray[ offset_tangent + 10 ] = t3.z;
  12698. tangentArray[ offset_tangent + 11 ] = t3.w;
  12699. offset_tangent += 12;
  12700. }
  12701. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12702. face = obj_faces[ chunk_faces4[ f ] ];
  12703. vertexTangents = face.vertexTangents;
  12704. t1 = vertexTangents[ 0 ];
  12705. t2 = vertexTangents[ 1 ];
  12706. t3 = vertexTangents[ 2 ];
  12707. t4 = vertexTangents[ 3 ];
  12708. tangentArray[ offset_tangent ] = t1.x;
  12709. tangentArray[ offset_tangent + 1 ] = t1.y;
  12710. tangentArray[ offset_tangent + 2 ] = t1.z;
  12711. tangentArray[ offset_tangent + 3 ] = t1.w;
  12712. tangentArray[ offset_tangent + 4 ] = t2.x;
  12713. tangentArray[ offset_tangent + 5 ] = t2.y;
  12714. tangentArray[ offset_tangent + 6 ] = t2.z;
  12715. tangentArray[ offset_tangent + 7 ] = t2.w;
  12716. tangentArray[ offset_tangent + 8 ] = t3.x;
  12717. tangentArray[ offset_tangent + 9 ] = t3.y;
  12718. tangentArray[ offset_tangent + 10 ] = t3.z;
  12719. tangentArray[ offset_tangent + 11 ] = t3.w;
  12720. tangentArray[ offset_tangent + 12 ] = t4.x;
  12721. tangentArray[ offset_tangent + 13 ] = t4.y;
  12722. tangentArray[ offset_tangent + 14 ] = t4.z;
  12723. tangentArray[ offset_tangent + 15 ] = t4.w;
  12724. offset_tangent += 16;
  12725. }
  12726. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12727. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12728. }
  12729. if ( dirtyNormals && normalType ) {
  12730. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12731. face = obj_faces[ chunk_faces3[ f ] ];
  12732. vertexNormals = face.vertexNormals;
  12733. faceNormal = face.normal;
  12734. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12735. for ( i = 0; i < 3; i ++ ) {
  12736. vn = vertexNormals[ i ];
  12737. normalArray[ offset_normal ] = vn.x;
  12738. normalArray[ offset_normal + 1 ] = vn.y;
  12739. normalArray[ offset_normal + 2 ] = vn.z;
  12740. offset_normal += 3;
  12741. }
  12742. } else {
  12743. for ( i = 0; i < 3; i ++ ) {
  12744. normalArray[ offset_normal ] = faceNormal.x;
  12745. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12746. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12747. offset_normal += 3;
  12748. }
  12749. }
  12750. }
  12751. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12752. face = obj_faces[ chunk_faces4[ f ] ];
  12753. vertexNormals = face.vertexNormals;
  12754. faceNormal = face.normal;
  12755. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12756. for ( i = 0; i < 4; i ++ ) {
  12757. vn = vertexNormals[ i ];
  12758. normalArray[ offset_normal ] = vn.x;
  12759. normalArray[ offset_normal + 1 ] = vn.y;
  12760. normalArray[ offset_normal + 2 ] = vn.z;
  12761. offset_normal += 3;
  12762. }
  12763. } else {
  12764. for ( i = 0; i < 4; i ++ ) {
  12765. normalArray[ offset_normal ] = faceNormal.x;
  12766. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12767. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12768. offset_normal += 3;
  12769. }
  12770. }
  12771. }
  12772. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12773. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12774. }
  12775. if ( dirtyUvs && obj_uvs && uvType ) {
  12776. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12777. fi = chunk_faces3[ f ];
  12778. uv = obj_uvs[ fi ];
  12779. if ( uv === undefined ) continue;
  12780. for ( i = 0; i < 3; i ++ ) {
  12781. uvi = uv[ i ];
  12782. uvArray[ offset_uv ] = uvi.x;
  12783. uvArray[ offset_uv + 1 ] = uvi.y;
  12784. offset_uv += 2;
  12785. }
  12786. }
  12787. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12788. fi = chunk_faces4[ f ];
  12789. uv = obj_uvs[ fi ];
  12790. if ( uv === undefined ) continue;
  12791. for ( i = 0; i < 4; i ++ ) {
  12792. uvi = uv[ i ];
  12793. uvArray[ offset_uv ] = uvi.x;
  12794. uvArray[ offset_uv + 1 ] = uvi.y;
  12795. offset_uv += 2;
  12796. }
  12797. }
  12798. if ( offset_uv > 0 ) {
  12799. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12800. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12801. }
  12802. }
  12803. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12804. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12805. fi = chunk_faces3[ f ];
  12806. uv2 = obj_uvs2[ fi ];
  12807. if ( uv2 === undefined ) continue;
  12808. for ( i = 0; i < 3; i ++ ) {
  12809. uv2i = uv2[ i ];
  12810. uv2Array[ offset_uv2 ] = uv2i.x;
  12811. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12812. offset_uv2 += 2;
  12813. }
  12814. }
  12815. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12816. fi = chunk_faces4[ f ];
  12817. uv2 = obj_uvs2[ fi ];
  12818. if ( uv2 === undefined ) continue;
  12819. for ( i = 0; i < 4; i ++ ) {
  12820. uv2i = uv2[ i ];
  12821. uv2Array[ offset_uv2 ] = uv2i.x;
  12822. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12823. offset_uv2 += 2;
  12824. }
  12825. }
  12826. if ( offset_uv2 > 0 ) {
  12827. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12828. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12829. }
  12830. }
  12831. if ( dirtyElements ) {
  12832. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12833. faceArray[ offset_face ] = vertexIndex;
  12834. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12835. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12836. offset_face += 3;
  12837. lineArray[ offset_line ] = vertexIndex;
  12838. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12839. lineArray[ offset_line + 2 ] = vertexIndex;
  12840. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12841. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12842. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12843. offset_line += 6;
  12844. vertexIndex += 3;
  12845. }
  12846. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12847. faceArray[ offset_face ] = vertexIndex;
  12848. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12849. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12850. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12851. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12852. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12853. offset_face += 6;
  12854. lineArray[ offset_line ] = vertexIndex;
  12855. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12856. lineArray[ offset_line + 2 ] = vertexIndex;
  12857. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12858. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12859. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12860. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12861. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12862. offset_line += 8;
  12863. vertexIndex += 4;
  12864. }
  12865. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12866. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12867. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12868. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12869. }
  12870. if ( customAttributes ) {
  12871. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12872. customAttribute = customAttributes[ i ];
  12873. if ( ! customAttribute.__original.needsUpdate ) continue;
  12874. offset_custom = 0;
  12875. offset_customSrc = 0;
  12876. if ( customAttribute.size === 1 ) {
  12877. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12878. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12879. face = obj_faces[ chunk_faces3[ f ] ];
  12880. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12881. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12882. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12883. offset_custom += 3;
  12884. }
  12885. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12886. face = obj_faces[ chunk_faces4[ f ] ];
  12887. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12888. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12889. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12890. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  12891. offset_custom += 4;
  12892. }
  12893. } else if ( customAttribute.boundTo === "faces" ) {
  12894. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12895. value = customAttribute.value[ chunk_faces3[ f ] ];
  12896. customAttribute.array[ offset_custom ] = value;
  12897. customAttribute.array[ offset_custom + 1 ] = value;
  12898. customAttribute.array[ offset_custom + 2 ] = value;
  12899. offset_custom += 3;
  12900. }
  12901. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12902. value = customAttribute.value[ chunk_faces4[ f ] ];
  12903. customAttribute.array[ offset_custom ] = value;
  12904. customAttribute.array[ offset_custom + 1 ] = value;
  12905. customAttribute.array[ offset_custom + 2 ] = value;
  12906. customAttribute.array[ offset_custom + 3 ] = value;
  12907. offset_custom += 4;
  12908. }
  12909. }
  12910. } else if ( customAttribute.size === 2 ) {
  12911. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12912. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12913. face = obj_faces[ chunk_faces3[ f ] ];
  12914. v1 = customAttribute.value[ face.a ];
  12915. v2 = customAttribute.value[ face.b ];
  12916. v3 = customAttribute.value[ face.c ];
  12917. customAttribute.array[ offset_custom ] = v1.x;
  12918. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12919. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12920. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12921. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12922. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12923. offset_custom += 6;
  12924. }
  12925. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12926. face = obj_faces[ chunk_faces4[ f ] ];
  12927. v1 = customAttribute.value[ face.a ];
  12928. v2 = customAttribute.value[ face.b ];
  12929. v3 = customAttribute.value[ face.c ];
  12930. v4 = customAttribute.value[ face.d ];
  12931. customAttribute.array[ offset_custom ] = v1.x;
  12932. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12933. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12934. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12935. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12936. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12937. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12938. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12939. offset_custom += 8;
  12940. }
  12941. } else if ( customAttribute.boundTo === "faces" ) {
  12942. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12943. value = customAttribute.value[ chunk_faces3[ f ] ];
  12944. v1 = value;
  12945. v2 = value;
  12946. v3 = value;
  12947. customAttribute.array[ offset_custom ] = v1.x;
  12948. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12949. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12950. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12951. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12952. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12953. offset_custom += 6;
  12954. }
  12955. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12956. value = customAttribute.value[ chunk_faces4[ f ] ];
  12957. v1 = value;
  12958. v2 = value;
  12959. v3 = value;
  12960. v4 = value;
  12961. customAttribute.array[ offset_custom ] = v1.x;
  12962. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12963. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12964. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12965. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12966. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12967. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12968. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12969. offset_custom += 8;
  12970. }
  12971. }
  12972. } else if ( customAttribute.size === 3 ) {
  12973. var pp;
  12974. if ( customAttribute.type === "c" ) {
  12975. pp = [ "r", "g", "b" ];
  12976. } else {
  12977. pp = [ "x", "y", "z" ];
  12978. }
  12979. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12980. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12981. face = obj_faces[ chunk_faces3[ f ] ];
  12982. v1 = customAttribute.value[ face.a ];
  12983. v2 = customAttribute.value[ face.b ];
  12984. v3 = customAttribute.value[ face.c ];
  12985. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12986. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12987. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12988. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12989. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12990. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12991. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12992. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12993. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12994. offset_custom += 9;
  12995. }
  12996. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12997. face = obj_faces[ chunk_faces4[ f ] ];
  12998. v1 = customAttribute.value[ face.a ];
  12999. v2 = customAttribute.value[ face.b ];
  13000. v3 = customAttribute.value[ face.c ];
  13001. v4 = customAttribute.value[ face.d ];
  13002. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13003. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13004. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13005. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13006. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13007. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13008. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13009. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13010. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13011. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13012. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13013. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13014. offset_custom += 12;
  13015. }
  13016. } else if ( customAttribute.boundTo === "faces" ) {
  13017. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13018. value = customAttribute.value[ chunk_faces3[ f ] ];
  13019. v1 = value;
  13020. v2 = value;
  13021. v3 = value;
  13022. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13023. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13024. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13025. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13026. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13027. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13028. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13029. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13030. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13031. offset_custom += 9;
  13032. }
  13033. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13034. value = customAttribute.value[ chunk_faces4[ f ] ];
  13035. v1 = value;
  13036. v2 = value;
  13037. v3 = value;
  13038. v4 = value;
  13039. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13040. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13041. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13042. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13043. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13044. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13045. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13046. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13047. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13048. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13049. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13050. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13051. offset_custom += 12;
  13052. }
  13053. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13054. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13055. value = customAttribute.value[ chunk_faces3[ f ] ];
  13056. v1 = value[ 0 ];
  13057. v2 = value[ 1 ];
  13058. v3 = value[ 2 ];
  13059. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13060. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13061. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13062. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13063. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13064. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13065. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13066. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13067. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13068. offset_custom += 9;
  13069. }
  13070. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13071. value = customAttribute.value[ chunk_faces4[ f ] ];
  13072. v1 = value[ 0 ];
  13073. v2 = value[ 1 ];
  13074. v3 = value[ 2 ];
  13075. v4 = value[ 3 ];
  13076. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13077. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13078. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13079. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13080. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13081. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13082. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13083. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13084. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13085. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13086. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13087. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13088. offset_custom += 12;
  13089. }
  13090. }
  13091. } else if ( customAttribute.size === 4 ) {
  13092. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13093. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13094. face = obj_faces[ chunk_faces3[ f ] ];
  13095. v1 = customAttribute.value[ face.a ];
  13096. v2 = customAttribute.value[ face.b ];
  13097. v3 = customAttribute.value[ face.c ];
  13098. customAttribute.array[ offset_custom ] = v1.x;
  13099. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13100. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13101. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13102. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13103. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13104. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13105. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13106. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13107. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13108. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13109. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13110. offset_custom += 12;
  13111. }
  13112. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13113. face = obj_faces[ chunk_faces4[ f ] ];
  13114. v1 = customAttribute.value[ face.a ];
  13115. v2 = customAttribute.value[ face.b ];
  13116. v3 = customAttribute.value[ face.c ];
  13117. v4 = customAttribute.value[ face.d ];
  13118. customAttribute.array[ offset_custom ] = v1.x;
  13119. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13120. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13121. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13122. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13123. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13124. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13125. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13126. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13127. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13128. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13129. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13130. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13131. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13132. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13133. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13134. offset_custom += 16;
  13135. }
  13136. } else if ( customAttribute.boundTo === "faces" ) {
  13137. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13138. value = customAttribute.value[ chunk_faces3[ f ] ];
  13139. v1 = value;
  13140. v2 = value;
  13141. v3 = value;
  13142. customAttribute.array[ offset_custom ] = v1.x;
  13143. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13144. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13145. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13146. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13147. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13148. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13149. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13150. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13151. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13152. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13153. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13154. offset_custom += 12;
  13155. }
  13156. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13157. value = customAttribute.value[ chunk_faces4[ f ] ];
  13158. v1 = value;
  13159. v2 = value;
  13160. v3 = value;
  13161. v4 = value;
  13162. customAttribute.array[ offset_custom ] = v1.x;
  13163. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13164. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13165. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13166. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13167. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13168. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13169. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13170. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13171. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13172. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13173. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13174. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13175. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13176. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13177. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13178. offset_custom += 16;
  13179. }
  13180. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13181. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13182. value = customAttribute.value[ chunk_faces3[ f ] ];
  13183. v1 = value[ 0 ];
  13184. v2 = value[ 1 ];
  13185. v3 = value[ 2 ];
  13186. customAttribute.array[ offset_custom ] = v1.x;
  13187. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13188. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13189. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13190. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13191. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13192. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13193. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13194. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13195. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13196. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13197. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13198. offset_custom += 12;
  13199. }
  13200. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13201. value = customAttribute.value[ chunk_faces4[ f ] ];
  13202. v1 = value[ 0 ];
  13203. v2 = value[ 1 ];
  13204. v3 = value[ 2 ];
  13205. v4 = value[ 3 ];
  13206. customAttribute.array[ offset_custom ] = v1.x;
  13207. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13208. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13209. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13210. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13211. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13212. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13213. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13214. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13215. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13216. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13217. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13218. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13219. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13220. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13221. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13222. offset_custom += 16;
  13223. }
  13224. }
  13225. }
  13226. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13227. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13228. }
  13229. }
  13230. if ( dispose ) {
  13231. delete geometryGroup.__inittedArrays;
  13232. delete geometryGroup.__colorArray;
  13233. delete geometryGroup.__normalArray;
  13234. delete geometryGroup.__tangentArray;
  13235. delete geometryGroup.__uvArray;
  13236. delete geometryGroup.__uv2Array;
  13237. delete geometryGroup.__faceArray;
  13238. delete geometryGroup.__vertexArray;
  13239. delete geometryGroup.__lineArray;
  13240. delete geometryGroup.__skinIndexArray;
  13241. delete geometryGroup.__skinWeightArray;
  13242. }
  13243. };
  13244. function setDirectBuffers ( geometry, hint, dispose ) {
  13245. var attributes = geometry.attributes;
  13246. var attributeName, attributeItem;
  13247. for ( attributeName in attributes ) {
  13248. attributeItem = attributes[ attributeName ];
  13249. if ( attributeItem.needsUpdate ) {
  13250. if ( attributeName === 'index' ) {
  13251. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13252. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13253. } else {
  13254. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13255. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13256. }
  13257. attributeItem.needsUpdate = false;
  13258. }
  13259. if ( dispose && ! attributeItem.dynamic ) {
  13260. attributeItem.array = null;
  13261. }
  13262. }
  13263. };
  13264. // Buffer rendering
  13265. this.renderBufferImmediate = function ( object, program, material ) {
  13266. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13267. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13268. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13269. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13270. if ( object.hasPositions ) {
  13271. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13272. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13273. _gl.enableVertexAttribArray( program.attributes.position );
  13274. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13275. }
  13276. if ( object.hasNormals ) {
  13277. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13278. if ( material.shading === THREE.FlatShading ) {
  13279. var nx, ny, nz,
  13280. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13281. normalArray,
  13282. i, il = object.count * 3;
  13283. for( i = 0; i < il; i += 9 ) {
  13284. normalArray = object.normalArray;
  13285. nax = normalArray[ i ];
  13286. nay = normalArray[ i + 1 ];
  13287. naz = normalArray[ i + 2 ];
  13288. nbx = normalArray[ i + 3 ];
  13289. nby = normalArray[ i + 4 ];
  13290. nbz = normalArray[ i + 5 ];
  13291. ncx = normalArray[ i + 6 ];
  13292. ncy = normalArray[ i + 7 ];
  13293. ncz = normalArray[ i + 8 ];
  13294. nx = ( nax + nbx + ncx ) / 3;
  13295. ny = ( nay + nby + ncy ) / 3;
  13296. nz = ( naz + nbz + ncz ) / 3;
  13297. normalArray[ i ] = nx;
  13298. normalArray[ i + 1 ] = ny;
  13299. normalArray[ i + 2 ] = nz;
  13300. normalArray[ i + 3 ] = nx;
  13301. normalArray[ i + 4 ] = ny;
  13302. normalArray[ i + 5 ] = nz;
  13303. normalArray[ i + 6 ] = nx;
  13304. normalArray[ i + 7 ] = ny;
  13305. normalArray[ i + 8 ] = nz;
  13306. }
  13307. }
  13308. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13309. _gl.enableVertexAttribArray( program.attributes.normal );
  13310. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13311. }
  13312. if ( object.hasUvs && material.map ) {
  13313. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13314. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13315. _gl.enableVertexAttribArray( program.attributes.uv );
  13316. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13317. }
  13318. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13319. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13320. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13321. _gl.enableVertexAttribArray( program.attributes.color );
  13322. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13323. }
  13324. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13325. object.count = 0;
  13326. };
  13327. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13328. if ( material.visible === false ) return;
  13329. var linewidth, a, attribute;
  13330. var attributeItem, attributeName, attributePointer, attributeSize;
  13331. var program = setProgram( camera, lights, fog, material, object );
  13332. var programAttributes = program.attributes;
  13333. var geometryAttributes = geometry.attributes;
  13334. var updateBuffers = false,
  13335. wireframeBit = material.wireframe ? 1 : 0,
  13336. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13337. if ( geometryHash !== _currentGeometryGroupHash ) {
  13338. _currentGeometryGroupHash = geometryHash;
  13339. updateBuffers = true;
  13340. }
  13341. if ( updateBuffers ) {
  13342. disableAttributes();
  13343. }
  13344. // render mesh
  13345. if ( object instanceof THREE.Mesh ) {
  13346. var index = geometryAttributes[ "index" ];
  13347. // indexed triangles
  13348. if ( index ) {
  13349. var offsets = geometry.offsets;
  13350. // if there is more than 1 chunk
  13351. // must set attribute pointers to use new offsets for each chunk
  13352. // even if geometry and materials didn't change
  13353. if ( offsets.length > 1 ) updateBuffers = true;
  13354. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13355. var startIndex = offsets[ i ].index;
  13356. if ( updateBuffers ) {
  13357. for ( attributeName in geometryAttributes ) {
  13358. if ( attributeName === 'index' ) continue;
  13359. attributePointer = programAttributes[ attributeName ];
  13360. attributeItem = geometryAttributes[ attributeName ];
  13361. attributeSize = attributeItem.itemSize;
  13362. if ( attributePointer >= 0 ) {
  13363. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13364. enableAttribute( attributePointer );
  13365. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13366. }
  13367. }
  13368. // indices
  13369. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13370. }
  13371. // render indexed triangles
  13372. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13373. _this.info.render.calls ++;
  13374. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13375. _this.info.render.faces += offsets[ i ].count / 3;
  13376. }
  13377. // non-indexed triangles
  13378. } else {
  13379. if ( updateBuffers ) {
  13380. for ( attributeName in geometryAttributes ) {
  13381. if ( attributeName === 'index') continue;
  13382. attributePointer = programAttributes[ attributeName ];
  13383. attributeItem = geometryAttributes[ attributeName ];
  13384. attributeSize = attributeItem.itemSize;
  13385. if ( attributePointer >= 0 ) {
  13386. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13387. enableAttribute( attributePointer );
  13388. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13389. }
  13390. }
  13391. }
  13392. var position = geometry.attributes[ "position" ];
  13393. // render non-indexed triangles
  13394. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13395. _this.info.render.calls ++;
  13396. _this.info.render.vertices += position.numItems / 3;
  13397. _this.info.render.faces += position.numItems / 3 / 3;
  13398. }
  13399. // render particles
  13400. } else if ( object instanceof THREE.ParticleSystem ) {
  13401. if ( updateBuffers ) {
  13402. for ( attributeName in geometryAttributes ) {
  13403. attributePointer = programAttributes[ attributeName ];
  13404. attributeItem = geometryAttributes[ attributeName ];
  13405. attributeSize = attributeItem.itemSize;
  13406. if ( attributePointer >= 0 ) {
  13407. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13408. enableAttribute( attributePointer );
  13409. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13410. }
  13411. }
  13412. var position = geometryAttributes[ "position" ];
  13413. // render particles
  13414. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13415. _this.info.render.calls ++;
  13416. _this.info.render.points += position.numItems / 3;
  13417. }
  13418. } else if ( object instanceof THREE.Line ) {
  13419. if ( updateBuffers ) {
  13420. for ( attributeName in geometryAttributes ) {
  13421. attributePointer = programAttributes[ attributeName ];
  13422. attributeItem = geometryAttributes[ attributeName ];
  13423. attributeSize = attributeItem.itemSize;
  13424. if ( attributePointer >= 0 ) {
  13425. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13426. enableAttribute( attributePointer );
  13427. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13428. }
  13429. }
  13430. // render lines
  13431. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13432. setLineWidth( material.linewidth );
  13433. var position = geometryAttributes[ "position" ];
  13434. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13435. _this.info.render.calls ++;
  13436. _this.info.render.points += position.numItems;
  13437. }
  13438. }
  13439. };
  13440. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13441. if ( material.visible === false ) return;
  13442. var linewidth, a, attribute, i, il;
  13443. var program = setProgram( camera, lights, fog, material, object );
  13444. var attributes = program.attributes;
  13445. var updateBuffers = false,
  13446. wireframeBit = material.wireframe ? 1 : 0,
  13447. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13448. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13449. _currentGeometryGroupHash = geometryGroupHash;
  13450. updateBuffers = true;
  13451. }
  13452. if ( updateBuffers ) {
  13453. disableAttributes();
  13454. }
  13455. // vertices
  13456. if ( !material.morphTargets && attributes.position >= 0 ) {
  13457. if ( updateBuffers ) {
  13458. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13459. enableAttribute( attributes.position );
  13460. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13461. }
  13462. } else {
  13463. if ( object.morphTargetBase ) {
  13464. setupMorphTargets( material, geometryGroup, object );
  13465. }
  13466. }
  13467. if ( updateBuffers ) {
  13468. // custom attributes
  13469. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13470. if ( geometryGroup.__webglCustomAttributesList ) {
  13471. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13472. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13473. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13474. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13475. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13476. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13477. }
  13478. }
  13479. }
  13480. // colors
  13481. if ( attributes.color >= 0 ) {
  13482. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13483. enableAttribute( attributes.color );
  13484. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13485. }
  13486. // normals
  13487. if ( attributes.normal >= 0 ) {
  13488. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13489. enableAttribute( attributes.normal );
  13490. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13491. }
  13492. // tangents
  13493. if ( attributes.tangent >= 0 ) {
  13494. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13495. enableAttribute( attributes.tangent );
  13496. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13497. }
  13498. // uvs
  13499. if ( attributes.uv >= 0 ) {
  13500. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13501. enableAttribute( attributes.uv );
  13502. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13503. }
  13504. if ( attributes.uv2 >= 0 ) {
  13505. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13506. enableAttribute( attributes.uv2 );
  13507. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13508. }
  13509. if ( material.skinning &&
  13510. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13511. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13512. enableAttribute( attributes.skinIndex );
  13513. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13514. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13515. enableAttribute( attributes.skinWeight );
  13516. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13517. }
  13518. // line distances
  13519. if ( attributes.lineDistance >= 0 ) {
  13520. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13521. enableAttribute( attributes.lineDistance );
  13522. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13523. }
  13524. }
  13525. // render mesh
  13526. if ( object instanceof THREE.Mesh ) {
  13527. // wireframe
  13528. if ( material.wireframe ) {
  13529. setLineWidth( material.wireframeLinewidth );
  13530. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13531. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13532. // triangles
  13533. } else {
  13534. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13535. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13536. }
  13537. _this.info.render.calls ++;
  13538. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13539. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13540. // render lines
  13541. } else if ( object instanceof THREE.Line ) {
  13542. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13543. setLineWidth( material.linewidth );
  13544. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13545. _this.info.render.calls ++;
  13546. // render particles
  13547. } else if ( object instanceof THREE.ParticleSystem ) {
  13548. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13549. _this.info.render.calls ++;
  13550. _this.info.render.points += geometryGroup.__webglParticleCount;
  13551. // render ribbon
  13552. } else if ( object instanceof THREE.Ribbon ) {
  13553. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13554. _this.info.render.calls ++;
  13555. }
  13556. };
  13557. function enableAttribute( attribute ) {
  13558. if ( ! _enabledAttributes[ attribute ] ) {
  13559. _gl.enableVertexAttribArray( attribute );
  13560. _enabledAttributes[ attribute ] = true;
  13561. }
  13562. };
  13563. function disableAttributes() {
  13564. for ( var attribute in _enabledAttributes ) {
  13565. if ( _enabledAttributes[ attribute ] ) {
  13566. _gl.disableVertexAttribArray( attribute );
  13567. _enabledAttributes[ attribute ] = false;
  13568. }
  13569. }
  13570. };
  13571. function setupMorphTargets ( material, geometryGroup, object ) {
  13572. // set base
  13573. var attributes = material.program.attributes;
  13574. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13575. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13576. enableAttribute( attributes.position );
  13577. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13578. } else if ( attributes.position >= 0 ) {
  13579. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13580. enableAttribute( attributes.position );
  13581. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13582. }
  13583. if ( object.morphTargetForcedOrder.length ) {
  13584. // set forced order
  13585. var m = 0;
  13586. var order = object.morphTargetForcedOrder;
  13587. var influences = object.morphTargetInfluences;
  13588. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13589. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13590. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13591. enableAttribute( attributes[ "morphTarget" + m ] );
  13592. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13593. }
  13594. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13595. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13596. enableAttribute( attributes[ "morphNormal" + m ] );
  13597. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13598. }
  13599. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13600. m ++;
  13601. }
  13602. } else {
  13603. // find the most influencing
  13604. var influence, activeInfluenceIndices = [];
  13605. var influences = object.morphTargetInfluences;
  13606. var i, il = influences.length;
  13607. for ( i = 0; i < il; i ++ ) {
  13608. influence = influences[ i ];
  13609. if ( influence > 0 ) {
  13610. activeInfluenceIndices.push( [ influence, i ] );
  13611. }
  13612. }
  13613. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13614. activeInfluenceIndices.sort( numericalSort );
  13615. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13616. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13617. activeInfluenceIndices.sort( numericalSort );
  13618. } else if ( activeInfluenceIndices.length === 0 ) {
  13619. activeInfluenceIndices.push( [ 0, 0 ] );
  13620. };
  13621. var influenceIndex, m = 0;
  13622. while ( m < material.numSupportedMorphTargets ) {
  13623. if ( activeInfluenceIndices[ m ] ) {
  13624. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13625. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13626. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13627. enableAttribute( attributes[ "morphTarget" + m ] );
  13628. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13629. }
  13630. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13631. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13632. enableAttribute( attributes[ "morphNormal" + m ] );
  13633. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13634. }
  13635. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13636. } else {
  13637. /*
  13638. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13639. if ( material.morphNormals ) {
  13640. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13641. }
  13642. */
  13643. object.__webglMorphTargetInfluences[ m ] = 0;
  13644. }
  13645. m ++;
  13646. }
  13647. }
  13648. // load updated influences uniform
  13649. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13650. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13651. }
  13652. };
  13653. // Sorting
  13654. function painterSortStable ( a, b ) {
  13655. if ( a.z !== b.z ) {
  13656. return b.z - a.z;
  13657. } else {
  13658. return a.id - b.id;
  13659. }
  13660. };
  13661. function numericalSort ( a, b ) {
  13662. return b[ 0 ] - a[ 0 ];
  13663. };
  13664. // Rendering
  13665. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13666. if ( camera instanceof THREE.Camera === false ) {
  13667. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13668. return;
  13669. }
  13670. var i, il,
  13671. webglObject, object,
  13672. renderList,
  13673. lights = scene.__lights,
  13674. fog = scene.fog;
  13675. // reset caching for this frame
  13676. _currentMaterialId = -1;
  13677. _lightsNeedUpdate = true;
  13678. // update scene graph
  13679. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13680. // update camera matrices and frustum
  13681. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13682. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13683. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13684. _frustum.setFromMatrix( _projScreenMatrix );
  13685. // update WebGL objects
  13686. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13687. // custom render plugins (pre pass)
  13688. renderPlugins( this.renderPluginsPre, scene, camera );
  13689. //
  13690. _this.info.render.calls = 0;
  13691. _this.info.render.vertices = 0;
  13692. _this.info.render.faces = 0;
  13693. _this.info.render.points = 0;
  13694. this.setRenderTarget( renderTarget );
  13695. if ( this.autoClear || forceClear ) {
  13696. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13697. }
  13698. // set matrices for regular objects (frustum culled)
  13699. renderList = scene.__webglObjects;
  13700. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13701. webglObject = renderList[ i ];
  13702. object = webglObject.object;
  13703. webglObject.id = i;
  13704. webglObject.render = false;
  13705. if ( object.visible ) {
  13706. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13707. setupMatrices( object, camera );
  13708. unrollBufferMaterial( webglObject );
  13709. webglObject.render = true;
  13710. if ( this.sortObjects === true ) {
  13711. if ( object.renderDepth !== null ) {
  13712. webglObject.z = object.renderDepth;
  13713. } else {
  13714. _vector3.getPositionFromMatrix( object.matrixWorld );
  13715. _vector3.applyProjection( _projScreenMatrix );
  13716. webglObject.z = _vector3.z;
  13717. }
  13718. }
  13719. }
  13720. }
  13721. }
  13722. if ( this.sortObjects ) {
  13723. renderList.sort( painterSortStable );
  13724. }
  13725. // set matrices for immediate objects
  13726. renderList = scene.__webglObjectsImmediate;
  13727. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13728. webglObject = renderList[ i ];
  13729. object = webglObject.object;
  13730. if ( object.visible ) {
  13731. setupMatrices( object, camera );
  13732. unrollImmediateBufferMaterial( webglObject );
  13733. }
  13734. }
  13735. if ( scene.overrideMaterial ) {
  13736. var material = scene.overrideMaterial;
  13737. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13738. this.setDepthTest( material.depthTest );
  13739. this.setDepthWrite( material.depthWrite );
  13740. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13741. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13742. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13743. } else {
  13744. var material = null;
  13745. // opaque pass (front-to-back order)
  13746. this.setBlending( THREE.NoBlending );
  13747. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13748. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13749. // transparent pass (back-to-front order)
  13750. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13751. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13752. }
  13753. // custom render plugins (post pass)
  13754. renderPlugins( this.renderPluginsPost, scene, camera );
  13755. // Generate mipmap if we're using any kind of mipmap filtering
  13756. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13757. updateRenderTargetMipmap( renderTarget );
  13758. }
  13759. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13760. this.setDepthTest( true );
  13761. this.setDepthWrite( true );
  13762. // _gl.finish();
  13763. };
  13764. function renderPlugins( plugins, scene, camera ) {
  13765. if ( ! plugins.length ) return;
  13766. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13767. // reset state for plugin (to start from clean slate)
  13768. _currentProgram = null;
  13769. _currentCamera = null;
  13770. _oldBlending = -1;
  13771. _oldDepthTest = -1;
  13772. _oldDepthWrite = -1;
  13773. _oldDoubleSided = -1;
  13774. _oldFlipSided = -1;
  13775. _currentGeometryGroupHash = -1;
  13776. _currentMaterialId = -1;
  13777. _lightsNeedUpdate = true;
  13778. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13779. // reset state after plugin (anything could have changed)
  13780. _currentProgram = null;
  13781. _currentCamera = null;
  13782. _oldBlending = -1;
  13783. _oldDepthTest = -1;
  13784. _oldDepthWrite = -1;
  13785. _oldDoubleSided = -1;
  13786. _oldFlipSided = -1;
  13787. _currentGeometryGroupHash = -1;
  13788. _currentMaterialId = -1;
  13789. _lightsNeedUpdate = true;
  13790. }
  13791. };
  13792. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13793. var webglObject, object, buffer, material, start, end, delta;
  13794. if ( reverse ) {
  13795. start = renderList.length - 1;
  13796. end = -1;
  13797. delta = -1;
  13798. } else {
  13799. start = 0;
  13800. end = renderList.length;
  13801. delta = 1;
  13802. }
  13803. for ( var i = start; i !== end; i += delta ) {
  13804. webglObject = renderList[ i ];
  13805. if ( webglObject.render ) {
  13806. object = webglObject.object;
  13807. buffer = webglObject.buffer;
  13808. if ( overrideMaterial ) {
  13809. material = overrideMaterial;
  13810. } else {
  13811. material = webglObject[ materialType ];
  13812. if ( ! material ) continue;
  13813. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13814. _this.setDepthTest( material.depthTest );
  13815. _this.setDepthWrite( material.depthWrite );
  13816. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13817. }
  13818. _this.setMaterialFaces( material );
  13819. if ( buffer instanceof THREE.BufferGeometry ) {
  13820. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13821. } else {
  13822. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13823. }
  13824. }
  13825. }
  13826. };
  13827. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13828. var webglObject, object, material, program;
  13829. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13830. webglObject = renderList[ i ];
  13831. object = webglObject.object;
  13832. if ( object.visible ) {
  13833. if ( overrideMaterial ) {
  13834. material = overrideMaterial;
  13835. } else {
  13836. material = webglObject[ materialType ];
  13837. if ( ! material ) continue;
  13838. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13839. _this.setDepthTest( material.depthTest );
  13840. _this.setDepthWrite( material.depthWrite );
  13841. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13842. }
  13843. _this.renderImmediateObject( camera, lights, fog, material, object );
  13844. }
  13845. }
  13846. };
  13847. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13848. var program = setProgram( camera, lights, fog, material, object );
  13849. _currentGeometryGroupHash = -1;
  13850. _this.setMaterialFaces( material );
  13851. if ( object.immediateRenderCallback ) {
  13852. object.immediateRenderCallback( program, _gl, _frustum );
  13853. } else {
  13854. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13855. }
  13856. };
  13857. function unrollImmediateBufferMaterial ( globject ) {
  13858. var object = globject.object,
  13859. material = object.material;
  13860. if ( material.transparent ) {
  13861. globject.transparent = material;
  13862. globject.opaque = null;
  13863. } else {
  13864. globject.opaque = material;
  13865. globject.transparent = null;
  13866. }
  13867. };
  13868. function unrollBufferMaterial ( globject ) {
  13869. var object = globject.object,
  13870. buffer = globject.buffer,
  13871. material, materialIndex, meshMaterial;
  13872. meshMaterial = object.material;
  13873. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13874. materialIndex = buffer.materialIndex;
  13875. material = meshMaterial.materials[ materialIndex ];
  13876. if ( material.transparent ) {
  13877. globject.transparent = material;
  13878. globject.opaque = null;
  13879. } else {
  13880. globject.opaque = material;
  13881. globject.transparent = null;
  13882. }
  13883. } else {
  13884. material = meshMaterial;
  13885. if ( material ) {
  13886. if ( material.transparent ) {
  13887. globject.transparent = material;
  13888. globject.opaque = null;
  13889. } else {
  13890. globject.opaque = material;
  13891. globject.transparent = null;
  13892. }
  13893. }
  13894. }
  13895. };
  13896. // Geometry splitting
  13897. function sortFacesByMaterial ( geometry, material ) {
  13898. var f, fl, face, materialIndex, vertices,
  13899. groupHash, hash_map = {};
  13900. var numMorphTargets = geometry.morphTargets.length;
  13901. var numMorphNormals = geometry.morphNormals.length;
  13902. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13903. geometry.geometryGroups = {};
  13904. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13905. face = geometry.faces[ f ];
  13906. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13907. if ( hash_map[ materialIndex ] === undefined ) {
  13908. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13909. }
  13910. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13911. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13912. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13913. }
  13914. vertices = face instanceof THREE.Face3 ? 3 : 4;
  13915. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13916. hash_map[ materialIndex ].counter += 1;
  13917. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13918. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13919. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13920. }
  13921. }
  13922. if ( face instanceof THREE.Face3 ) {
  13923. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13924. } else {
  13925. geometry.geometryGroups[ groupHash ].faces4.push( f );
  13926. }
  13927. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13928. }
  13929. geometry.geometryGroupsList = [];
  13930. for ( var g in geometry.geometryGroups ) {
  13931. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13932. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13933. }
  13934. };
  13935. // Objects refresh
  13936. this.initWebGLObjects = function ( scene ) {
  13937. if ( !scene.__webglObjects ) {
  13938. scene.__webglObjects = [];
  13939. scene.__webglObjectsImmediate = [];
  13940. scene.__webglSprites = [];
  13941. scene.__webglFlares = [];
  13942. }
  13943. while ( scene.__objectsAdded.length ) {
  13944. addObject( scene.__objectsAdded[ 0 ], scene );
  13945. scene.__objectsAdded.splice( 0, 1 );
  13946. }
  13947. while ( scene.__objectsRemoved.length ) {
  13948. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13949. scene.__objectsRemoved.splice( 0, 1 );
  13950. }
  13951. // update must be called after objects adding / removal
  13952. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13953. var object = scene.__webglObjects[ o ].object;
  13954. // TODO: Remove this hack (WebGLRenderer refactoring)
  13955. if ( object.__webglInit === undefined ) {
  13956. if ( object.__webglActive !== undefined ) {
  13957. removeObject( object, scene );
  13958. }
  13959. addObject( object, scene );
  13960. }
  13961. updateObject( object );
  13962. }
  13963. };
  13964. // Objects adding
  13965. function addObject( object, scene ) {
  13966. var g, geometry, material, geometryGroup;
  13967. if ( object.__webglInit === undefined ) {
  13968. object.__webglInit = true;
  13969. object._modelViewMatrix = new THREE.Matrix4();
  13970. object._normalMatrix = new THREE.Matrix3();
  13971. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13972. object.geometry.__webglInit = true;
  13973. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13974. }
  13975. geometry = object.geometry;
  13976. if ( geometry === undefined ) {
  13977. // fail silently for now
  13978. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13979. initDirectBuffers( geometry );
  13980. } else if ( object instanceof THREE.Mesh ) {
  13981. material = object.material;
  13982. if ( geometry.geometryGroups === undefined ) {
  13983. sortFacesByMaterial( geometry, material );
  13984. }
  13985. // create separate VBOs per geometry chunk
  13986. for ( g in geometry.geometryGroups ) {
  13987. geometryGroup = geometry.geometryGroups[ g ];
  13988. // initialise VBO on the first access
  13989. if ( ! geometryGroup.__webglVertexBuffer ) {
  13990. createMeshBuffers( geometryGroup );
  13991. initMeshBuffers( geometryGroup, object );
  13992. geometry.verticesNeedUpdate = true;
  13993. geometry.morphTargetsNeedUpdate = true;
  13994. geometry.elementsNeedUpdate = true;
  13995. geometry.uvsNeedUpdate = true;
  13996. geometry.normalsNeedUpdate = true;
  13997. geometry.tangentsNeedUpdate = true;
  13998. geometry.colorsNeedUpdate = true;
  13999. }
  14000. }
  14001. } else if ( object instanceof THREE.Ribbon ) {
  14002. if ( ! geometry.__webglVertexBuffer ) {
  14003. createRibbonBuffers( geometry );
  14004. initRibbonBuffers( geometry, object );
  14005. geometry.verticesNeedUpdate = true;
  14006. geometry.colorsNeedUpdate = true;
  14007. geometry.normalsNeedUpdate = true;
  14008. }
  14009. } else if ( object instanceof THREE.Line ) {
  14010. if ( ! geometry.__webglVertexBuffer ) {
  14011. createLineBuffers( geometry );
  14012. initLineBuffers( geometry, object );
  14013. geometry.verticesNeedUpdate = true;
  14014. geometry.colorsNeedUpdate = true;
  14015. geometry.lineDistancesNeedUpdate = true;
  14016. }
  14017. } else if ( object instanceof THREE.ParticleSystem ) {
  14018. if ( ! geometry.__webglVertexBuffer ) {
  14019. createParticleBuffers( geometry );
  14020. initParticleBuffers( geometry, object );
  14021. geometry.verticesNeedUpdate = true;
  14022. geometry.colorsNeedUpdate = true;
  14023. }
  14024. }
  14025. }
  14026. if ( object.__webglActive === undefined ) {
  14027. if ( object instanceof THREE.Mesh ) {
  14028. geometry = object.geometry;
  14029. if ( geometry instanceof THREE.BufferGeometry ) {
  14030. addBuffer( scene.__webglObjects, geometry, object );
  14031. } else if ( geometry instanceof THREE.Geometry ) {
  14032. for ( g in geometry.geometryGroups ) {
  14033. geometryGroup = geometry.geometryGroups[ g ];
  14034. addBuffer( scene.__webglObjects, geometryGroup, object );
  14035. }
  14036. }
  14037. } else if ( object instanceof THREE.Ribbon ||
  14038. object instanceof THREE.Line ||
  14039. object instanceof THREE.ParticleSystem ) {
  14040. geometry = object.geometry;
  14041. addBuffer( scene.__webglObjects, geometry, object );
  14042. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14043. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14044. } else if ( object instanceof THREE.Sprite ) {
  14045. scene.__webglSprites.push( object );
  14046. } else if ( object instanceof THREE.LensFlare ) {
  14047. scene.__webglFlares.push( object );
  14048. }
  14049. object.__webglActive = true;
  14050. }
  14051. };
  14052. function addBuffer( objlist, buffer, object ) {
  14053. objlist.push(
  14054. {
  14055. id: null,
  14056. buffer: buffer,
  14057. object: object,
  14058. opaque: null,
  14059. transparent: null,
  14060. z: 0
  14061. }
  14062. );
  14063. };
  14064. function addBufferImmediate( objlist, object ) {
  14065. objlist.push(
  14066. {
  14067. id: null,
  14068. object: object,
  14069. opaque: null,
  14070. transparent: null,
  14071. z: 0
  14072. }
  14073. );
  14074. };
  14075. // Objects updates
  14076. function updateObject( object ) {
  14077. var geometry = object.geometry,
  14078. geometryGroup, customAttributesDirty, material;
  14079. if ( geometry instanceof THREE.BufferGeometry ) {
  14080. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  14081. } else if ( object instanceof THREE.Mesh ) {
  14082. // check all geometry groups
  14083. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14084. geometryGroup = geometry.geometryGroupsList[ i ];
  14085. material = getBufferMaterial( object, geometryGroup );
  14086. if ( geometry.buffersNeedUpdate ) {
  14087. initMeshBuffers( geometryGroup, object );
  14088. }
  14089. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14090. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14091. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14092. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14093. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14094. }
  14095. }
  14096. geometry.verticesNeedUpdate = false;
  14097. geometry.morphTargetsNeedUpdate = false;
  14098. geometry.elementsNeedUpdate = false;
  14099. geometry.uvsNeedUpdate = false;
  14100. geometry.normalsNeedUpdate = false;
  14101. geometry.colorsNeedUpdate = false;
  14102. geometry.tangentsNeedUpdate = false;
  14103. geometry.buffersNeedUpdate = false;
  14104. material.attributes && clearCustomAttributes( material );
  14105. } else if ( object instanceof THREE.Ribbon ) {
  14106. material = getBufferMaterial( object, geometry );
  14107. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14108. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  14109. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  14110. }
  14111. geometry.verticesNeedUpdate = false;
  14112. geometry.colorsNeedUpdate = false;
  14113. geometry.normalsNeedUpdate = false;
  14114. material.attributes && clearCustomAttributes( material );
  14115. } else if ( object instanceof THREE.Line ) {
  14116. material = getBufferMaterial( object, geometry );
  14117. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14118. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14119. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14120. }
  14121. geometry.verticesNeedUpdate = false;
  14122. geometry.colorsNeedUpdate = false;
  14123. geometry.lineDistancesNeedUpdate = false;
  14124. material.attributes && clearCustomAttributes( material );
  14125. } else if ( object instanceof THREE.ParticleSystem ) {
  14126. material = getBufferMaterial( object, geometry );
  14127. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14128. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14129. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14130. }
  14131. geometry.verticesNeedUpdate = false;
  14132. geometry.colorsNeedUpdate = false;
  14133. material.attributes && clearCustomAttributes( material );
  14134. }
  14135. };
  14136. // Objects updates - custom attributes check
  14137. function areCustomAttributesDirty( material ) {
  14138. for ( var a in material.attributes ) {
  14139. if ( material.attributes[ a ].needsUpdate ) return true;
  14140. }
  14141. return false;
  14142. };
  14143. function clearCustomAttributes( material ) {
  14144. for ( var a in material.attributes ) {
  14145. material.attributes[ a ].needsUpdate = false;
  14146. }
  14147. };
  14148. // Objects removal
  14149. function removeObject( object, scene ) {
  14150. if ( object instanceof THREE.Mesh ||
  14151. object instanceof THREE.ParticleSystem ||
  14152. object instanceof THREE.Ribbon ||
  14153. object instanceof THREE.Line ) {
  14154. removeInstances( scene.__webglObjects, object );
  14155. } else if ( object instanceof THREE.Sprite ) {
  14156. removeInstancesDirect( scene.__webglSprites, object );
  14157. } else if ( object instanceof THREE.LensFlare ) {
  14158. removeInstancesDirect( scene.__webglFlares, object );
  14159. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14160. removeInstances( scene.__webglObjectsImmediate, object );
  14161. }
  14162. delete object.__webglActive;
  14163. };
  14164. function removeInstances( objlist, object ) {
  14165. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14166. if ( objlist[ o ].object === object ) {
  14167. objlist.splice( o, 1 );
  14168. }
  14169. }
  14170. };
  14171. function removeInstancesDirect( objlist, object ) {
  14172. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14173. if ( objlist[ o ] === object ) {
  14174. objlist.splice( o, 1 );
  14175. }
  14176. }
  14177. };
  14178. // Materials
  14179. this.initMaterial = function ( material, lights, fog, object ) {
  14180. material.addEventListener( 'dispose', onMaterialDispose );
  14181. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14182. if ( material instanceof THREE.MeshDepthMaterial ) {
  14183. shaderID = 'depth';
  14184. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14185. shaderID = 'normal';
  14186. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14187. shaderID = 'basic';
  14188. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14189. shaderID = 'lambert';
  14190. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14191. shaderID = 'phong';
  14192. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14193. shaderID = 'basic';
  14194. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14195. shaderID = 'dashed';
  14196. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14197. shaderID = 'particle_basic';
  14198. }
  14199. if ( shaderID ) {
  14200. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14201. }
  14202. // heuristics to create shader parameters according to lights in the scene
  14203. // (not to blow over maxLights budget)
  14204. maxLightCount = allocateLights( lights );
  14205. maxShadows = allocateShadows( lights );
  14206. maxBones = allocateBones( object );
  14207. parameters = {
  14208. map: !!material.map,
  14209. envMap: !!material.envMap,
  14210. lightMap: !!material.lightMap,
  14211. bumpMap: !!material.bumpMap,
  14212. normalMap: !!material.normalMap,
  14213. specularMap: !!material.specularMap,
  14214. vertexColors: material.vertexColors,
  14215. fog: fog,
  14216. useFog: material.fog,
  14217. fogExp: fog instanceof THREE.FogExp2,
  14218. sizeAttenuation: material.sizeAttenuation,
  14219. skinning: material.skinning,
  14220. maxBones: maxBones,
  14221. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14222. boneTextureWidth: object && object.boneTextureWidth,
  14223. boneTextureHeight: object && object.boneTextureHeight,
  14224. morphTargets: material.morphTargets,
  14225. morphNormals: material.morphNormals,
  14226. maxMorphTargets: this.maxMorphTargets,
  14227. maxMorphNormals: this.maxMorphNormals,
  14228. maxDirLights: maxLightCount.directional,
  14229. maxPointLights: maxLightCount.point,
  14230. maxSpotLights: maxLightCount.spot,
  14231. maxHemiLights: maxLightCount.hemi,
  14232. maxShadows: maxShadows,
  14233. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  14234. shadowMapType: this.shadowMapType,
  14235. shadowMapDebug: this.shadowMapDebug,
  14236. shadowMapCascade: this.shadowMapCascade,
  14237. alphaTest: material.alphaTest,
  14238. metal: material.metal,
  14239. perPixel: material.perPixel,
  14240. wrapAround: material.wrapAround,
  14241. doubleSided: material.side === THREE.DoubleSide,
  14242. flipSided: material.side === THREE.BackSide
  14243. };
  14244. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  14245. var attributes = material.program.attributes;
  14246. if ( material.morphTargets ) {
  14247. material.numSupportedMorphTargets = 0;
  14248. var id, base = "morphTarget";
  14249. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14250. id = base + i;
  14251. if ( attributes[ id ] >= 0 ) {
  14252. material.numSupportedMorphTargets ++;
  14253. }
  14254. }
  14255. }
  14256. if ( material.morphNormals ) {
  14257. material.numSupportedMorphNormals = 0;
  14258. var id, base = "morphNormal";
  14259. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14260. id = base + i;
  14261. if ( attributes[ id ] >= 0 ) {
  14262. material.numSupportedMorphNormals ++;
  14263. }
  14264. }
  14265. }
  14266. material.uniformsList = [];
  14267. for ( u in material.uniforms ) {
  14268. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14269. }
  14270. };
  14271. function setMaterialShaders( material, shaders ) {
  14272. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14273. material.vertexShader = shaders.vertexShader;
  14274. material.fragmentShader = shaders.fragmentShader;
  14275. };
  14276. function setProgram( camera, lights, fog, material, object ) {
  14277. _usedTextureUnits = 0;
  14278. if ( material.needsUpdate ) {
  14279. if ( material.program ) deallocateMaterial( material );
  14280. _this.initMaterial( material, lights, fog, object );
  14281. material.needsUpdate = false;
  14282. }
  14283. if ( material.morphTargets ) {
  14284. if ( ! object.__webglMorphTargetInfluences ) {
  14285. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14286. }
  14287. }
  14288. var refreshMaterial = false;
  14289. var program = material.program,
  14290. p_uniforms = program.uniforms,
  14291. m_uniforms = material.uniforms;
  14292. if ( program !== _currentProgram ) {
  14293. _gl.useProgram( program );
  14294. _currentProgram = program;
  14295. refreshMaterial = true;
  14296. }
  14297. if ( material.id !== _currentMaterialId ) {
  14298. _currentMaterialId = material.id;
  14299. refreshMaterial = true;
  14300. }
  14301. if ( refreshMaterial || camera !== _currentCamera ) {
  14302. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14303. if ( camera !== _currentCamera ) _currentCamera = camera;
  14304. }
  14305. // skinning uniforms must be set even if material didn't change
  14306. // auto-setting of texture unit for bone texture must go before other textures
  14307. // not sure why, but otherwise weird things happen
  14308. if ( material.skinning ) {
  14309. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14310. if ( p_uniforms.boneTexture !== null ) {
  14311. var textureUnit = getTextureUnit();
  14312. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14313. _this.setTexture( object.boneTexture, textureUnit );
  14314. }
  14315. } else {
  14316. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14317. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14318. }
  14319. }
  14320. }
  14321. if ( refreshMaterial ) {
  14322. // refresh uniforms common to several materials
  14323. if ( fog && material.fog ) {
  14324. refreshUniformsFog( m_uniforms, fog );
  14325. }
  14326. if ( material instanceof THREE.MeshPhongMaterial ||
  14327. material instanceof THREE.MeshLambertMaterial ||
  14328. material.lights ) {
  14329. if ( _lightsNeedUpdate ) {
  14330. setupLights( program, lights );
  14331. _lightsNeedUpdate = false;
  14332. }
  14333. refreshUniformsLights( m_uniforms, _lights );
  14334. }
  14335. if ( material instanceof THREE.MeshBasicMaterial ||
  14336. material instanceof THREE.MeshLambertMaterial ||
  14337. material instanceof THREE.MeshPhongMaterial ) {
  14338. refreshUniformsCommon( m_uniforms, material );
  14339. }
  14340. // refresh single material specific uniforms
  14341. if ( material instanceof THREE.LineBasicMaterial ) {
  14342. refreshUniformsLine( m_uniforms, material );
  14343. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14344. refreshUniformsLine( m_uniforms, material );
  14345. refreshUniformsDash( m_uniforms, material );
  14346. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14347. refreshUniformsParticle( m_uniforms, material );
  14348. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14349. refreshUniformsPhong( m_uniforms, material );
  14350. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14351. refreshUniformsLambert( m_uniforms, material );
  14352. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14353. m_uniforms.mNear.value = camera.near;
  14354. m_uniforms.mFar.value = camera.far;
  14355. m_uniforms.opacity.value = material.opacity;
  14356. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14357. m_uniforms.opacity.value = material.opacity;
  14358. }
  14359. if ( object.receiveShadow && ! material._shadowPass ) {
  14360. refreshUniformsShadow( m_uniforms, lights );
  14361. }
  14362. // load common uniforms
  14363. loadUniformsGeneric( program, material.uniformsList );
  14364. // load material specific uniforms
  14365. // (shader material also gets them for the sake of genericity)
  14366. if ( material instanceof THREE.ShaderMaterial ||
  14367. material instanceof THREE.MeshPhongMaterial ||
  14368. material.envMap ) {
  14369. if ( p_uniforms.cameraPosition !== null ) {
  14370. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14371. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14372. }
  14373. }
  14374. if ( material instanceof THREE.MeshPhongMaterial ||
  14375. material instanceof THREE.MeshLambertMaterial ||
  14376. material instanceof THREE.ShaderMaterial ||
  14377. material.skinning ) {
  14378. if ( p_uniforms.viewMatrix !== null ) {
  14379. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14380. }
  14381. }
  14382. }
  14383. loadUniformsMatrices( p_uniforms, object );
  14384. if ( p_uniforms.modelMatrix !== null ) {
  14385. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14386. }
  14387. return program;
  14388. };
  14389. // Uniforms (refresh uniforms objects)
  14390. function refreshUniformsCommon ( uniforms, material ) {
  14391. uniforms.opacity.value = material.opacity;
  14392. if ( _this.gammaInput ) {
  14393. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14394. } else {
  14395. uniforms.diffuse.value = material.color;
  14396. }
  14397. uniforms.map.value = material.map;
  14398. uniforms.lightMap.value = material.lightMap;
  14399. uniforms.specularMap.value = material.specularMap;
  14400. if ( material.bumpMap ) {
  14401. uniforms.bumpMap.value = material.bumpMap;
  14402. uniforms.bumpScale.value = material.bumpScale;
  14403. }
  14404. if ( material.normalMap ) {
  14405. uniforms.normalMap.value = material.normalMap;
  14406. uniforms.normalScale.value.copy( material.normalScale );
  14407. }
  14408. // uv repeat and offset setting priorities
  14409. // 1. color map
  14410. // 2. specular map
  14411. // 3. normal map
  14412. // 4. bump map
  14413. var uvScaleMap;
  14414. if ( material.map ) {
  14415. uvScaleMap = material.map;
  14416. } else if ( material.specularMap ) {
  14417. uvScaleMap = material.specularMap;
  14418. } else if ( material.normalMap ) {
  14419. uvScaleMap = material.normalMap;
  14420. } else if ( material.bumpMap ) {
  14421. uvScaleMap = material.bumpMap;
  14422. }
  14423. if ( uvScaleMap !== undefined ) {
  14424. var offset = uvScaleMap.offset;
  14425. var repeat = uvScaleMap.repeat;
  14426. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14427. }
  14428. uniforms.envMap.value = material.envMap;
  14429. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14430. if ( _this.gammaInput ) {
  14431. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14432. uniforms.reflectivity.value = material.reflectivity;
  14433. } else {
  14434. uniforms.reflectivity.value = material.reflectivity;
  14435. }
  14436. uniforms.refractionRatio.value = material.refractionRatio;
  14437. uniforms.combine.value = material.combine;
  14438. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14439. };
  14440. function refreshUniformsLine ( uniforms, material ) {
  14441. uniforms.diffuse.value = material.color;
  14442. uniforms.opacity.value = material.opacity;
  14443. };
  14444. function refreshUniformsDash ( uniforms, material ) {
  14445. uniforms.dashSize.value = material.dashSize;
  14446. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14447. uniforms.scale.value = material.scale;
  14448. };
  14449. function refreshUniformsParticle ( uniforms, material ) {
  14450. uniforms.psColor.value = material.color;
  14451. uniforms.opacity.value = material.opacity;
  14452. uniforms.size.value = material.size;
  14453. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14454. uniforms.map.value = material.map;
  14455. };
  14456. function refreshUniformsFog ( uniforms, fog ) {
  14457. uniforms.fogColor.value = fog.color;
  14458. if ( fog instanceof THREE.Fog ) {
  14459. uniforms.fogNear.value = fog.near;
  14460. uniforms.fogFar.value = fog.far;
  14461. } else if ( fog instanceof THREE.FogExp2 ) {
  14462. uniforms.fogDensity.value = fog.density;
  14463. }
  14464. };
  14465. function refreshUniformsPhong ( uniforms, material ) {
  14466. uniforms.shininess.value = material.shininess;
  14467. if ( _this.gammaInput ) {
  14468. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14469. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14470. uniforms.specular.value.copyGammaToLinear( material.specular );
  14471. } else {
  14472. uniforms.ambient.value = material.ambient;
  14473. uniforms.emissive.value = material.emissive;
  14474. uniforms.specular.value = material.specular;
  14475. }
  14476. if ( material.wrapAround ) {
  14477. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14478. }
  14479. };
  14480. function refreshUniformsLambert ( uniforms, material ) {
  14481. if ( _this.gammaInput ) {
  14482. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14483. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14484. } else {
  14485. uniforms.ambient.value = material.ambient;
  14486. uniforms.emissive.value = material.emissive;
  14487. }
  14488. if ( material.wrapAround ) {
  14489. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14490. }
  14491. };
  14492. function refreshUniformsLights ( uniforms, lights ) {
  14493. uniforms.ambientLightColor.value = lights.ambient;
  14494. uniforms.directionalLightColor.value = lights.directional.colors;
  14495. uniforms.directionalLightDirection.value = lights.directional.positions;
  14496. uniforms.pointLightColor.value = lights.point.colors;
  14497. uniforms.pointLightPosition.value = lights.point.positions;
  14498. uniforms.pointLightDistance.value = lights.point.distances;
  14499. uniforms.spotLightColor.value = lights.spot.colors;
  14500. uniforms.spotLightPosition.value = lights.spot.positions;
  14501. uniforms.spotLightDistance.value = lights.spot.distances;
  14502. uniforms.spotLightDirection.value = lights.spot.directions;
  14503. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14504. uniforms.spotLightExponent.value = lights.spot.exponents;
  14505. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14506. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14507. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14508. };
  14509. function refreshUniformsShadow ( uniforms, lights ) {
  14510. if ( uniforms.shadowMatrix ) {
  14511. var j = 0;
  14512. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14513. var light = lights[ i ];
  14514. if ( ! light.castShadow ) continue;
  14515. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14516. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14517. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14518. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14519. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14520. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14521. j ++;
  14522. }
  14523. }
  14524. }
  14525. };
  14526. // Uniforms (load to GPU)
  14527. function loadUniformsMatrices ( uniforms, object ) {
  14528. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14529. if ( uniforms.normalMatrix ) {
  14530. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14531. }
  14532. };
  14533. function getTextureUnit() {
  14534. var textureUnit = _usedTextureUnits;
  14535. if ( textureUnit >= _maxTextures ) {
  14536. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14537. }
  14538. _usedTextureUnits += 1;
  14539. return textureUnit;
  14540. };
  14541. function loadUniformsGeneric ( program, uniforms ) {
  14542. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14543. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14544. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14545. if ( !location ) continue;
  14546. uniform = uniforms[ j ][ 0 ];
  14547. type = uniform.type;
  14548. value = uniform.value;
  14549. if ( type === "i" ) { // single integer
  14550. _gl.uniform1i( location, value );
  14551. } else if ( type === "f" ) { // single float
  14552. _gl.uniform1f( location, value );
  14553. } else if ( type === "v2" ) { // single THREE.Vector2
  14554. _gl.uniform2f( location, value.x, value.y );
  14555. } else if ( type === "v3" ) { // single THREE.Vector3
  14556. _gl.uniform3f( location, value.x, value.y, value.z );
  14557. } else if ( type === "v4" ) { // single THREE.Vector4
  14558. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14559. } else if ( type === "c" ) { // single THREE.Color
  14560. _gl.uniform3f( location, value.r, value.g, value.b );
  14561. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14562. _gl.uniform1iv( location, value );
  14563. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14564. _gl.uniform3iv( location, value );
  14565. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14566. _gl.uniform1fv( location, value );
  14567. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14568. _gl.uniform3fv( location, value );
  14569. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14570. if ( uniform._array === undefined ) {
  14571. uniform._array = new Float32Array( 2 * value.length );
  14572. }
  14573. for ( i = 0, il = value.length; i < il; i ++ ) {
  14574. offset = i * 2;
  14575. uniform._array[ offset ] = value[ i ].x;
  14576. uniform._array[ offset + 1 ] = value[ i ].y;
  14577. }
  14578. _gl.uniform2fv( location, uniform._array );
  14579. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14580. if ( uniform._array === undefined ) {
  14581. uniform._array = new Float32Array( 3 * value.length );
  14582. }
  14583. for ( i = 0, il = value.length; i < il; i ++ ) {
  14584. offset = i * 3;
  14585. uniform._array[ offset ] = value[ i ].x;
  14586. uniform._array[ offset + 1 ] = value[ i ].y;
  14587. uniform._array[ offset + 2 ] = value[ i ].z;
  14588. }
  14589. _gl.uniform3fv( location, uniform._array );
  14590. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14591. if ( uniform._array === undefined ) {
  14592. uniform._array = new Float32Array( 4 * value.length );
  14593. }
  14594. for ( i = 0, il = value.length; i < il; i ++ ) {
  14595. offset = i * 4;
  14596. uniform._array[ offset ] = value[ i ].x;
  14597. uniform._array[ offset + 1 ] = value[ i ].y;
  14598. uniform._array[ offset + 2 ] = value[ i ].z;
  14599. uniform._array[ offset + 3 ] = value[ i ].w;
  14600. }
  14601. _gl.uniform4fv( location, uniform._array );
  14602. } else if ( type === "m4") { // single THREE.Matrix4
  14603. if ( uniform._array === undefined ) {
  14604. uniform._array = new Float32Array( 16 );
  14605. }
  14606. value.flattenToArray( uniform._array );
  14607. _gl.uniformMatrix4fv( location, false, uniform._array );
  14608. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14609. if ( uniform._array === undefined ) {
  14610. uniform._array = new Float32Array( 16 * value.length );
  14611. }
  14612. for ( i = 0, il = value.length; i < il; i ++ ) {
  14613. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14614. }
  14615. _gl.uniformMatrix4fv( location, false, uniform._array );
  14616. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14617. texture = value;
  14618. textureUnit = getTextureUnit();
  14619. _gl.uniform1i( location, textureUnit );
  14620. if ( !texture ) continue;
  14621. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14622. setCubeTexture( texture, textureUnit );
  14623. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14624. setCubeTextureDynamic( texture, textureUnit );
  14625. } else {
  14626. _this.setTexture( texture, textureUnit );
  14627. }
  14628. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14629. if ( uniform._array === undefined ) {
  14630. uniform._array = [];
  14631. }
  14632. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14633. uniform._array[ i ] = getTextureUnit();
  14634. }
  14635. _gl.uniform1iv( location, uniform._array );
  14636. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14637. texture = uniform.value[ i ];
  14638. textureUnit = uniform._array[ i ];
  14639. if ( !texture ) continue;
  14640. _this.setTexture( texture, textureUnit );
  14641. }
  14642. }
  14643. }
  14644. };
  14645. function setupMatrices ( object, camera ) {
  14646. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14647. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14648. };
  14649. //
  14650. function setColorGamma( array, offset, color, intensitySq ) {
  14651. array[ offset ] = color.r * color.r * intensitySq;
  14652. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14653. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14654. };
  14655. function setColorLinear( array, offset, color, intensity ) {
  14656. array[ offset ] = color.r * intensity;
  14657. array[ offset + 1 ] = color.g * intensity;
  14658. array[ offset + 2 ] = color.b * intensity;
  14659. };
  14660. function setupLights ( program, lights ) {
  14661. var l, ll, light, n,
  14662. r = 0, g = 0, b = 0,
  14663. color, skyColor, groundColor,
  14664. intensity, intensitySq,
  14665. position,
  14666. distance,
  14667. zlights = _lights,
  14668. dirColors = zlights.directional.colors,
  14669. dirPositions = zlights.directional.positions,
  14670. pointColors = zlights.point.colors,
  14671. pointPositions = zlights.point.positions,
  14672. pointDistances = zlights.point.distances,
  14673. spotColors = zlights.spot.colors,
  14674. spotPositions = zlights.spot.positions,
  14675. spotDistances = zlights.spot.distances,
  14676. spotDirections = zlights.spot.directions,
  14677. spotAnglesCos = zlights.spot.anglesCos,
  14678. spotExponents = zlights.spot.exponents,
  14679. hemiSkyColors = zlights.hemi.skyColors,
  14680. hemiGroundColors = zlights.hemi.groundColors,
  14681. hemiPositions = zlights.hemi.positions,
  14682. dirLength = 0,
  14683. pointLength = 0,
  14684. spotLength = 0,
  14685. hemiLength = 0,
  14686. dirCount = 0,
  14687. pointCount = 0,
  14688. spotCount = 0,
  14689. hemiCount = 0,
  14690. dirOffset = 0,
  14691. pointOffset = 0,
  14692. spotOffset = 0,
  14693. hemiOffset = 0;
  14694. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14695. light = lights[ l ];
  14696. if ( light.onlyShadow ) continue;
  14697. color = light.color;
  14698. intensity = light.intensity;
  14699. distance = light.distance;
  14700. if ( light instanceof THREE.AmbientLight ) {
  14701. if ( ! light.visible ) continue;
  14702. if ( _this.gammaInput ) {
  14703. r += color.r * color.r;
  14704. g += color.g * color.g;
  14705. b += color.b * color.b;
  14706. } else {
  14707. r += color.r;
  14708. g += color.g;
  14709. b += color.b;
  14710. }
  14711. } else if ( light instanceof THREE.DirectionalLight ) {
  14712. dirCount += 1;
  14713. if ( ! light.visible ) continue;
  14714. _direction.getPositionFromMatrix( light.matrixWorld );
  14715. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14716. _direction.sub( _vector3 );
  14717. _direction.normalize();
  14718. // skip lights with undefined direction
  14719. // these create troubles in OpenGL (making pixel black)
  14720. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14721. dirOffset = dirLength * 3;
  14722. dirPositions[ dirOffset ] = _direction.x;
  14723. dirPositions[ dirOffset + 1 ] = _direction.y;
  14724. dirPositions[ dirOffset + 2 ] = _direction.z;
  14725. if ( _this.gammaInput ) {
  14726. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14727. } else {
  14728. setColorLinear( dirColors, dirOffset, color, intensity );
  14729. }
  14730. dirLength += 1;
  14731. } else if ( light instanceof THREE.PointLight ) {
  14732. pointCount += 1;
  14733. if ( ! light.visible ) continue;
  14734. pointOffset = pointLength * 3;
  14735. if ( _this.gammaInput ) {
  14736. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14737. } else {
  14738. setColorLinear( pointColors, pointOffset, color, intensity );
  14739. }
  14740. _vector3.getPositionFromMatrix( light.matrixWorld );
  14741. pointPositions[ pointOffset ] = _vector3.x;
  14742. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14743. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14744. pointDistances[ pointLength ] = distance;
  14745. pointLength += 1;
  14746. } else if ( light instanceof THREE.SpotLight ) {
  14747. spotCount += 1;
  14748. if ( ! light.visible ) continue;
  14749. spotOffset = spotLength * 3;
  14750. if ( _this.gammaInput ) {
  14751. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14752. } else {
  14753. setColorLinear( spotColors, spotOffset, color, intensity );
  14754. }
  14755. _vector3.getPositionFromMatrix( light.matrixWorld );
  14756. spotPositions[ spotOffset ] = _vector3.x;
  14757. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14758. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14759. spotDistances[ spotLength ] = distance;
  14760. _direction.copy( _vector3 );
  14761. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14762. _direction.sub( _vector3 );
  14763. _direction.normalize();
  14764. spotDirections[ spotOffset ] = _direction.x;
  14765. spotDirections[ spotOffset + 1 ] = _direction.y;
  14766. spotDirections[ spotOffset + 2 ] = _direction.z;
  14767. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14768. spotExponents[ spotLength ] = light.exponent;
  14769. spotLength += 1;
  14770. } else if ( light instanceof THREE.HemisphereLight ) {
  14771. hemiCount += 1;
  14772. if ( ! light.visible ) continue;
  14773. _direction.getPositionFromMatrix( light.matrixWorld );
  14774. _direction.normalize();
  14775. // skip lights with undefined direction
  14776. // these create troubles in OpenGL (making pixel black)
  14777. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14778. hemiOffset = hemiLength * 3;
  14779. hemiPositions[ hemiOffset ] = _direction.x;
  14780. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14781. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14782. skyColor = light.color;
  14783. groundColor = light.groundColor;
  14784. if ( _this.gammaInput ) {
  14785. intensitySq = intensity * intensity;
  14786. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14787. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14788. } else {
  14789. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14790. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14791. }
  14792. hemiLength += 1;
  14793. }
  14794. }
  14795. // null eventual remains from removed lights
  14796. // (this is to avoid if in shader)
  14797. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14798. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14799. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14800. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14801. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14802. zlights.directional.length = dirLength;
  14803. zlights.point.length = pointLength;
  14804. zlights.spot.length = spotLength;
  14805. zlights.hemi.length = hemiLength;
  14806. zlights.ambient[ 0 ] = r;
  14807. zlights.ambient[ 1 ] = g;
  14808. zlights.ambient[ 2 ] = b;
  14809. };
  14810. // GL state setting
  14811. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14812. if ( cullFace === THREE.CullFaceNone ) {
  14813. _gl.disable( _gl.CULL_FACE );
  14814. } else {
  14815. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14816. _gl.frontFace( _gl.CW );
  14817. } else {
  14818. _gl.frontFace( _gl.CCW );
  14819. }
  14820. if ( cullFace === THREE.CullFaceBack ) {
  14821. _gl.cullFace( _gl.BACK );
  14822. } else if ( cullFace === THREE.CullFaceFront ) {
  14823. _gl.cullFace( _gl.FRONT );
  14824. } else {
  14825. _gl.cullFace( _gl.FRONT_AND_BACK );
  14826. }
  14827. _gl.enable( _gl.CULL_FACE );
  14828. }
  14829. };
  14830. this.setMaterialFaces = function ( material ) {
  14831. var doubleSided = material.side === THREE.DoubleSide;
  14832. var flipSided = material.side === THREE.BackSide;
  14833. if ( _oldDoubleSided !== doubleSided ) {
  14834. if ( doubleSided ) {
  14835. _gl.disable( _gl.CULL_FACE );
  14836. } else {
  14837. _gl.enable( _gl.CULL_FACE );
  14838. }
  14839. _oldDoubleSided = doubleSided;
  14840. }
  14841. if ( _oldFlipSided !== flipSided ) {
  14842. if ( flipSided ) {
  14843. _gl.frontFace( _gl.CW );
  14844. } else {
  14845. _gl.frontFace( _gl.CCW );
  14846. }
  14847. _oldFlipSided = flipSided;
  14848. }
  14849. };
  14850. this.setDepthTest = function ( depthTest ) {
  14851. if ( _oldDepthTest !== depthTest ) {
  14852. if ( depthTest ) {
  14853. _gl.enable( _gl.DEPTH_TEST );
  14854. } else {
  14855. _gl.disable( _gl.DEPTH_TEST );
  14856. }
  14857. _oldDepthTest = depthTest;
  14858. }
  14859. };
  14860. this.setDepthWrite = function ( depthWrite ) {
  14861. if ( _oldDepthWrite !== depthWrite ) {
  14862. _gl.depthMask( depthWrite );
  14863. _oldDepthWrite = depthWrite;
  14864. }
  14865. };
  14866. function setLineWidth ( width ) {
  14867. if ( width !== _oldLineWidth ) {
  14868. _gl.lineWidth( width );
  14869. _oldLineWidth = width;
  14870. }
  14871. };
  14872. function setPolygonOffset ( polygonoffset, factor, units ) {
  14873. if ( _oldPolygonOffset !== polygonoffset ) {
  14874. if ( polygonoffset ) {
  14875. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14876. } else {
  14877. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14878. }
  14879. _oldPolygonOffset = polygonoffset;
  14880. }
  14881. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14882. _gl.polygonOffset( factor, units );
  14883. _oldPolygonOffsetFactor = factor;
  14884. _oldPolygonOffsetUnits = units;
  14885. }
  14886. };
  14887. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14888. if ( blending !== _oldBlending ) {
  14889. if ( blending === THREE.NoBlending ) {
  14890. _gl.disable( _gl.BLEND );
  14891. } else if ( blending === THREE.AdditiveBlending ) {
  14892. _gl.enable( _gl.BLEND );
  14893. _gl.blendEquation( _gl.FUNC_ADD );
  14894. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14895. } else if ( blending === THREE.SubtractiveBlending ) {
  14896. // TODO: Find blendFuncSeparate() combination
  14897. _gl.enable( _gl.BLEND );
  14898. _gl.blendEquation( _gl.FUNC_ADD );
  14899. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14900. } else if ( blending === THREE.MultiplyBlending ) {
  14901. // TODO: Find blendFuncSeparate() combination
  14902. _gl.enable( _gl.BLEND );
  14903. _gl.blendEquation( _gl.FUNC_ADD );
  14904. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14905. } else if ( blending === THREE.CustomBlending ) {
  14906. _gl.enable( _gl.BLEND );
  14907. } else {
  14908. _gl.enable( _gl.BLEND );
  14909. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14910. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14911. }
  14912. _oldBlending = blending;
  14913. }
  14914. if ( blending === THREE.CustomBlending ) {
  14915. if ( blendEquation !== _oldBlendEquation ) {
  14916. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14917. _oldBlendEquation = blendEquation;
  14918. }
  14919. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14920. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14921. _oldBlendSrc = blendSrc;
  14922. _oldBlendDst = blendDst;
  14923. }
  14924. } else {
  14925. _oldBlendEquation = null;
  14926. _oldBlendSrc = null;
  14927. _oldBlendDst = null;
  14928. }
  14929. };
  14930. // Defines
  14931. function generateDefines ( defines ) {
  14932. var value, chunk, chunks = [];
  14933. for ( var d in defines ) {
  14934. value = defines[ d ];
  14935. if ( value === false ) continue;
  14936. chunk = "#define " + d + " " + value;
  14937. chunks.push( chunk );
  14938. }
  14939. return chunks.join( "\n" );
  14940. };
  14941. // Shaders
  14942. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  14943. var p, pl, d, program, code;
  14944. var chunks = [];
  14945. // Generate code
  14946. if ( shaderID ) {
  14947. chunks.push( shaderID );
  14948. } else {
  14949. chunks.push( fragmentShader );
  14950. chunks.push( vertexShader );
  14951. }
  14952. for ( d in defines ) {
  14953. chunks.push( d );
  14954. chunks.push( defines[ d ] );
  14955. }
  14956. for ( p in parameters ) {
  14957. chunks.push( p );
  14958. chunks.push( parameters[ p ] );
  14959. }
  14960. code = chunks.join();
  14961. // Check if code has been already compiled
  14962. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14963. var programInfo = _programs[ p ];
  14964. if ( programInfo.code === code ) {
  14965. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14966. programInfo.usedTimes ++;
  14967. return programInfo.program;
  14968. }
  14969. }
  14970. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14971. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14972. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14973. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14974. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14975. }
  14976. // console.log( "building new program " );
  14977. //
  14978. var customDefines = generateDefines( defines );
  14979. //
  14980. program = _gl.createProgram();
  14981. var prefix_vertex = [
  14982. "precision " + _precision + " float;",
  14983. customDefines,
  14984. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14985. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14986. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14987. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14988. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14989. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14990. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14991. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14992. "#define MAX_SHADOWS " + parameters.maxShadows,
  14993. "#define MAX_BONES " + parameters.maxBones,
  14994. parameters.map ? "#define USE_MAP" : "",
  14995. parameters.envMap ? "#define USE_ENVMAP" : "",
  14996. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14997. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14998. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14999. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15000. parameters.vertexColors ? "#define USE_COLOR" : "",
  15001. parameters.skinning ? "#define USE_SKINNING" : "",
  15002. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15003. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  15004. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  15005. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15006. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15007. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15008. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15009. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15010. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15011. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15012. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15013. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15014. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15015. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15016. "uniform mat4 modelMatrix;",
  15017. "uniform mat4 modelViewMatrix;",
  15018. "uniform mat4 projectionMatrix;",
  15019. "uniform mat4 viewMatrix;",
  15020. "uniform mat3 normalMatrix;",
  15021. "uniform vec3 cameraPosition;",
  15022. "attribute vec3 position;",
  15023. "attribute vec3 normal;",
  15024. "attribute vec2 uv;",
  15025. "attribute vec2 uv2;",
  15026. "#ifdef USE_COLOR",
  15027. "attribute vec3 color;",
  15028. "#endif",
  15029. "#ifdef USE_MORPHTARGETS",
  15030. "attribute vec3 morphTarget0;",
  15031. "attribute vec3 morphTarget1;",
  15032. "attribute vec3 morphTarget2;",
  15033. "attribute vec3 morphTarget3;",
  15034. "#ifdef USE_MORPHNORMALS",
  15035. "attribute vec3 morphNormal0;",
  15036. "attribute vec3 morphNormal1;",
  15037. "attribute vec3 morphNormal2;",
  15038. "attribute vec3 morphNormal3;",
  15039. "#else",
  15040. "attribute vec3 morphTarget4;",
  15041. "attribute vec3 morphTarget5;",
  15042. "attribute vec3 morphTarget6;",
  15043. "attribute vec3 morphTarget7;",
  15044. "#endif",
  15045. "#endif",
  15046. "#ifdef USE_SKINNING",
  15047. "attribute vec4 skinIndex;",
  15048. "attribute vec4 skinWeight;",
  15049. "#endif",
  15050. ""
  15051. ].join("\n");
  15052. var prefix_fragment = [
  15053. "precision " + _precision + " float;",
  15054. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15055. customDefines,
  15056. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15057. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15058. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15059. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15060. "#define MAX_SHADOWS " + parameters.maxShadows,
  15061. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15062. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15063. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15064. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  15065. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15066. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15067. parameters.map ? "#define USE_MAP" : "",
  15068. parameters.envMap ? "#define USE_ENVMAP" : "",
  15069. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15070. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15071. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15072. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15073. parameters.vertexColors ? "#define USE_COLOR" : "",
  15074. parameters.metal ? "#define METAL" : "",
  15075. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15076. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15077. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15078. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15079. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15080. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15081. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15082. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15083. "uniform mat4 viewMatrix;",
  15084. "uniform vec3 cameraPosition;",
  15085. ""
  15086. ].join("\n");
  15087. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  15088. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  15089. _gl.attachShader( program, glVertexShader );
  15090. _gl.attachShader( program, glFragmentShader );
  15091. _gl.linkProgram( program );
  15092. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  15093. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  15094. }
  15095. // clean up
  15096. _gl.deleteShader( glFragmentShader );
  15097. _gl.deleteShader( glVertexShader );
  15098. // console.log( prefix_fragment + fragmentShader );
  15099. // console.log( prefix_vertex + vertexShader );
  15100. program.uniforms = {};
  15101. program.attributes = {};
  15102. var identifiers, u, a, i;
  15103. // cache uniform locations
  15104. identifiers = [
  15105. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15106. 'morphTargetInfluences'
  15107. ];
  15108. if ( parameters.useVertexTexture ) {
  15109. identifiers.push( 'boneTexture' );
  15110. } else {
  15111. identifiers.push( 'boneGlobalMatrices' );
  15112. }
  15113. for ( u in uniforms ) {
  15114. identifiers.push( u );
  15115. }
  15116. cacheUniformLocations( program, identifiers );
  15117. // cache attributes locations
  15118. identifiers = [
  15119. "position", "normal", "uv", "uv2", "tangent", "color",
  15120. "skinIndex", "skinWeight", "lineDistance"
  15121. ];
  15122. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15123. identifiers.push( "morphTarget" + i );
  15124. }
  15125. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15126. identifiers.push( "morphNormal" + i );
  15127. }
  15128. for ( a in attributes ) {
  15129. identifiers.push( a );
  15130. }
  15131. cacheAttributeLocations( program, identifiers );
  15132. program.id = _programs_counter ++;
  15133. _programs.push( { program: program, code: code, usedTimes: 1 } );
  15134. _this.info.memory.programs = _programs.length;
  15135. return program;
  15136. };
  15137. // Shader parameters cache
  15138. function cacheUniformLocations ( program, identifiers ) {
  15139. var i, l, id;
  15140. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15141. id = identifiers[ i ];
  15142. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  15143. }
  15144. };
  15145. function cacheAttributeLocations ( program, identifiers ) {
  15146. var i, l, id;
  15147. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15148. id = identifiers[ i ];
  15149. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  15150. }
  15151. };
  15152. function addLineNumbers ( string ) {
  15153. var chunks = string.split( "\n" );
  15154. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  15155. // Chrome reports shader errors on lines
  15156. // starting counting from 1
  15157. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  15158. }
  15159. return chunks.join( "\n" );
  15160. };
  15161. function getShader ( type, string ) {
  15162. var shader;
  15163. if ( type === "fragment" ) {
  15164. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  15165. } else if ( type === "vertex" ) {
  15166. shader = _gl.createShader( _gl.VERTEX_SHADER );
  15167. }
  15168. _gl.shaderSource( shader, string );
  15169. _gl.compileShader( shader );
  15170. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  15171. console.error( _gl.getShaderInfoLog( shader ) );
  15172. console.error( addLineNumbers( string ) );
  15173. return null;
  15174. }
  15175. return shader;
  15176. };
  15177. // Textures
  15178. function isPowerOfTwo ( value ) {
  15179. return ( value & ( value - 1 ) ) === 0;
  15180. };
  15181. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15182. if ( isImagePowerOfTwo ) {
  15183. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15184. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15185. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15186. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15187. } else {
  15188. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15189. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15190. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15191. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15192. }
  15193. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15194. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15195. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15196. texture.__oldAnisotropy = texture.anisotropy;
  15197. }
  15198. }
  15199. };
  15200. this.setTexture = function ( texture, slot ) {
  15201. if ( texture.needsUpdate ) {
  15202. if ( ! texture.__webglInit ) {
  15203. texture.__webglInit = true;
  15204. texture.addEventListener( 'dispose', onTextureDispose );
  15205. texture.__webglTexture = _gl.createTexture();
  15206. _this.info.memory.textures ++;
  15207. }
  15208. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15209. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15210. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15211. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15212. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15213. var image = texture.image,
  15214. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15215. glFormat = paramThreeToGL( texture.format ),
  15216. glType = paramThreeToGL( texture.type );
  15217. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15218. var mipmap, mipmaps = texture.mipmaps;
  15219. if ( texture instanceof THREE.DataTexture ) {
  15220. // use manually created mipmaps if available
  15221. // if there are no manual mipmaps
  15222. // set 0 level mipmap and then use GL to generate other mipmap levels
  15223. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15224. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15225. mipmap = mipmaps[ i ];
  15226. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15227. }
  15228. texture.generateMipmaps = false;
  15229. } else {
  15230. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15231. }
  15232. } else if ( texture instanceof THREE.CompressedTexture ) {
  15233. // compressed textures can only use manually created mipmaps
  15234. // WebGL can't generate mipmaps for DDS textures
  15235. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15236. mipmap = mipmaps[ i ];
  15237. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15238. }
  15239. } else { // regular Texture (image, video, canvas)
  15240. // use manually created mipmaps if available
  15241. // if there are no manual mipmaps
  15242. // set 0 level mipmap and then use GL to generate other mipmap levels
  15243. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15244. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15245. mipmap = mipmaps[ i ];
  15246. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15247. }
  15248. texture.generateMipmaps = false;
  15249. } else {
  15250. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15251. }
  15252. }
  15253. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15254. texture.needsUpdate = false;
  15255. if ( texture.onUpdate ) texture.onUpdate();
  15256. } else {
  15257. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15258. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15259. }
  15260. };
  15261. function clampToMaxSize ( image, maxSize ) {
  15262. if ( image.width <= maxSize && image.height <= maxSize ) {
  15263. return image;
  15264. }
  15265. // Warning: Scaling through the canvas will only work with images that use
  15266. // premultiplied alpha.
  15267. var maxDimension = Math.max( image.width, image.height );
  15268. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15269. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15270. var canvas = document.createElement( 'canvas' );
  15271. canvas.width = newWidth;
  15272. canvas.height = newHeight;
  15273. var ctx = canvas.getContext( "2d" );
  15274. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15275. return canvas;
  15276. }
  15277. function setCubeTexture ( texture, slot ) {
  15278. if ( texture.image.length === 6 ) {
  15279. if ( texture.needsUpdate ) {
  15280. if ( ! texture.image.__webglTextureCube ) {
  15281. texture.image.__webglTextureCube = _gl.createTexture();
  15282. _this.info.memory.textures ++;
  15283. }
  15284. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15285. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15286. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15287. var isCompressed = texture instanceof THREE.CompressedTexture;
  15288. var cubeImage = [];
  15289. for ( var i = 0; i < 6; i ++ ) {
  15290. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15291. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15292. } else {
  15293. cubeImage[ i ] = texture.image[ i ];
  15294. }
  15295. }
  15296. var image = cubeImage[ 0 ],
  15297. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15298. glFormat = paramThreeToGL( texture.format ),
  15299. glType = paramThreeToGL( texture.type );
  15300. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15301. for ( var i = 0; i < 6; i ++ ) {
  15302. if ( isCompressed ) {
  15303. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15304. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15305. mipmap = mipmaps[ j ];
  15306. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15307. }
  15308. } else {
  15309. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15310. }
  15311. }
  15312. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15313. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15314. }
  15315. texture.needsUpdate = false;
  15316. if ( texture.onUpdate ) texture.onUpdate();
  15317. } else {
  15318. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15319. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15320. }
  15321. }
  15322. };
  15323. function setCubeTextureDynamic ( texture, slot ) {
  15324. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15325. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15326. };
  15327. // Render targets
  15328. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15329. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15330. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15331. };
  15332. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15333. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15334. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15335. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15336. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15337. /* For some reason this is not working. Defaulting to RGBA4.
  15338. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15339. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15340. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15341. */
  15342. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15343. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15344. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15345. } else {
  15346. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15347. }
  15348. };
  15349. this.setRenderTarget = function ( renderTarget ) {
  15350. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15351. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15352. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15353. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15354. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15355. renderTarget.__webglTexture = _gl.createTexture();
  15356. _this.info.memory.textures ++;
  15357. // Setup texture, create render and frame buffers
  15358. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15359. glFormat = paramThreeToGL( renderTarget.format ),
  15360. glType = paramThreeToGL( renderTarget.type );
  15361. if ( isCube ) {
  15362. renderTarget.__webglFramebuffer = [];
  15363. renderTarget.__webglRenderbuffer = [];
  15364. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15365. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15366. for ( var i = 0; i < 6; i ++ ) {
  15367. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15368. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15369. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15370. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15371. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15372. }
  15373. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15374. } else {
  15375. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15376. if ( renderTarget.shareDepthFrom ) {
  15377. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15378. } else {
  15379. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15380. }
  15381. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15382. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15383. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15384. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15385. if ( renderTarget.shareDepthFrom ) {
  15386. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15387. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15388. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15389. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15390. }
  15391. } else {
  15392. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15393. }
  15394. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15395. }
  15396. // Release everything
  15397. if ( isCube ) {
  15398. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15399. } else {
  15400. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15401. }
  15402. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15403. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15404. }
  15405. var framebuffer, width, height, vx, vy;
  15406. if ( renderTarget ) {
  15407. if ( isCube ) {
  15408. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15409. } else {
  15410. framebuffer = renderTarget.__webglFramebuffer;
  15411. }
  15412. width = renderTarget.width;
  15413. height = renderTarget.height;
  15414. vx = 0;
  15415. vy = 0;
  15416. } else {
  15417. framebuffer = null;
  15418. width = _viewportWidth;
  15419. height = _viewportHeight;
  15420. vx = _viewportX;
  15421. vy = _viewportY;
  15422. }
  15423. if ( framebuffer !== _currentFramebuffer ) {
  15424. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15425. _gl.viewport( vx, vy, width, height );
  15426. _currentFramebuffer = framebuffer;
  15427. }
  15428. _currentWidth = width;
  15429. _currentHeight = height;
  15430. };
  15431. function updateRenderTargetMipmap ( renderTarget ) {
  15432. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15433. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15434. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15435. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15436. } else {
  15437. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15438. _gl.generateMipmap( _gl.TEXTURE_2D );
  15439. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15440. }
  15441. };
  15442. // Fallback filters for non-power-of-2 textures
  15443. function filterFallback ( f ) {
  15444. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15445. return _gl.NEAREST;
  15446. }
  15447. return _gl.LINEAR;
  15448. };
  15449. // Map three.js constants to WebGL constants
  15450. function paramThreeToGL ( p ) {
  15451. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15452. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15453. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15454. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15455. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15456. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15457. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15458. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15459. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15460. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15461. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15462. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15463. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15464. if ( p === THREE.ByteType ) return _gl.BYTE;
  15465. if ( p === THREE.ShortType ) return _gl.SHORT;
  15466. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15467. if ( p === THREE.IntType ) return _gl.INT;
  15468. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15469. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15470. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15471. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15472. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15473. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15474. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15475. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15476. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15477. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15478. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15479. if ( p === THREE.OneFactor ) return _gl.ONE;
  15480. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15481. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15482. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15483. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15484. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15485. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15486. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15487. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15488. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15489. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15490. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15491. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15492. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15493. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15494. }
  15495. return 0;
  15496. };
  15497. // Allocations
  15498. function allocateBones ( object ) {
  15499. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15500. return 1024;
  15501. } else {
  15502. // default for when object is not specified
  15503. // ( for example when prebuilding shader
  15504. // to be used with multiple objects )
  15505. //
  15506. // - leave some extra space for other uniforms
  15507. // - limit here is ANGLE's 254 max uniform vectors
  15508. // (up to 54 should be safe)
  15509. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15510. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15511. var maxBones = nVertexMatrices;
  15512. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15513. maxBones = Math.min( object.bones.length, maxBones );
  15514. if ( maxBones < object.bones.length ) {
  15515. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15516. }
  15517. }
  15518. return maxBones;
  15519. }
  15520. };
  15521. function allocateLights( lights ) {
  15522. var dirLights = 0;
  15523. var pointLights = 0;
  15524. var spotLights = 0;
  15525. var hemiLights = 0;
  15526. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15527. var light = lights[ l ];
  15528. if ( light.onlyShadow ) continue;
  15529. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15530. if ( light instanceof THREE.PointLight ) pointLights ++;
  15531. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15532. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15533. }
  15534. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15535. };
  15536. function allocateShadows( lights ) {
  15537. var maxShadows = 0;
  15538. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15539. var light = lights[ l ];
  15540. if ( ! light.castShadow ) continue;
  15541. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15542. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15543. }
  15544. return maxShadows;
  15545. };
  15546. // Initialization
  15547. function initGL() {
  15548. try {
  15549. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15550. throw 'Error creating WebGL context.';
  15551. }
  15552. } catch ( error ) {
  15553. console.error( error );
  15554. }
  15555. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15556. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15557. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15558. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15559. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15560. if ( ! _glExtensionTextureFloat ) {
  15561. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15562. }
  15563. if ( ! _glExtensionStandardDerivatives ) {
  15564. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15565. }
  15566. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15567. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15568. }
  15569. if ( ! _glExtensionCompressedTextureS3TC ) {
  15570. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15571. }
  15572. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15573. _gl.getShaderPrecisionFormat = function() {
  15574. return {
  15575. "rangeMin" : 1,
  15576. "rangeMax" : 1,
  15577. "precision" : 1
  15578. };
  15579. }
  15580. }
  15581. };
  15582. function setDefaultGLState () {
  15583. _gl.clearColor( 0, 0, 0, 1 );
  15584. _gl.clearDepth( 1 );
  15585. _gl.clearStencil( 0 );
  15586. _gl.enable( _gl.DEPTH_TEST );
  15587. _gl.depthFunc( _gl.LEQUAL );
  15588. _gl.frontFace( _gl.CCW );
  15589. _gl.cullFace( _gl.BACK );
  15590. _gl.enable( _gl.CULL_FACE );
  15591. _gl.enable( _gl.BLEND );
  15592. _gl.blendEquation( _gl.FUNC_ADD );
  15593. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15594. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15595. };
  15596. // default plugins (order is important)
  15597. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15598. this.addPrePlugin( this.shadowMapPlugin );
  15599. this.addPostPlugin( new THREE.SpritePlugin() );
  15600. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15601. };
  15602. /**
  15603. * @author szimek / https://github.com/szimek/
  15604. * @author alteredq / http://alteredqualia.com/
  15605. */
  15606. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15607. this.width = width;
  15608. this.height = height;
  15609. options = options || {};
  15610. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15611. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15612. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15613. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15614. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15615. this.offset = new THREE.Vector2( 0, 0 );
  15616. this.repeat = new THREE.Vector2( 1, 1 );
  15617. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15618. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15619. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15620. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15621. this.generateMipmaps = true;
  15622. this.shareDepthFrom = null;
  15623. };
  15624. THREE.WebGLRenderTarget.prototype = {
  15625. constructor: THREE.WebGLRenderTarget,
  15626. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  15627. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  15628. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  15629. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  15630. clone: function () {
  15631. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15632. tmp.wrapS = this.wrapS;
  15633. tmp.wrapT = this.wrapT;
  15634. tmp.magFilter = this.magFilter;
  15635. tmp.minFilter = this.minFilter;
  15636. tmp.anisotropy = this.anisotropy;
  15637. tmp.offset.copy( this.offset );
  15638. tmp.repeat.copy( this.repeat );
  15639. tmp.format = this.format;
  15640. tmp.type = this.type;
  15641. tmp.depthBuffer = this.depthBuffer;
  15642. tmp.stencilBuffer = this.stencilBuffer;
  15643. tmp.generateMipmaps = this.generateMipmaps;
  15644. tmp.shareDepthFrom = this.shareDepthFrom;
  15645. return tmp;
  15646. },
  15647. dispose: function () {
  15648. this.dispatchEvent( { type: 'dispose' } );
  15649. }
  15650. };
  15651. /**
  15652. * @author alteredq / http://alteredqualia.com
  15653. */
  15654. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15655. THREE.WebGLRenderTarget.call( this, width, height, options );
  15656. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15657. };
  15658. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15659. /**
  15660. * @author mrdoob / http://mrdoob.com/
  15661. */
  15662. THREE.RenderableVertex = function () {
  15663. this.positionWorld = new THREE.Vector3();
  15664. this.positionScreen = new THREE.Vector4();
  15665. this.visible = true;
  15666. };
  15667. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15668. this.positionWorld.copy( vertex.positionWorld );
  15669. this.positionScreen.copy( vertex.positionScreen );
  15670. };
  15671. /**
  15672. * @author mrdoob / http://mrdoob.com/
  15673. */
  15674. THREE.RenderableFace3 = function () {
  15675. this.v1 = new THREE.RenderableVertex();
  15676. this.v2 = new THREE.RenderableVertex();
  15677. this.v3 = new THREE.RenderableVertex();
  15678. this.centroidModel = new THREE.Vector3();
  15679. this.normalModel = new THREE.Vector3();
  15680. this.normalModelView = new THREE.Vector3();
  15681. this.vertexNormalsLength = 0;
  15682. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15683. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15684. this.color = null;
  15685. this.material = null;
  15686. this.uvs = [[]];
  15687. this.z = null;
  15688. };
  15689. /**
  15690. * @author mrdoob / http://mrdoob.com/
  15691. */
  15692. THREE.RenderableFace4 = function () {
  15693. this.v1 = new THREE.RenderableVertex();
  15694. this.v2 = new THREE.RenderableVertex();
  15695. this.v3 = new THREE.RenderableVertex();
  15696. this.v4 = new THREE.RenderableVertex();
  15697. this.centroidModel = new THREE.Vector3();
  15698. this.normalModel = new THREE.Vector3();
  15699. this.normalModelView = new THREE.Vector3();
  15700. this.vertexNormalsLength = 0;
  15701. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15702. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15703. this.color = null;
  15704. this.material = null;
  15705. this.uvs = [[]];
  15706. this.z = null;
  15707. };
  15708. /**
  15709. * @author mrdoob / http://mrdoob.com/
  15710. */
  15711. THREE.RenderableObject = function () {
  15712. this.object = null;
  15713. this.z = null;
  15714. };
  15715. /**
  15716. * @author mrdoob / http://mrdoob.com/
  15717. */
  15718. THREE.RenderableParticle = function () {
  15719. this.object = null;
  15720. this.x = null;
  15721. this.y = null;
  15722. this.z = null;
  15723. this.rotation = null;
  15724. this.scale = new THREE.Vector2();
  15725. this.material = null;
  15726. };
  15727. /**
  15728. * @author mrdoob / http://mrdoob.com/
  15729. */
  15730. THREE.RenderableLine = function () {
  15731. this.z = null;
  15732. this.v1 = new THREE.RenderableVertex();
  15733. this.v2 = new THREE.RenderableVertex();
  15734. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15735. this.material = null;
  15736. };
  15737. /**
  15738. * @author mrdoob / http://mrdoob.com/
  15739. * @author alteredq / http://alteredqualia.com/
  15740. */
  15741. THREE.GeometryUtils = {
  15742. // Merge two geometries or geometry and geometry from object (using object's transform)
  15743. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15744. var matrix, normalMatrix,
  15745. vertexOffset = geometry1.vertices.length,
  15746. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15747. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15748. vertices1 = geometry1.vertices,
  15749. vertices2 = geometry2.vertices,
  15750. faces1 = geometry1.faces,
  15751. faces2 = geometry2.faces,
  15752. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15753. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15754. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15755. if ( object2 instanceof THREE.Mesh ) {
  15756. object2.matrixAutoUpdate && object2.updateMatrix();
  15757. matrix = object2.matrix;
  15758. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15759. }
  15760. // vertices
  15761. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15762. var vertex = vertices2[ i ];
  15763. var vertexCopy = vertex.clone();
  15764. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15765. vertices1.push( vertexCopy );
  15766. }
  15767. // faces
  15768. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15769. var face = faces2[ i ], faceCopy, normal, color,
  15770. faceVertexNormals = face.vertexNormals,
  15771. faceVertexColors = face.vertexColors;
  15772. if ( face instanceof THREE.Face3 ) {
  15773. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15774. } else if ( face instanceof THREE.Face4 ) {
  15775. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15776. }
  15777. faceCopy.normal.copy( face.normal );
  15778. if ( normalMatrix ) {
  15779. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15780. }
  15781. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15782. normal = faceVertexNormals[ j ].clone();
  15783. if ( normalMatrix ) {
  15784. normal.applyMatrix3( normalMatrix ).normalize();
  15785. }
  15786. faceCopy.vertexNormals.push( normal );
  15787. }
  15788. faceCopy.color.copy( face.color );
  15789. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15790. color = faceVertexColors[ j ];
  15791. faceCopy.vertexColors.push( color.clone() );
  15792. }
  15793. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15794. faceCopy.centroid.copy( face.centroid );
  15795. if ( matrix ) {
  15796. faceCopy.centroid.applyMatrix4( matrix );
  15797. }
  15798. faces1.push( faceCopy );
  15799. }
  15800. // uvs
  15801. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15802. var uv = uvs2[ i ], uvCopy = [];
  15803. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15804. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15805. }
  15806. uvs1.push( uvCopy );
  15807. }
  15808. },
  15809. removeMaterials: function ( geometry, materialIndexArray ) {
  15810. var materialIndexMap = {};
  15811. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15812. materialIndexMap[ materialIndexArray[i] ] = true;
  15813. }
  15814. var face, newFaces = [];
  15815. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15816. face = geometry.faces[ i ];
  15817. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15818. }
  15819. geometry.faces = newFaces;
  15820. },
  15821. // Get random point in triangle (via barycentric coordinates)
  15822. // (uniform distribution)
  15823. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15824. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15825. var a, b, c,
  15826. point = new THREE.Vector3(),
  15827. tmp = THREE.GeometryUtils.__v1;
  15828. a = THREE.GeometryUtils.random();
  15829. b = THREE.GeometryUtils.random();
  15830. if ( ( a + b ) > 1 ) {
  15831. a = 1 - a;
  15832. b = 1 - b;
  15833. }
  15834. c = 1 - a - b;
  15835. point.copy( vectorA );
  15836. point.multiplyScalar( a );
  15837. tmp.copy( vectorB );
  15838. tmp.multiplyScalar( b );
  15839. point.add( tmp );
  15840. tmp.copy( vectorC );
  15841. tmp.multiplyScalar( c );
  15842. point.add( tmp );
  15843. return point;
  15844. },
  15845. // Get random point in face (triangle / quad)
  15846. // (uniform distribution)
  15847. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15848. var vA, vB, vC, vD;
  15849. if ( face instanceof THREE.Face3 ) {
  15850. vA = geometry.vertices[ face.a ];
  15851. vB = geometry.vertices[ face.b ];
  15852. vC = geometry.vertices[ face.c ];
  15853. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15854. } else if ( face instanceof THREE.Face4 ) {
  15855. vA = geometry.vertices[ face.a ];
  15856. vB = geometry.vertices[ face.b ];
  15857. vC = geometry.vertices[ face.c ];
  15858. vD = geometry.vertices[ face.d ];
  15859. var area1, area2;
  15860. if ( useCachedAreas ) {
  15861. if ( face._area1 && face._area2 ) {
  15862. area1 = face._area1;
  15863. area2 = face._area2;
  15864. } else {
  15865. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15866. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15867. face._area1 = area1;
  15868. face._area2 = area2;
  15869. }
  15870. } else {
  15871. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15872. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15873. }
  15874. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15875. if ( r < area1 ) {
  15876. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15877. } else {
  15878. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15879. }
  15880. }
  15881. },
  15882. // Get uniformly distributed random points in mesh
  15883. // - create array with cumulative sums of face areas
  15884. // - pick random number from 0 to total area
  15885. // - find corresponding place in area array by binary search
  15886. // - get random point in face
  15887. randomPointsInGeometry: function ( geometry, n ) {
  15888. var face, i,
  15889. faces = geometry.faces,
  15890. vertices = geometry.vertices,
  15891. il = faces.length,
  15892. totalArea = 0,
  15893. cumulativeAreas = [],
  15894. vA, vB, vC, vD;
  15895. // precompute face areas
  15896. for ( i = 0; i < il; i ++ ) {
  15897. face = faces[ i ];
  15898. if ( face instanceof THREE.Face3 ) {
  15899. vA = vertices[ face.a ];
  15900. vB = vertices[ face.b ];
  15901. vC = vertices[ face.c ];
  15902. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15903. } else if ( face instanceof THREE.Face4 ) {
  15904. vA = vertices[ face.a ];
  15905. vB = vertices[ face.b ];
  15906. vC = vertices[ face.c ];
  15907. vD = vertices[ face.d ];
  15908. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15909. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15910. face._area = face._area1 + face._area2;
  15911. }
  15912. totalArea += face._area;
  15913. cumulativeAreas[ i ] = totalArea;
  15914. }
  15915. // binary search cumulative areas array
  15916. function binarySearchIndices( value ) {
  15917. function binarySearch( start, end ) {
  15918. // return closest larger index
  15919. // if exact number is not found
  15920. if ( end < start )
  15921. return start;
  15922. var mid = start + Math.floor( ( end - start ) / 2 );
  15923. if ( cumulativeAreas[ mid ] > value ) {
  15924. return binarySearch( start, mid - 1 );
  15925. } else if ( cumulativeAreas[ mid ] < value ) {
  15926. return binarySearch( mid + 1, end );
  15927. } else {
  15928. return mid;
  15929. }
  15930. }
  15931. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15932. return result;
  15933. }
  15934. // pick random face weighted by face area
  15935. var r, index,
  15936. result = [];
  15937. var stats = {};
  15938. for ( i = 0; i < n; i ++ ) {
  15939. r = THREE.GeometryUtils.random() * totalArea;
  15940. index = binarySearchIndices( r );
  15941. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15942. if ( ! stats[ index ] ) {
  15943. stats[ index ] = 1;
  15944. } else {
  15945. stats[ index ] += 1;
  15946. }
  15947. }
  15948. return result;
  15949. },
  15950. // Get triangle area (half of parallelogram)
  15951. // http://mathworld.wolfram.com/TriangleArea.html
  15952. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15953. var tmp1 = THREE.GeometryUtils.__v1,
  15954. tmp2 = THREE.GeometryUtils.__v2;
  15955. tmp1.subVectors( vectorB, vectorA );
  15956. tmp2.subVectors( vectorC, vectorA );
  15957. tmp1.cross( tmp2 );
  15958. return 0.5 * tmp1.length();
  15959. },
  15960. // Center geometry so that 0,0,0 is in center of bounding box
  15961. center: function ( geometry ) {
  15962. geometry.computeBoundingBox();
  15963. var bb = geometry.boundingBox;
  15964. var offset = new THREE.Vector3();
  15965. offset.addVectors( bb.min, bb.max );
  15966. offset.multiplyScalar( -0.5 );
  15967. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15968. geometry.computeBoundingBox();
  15969. return offset;
  15970. },
  15971. // Normalize UVs to be from <0,1>
  15972. // (for now just the first set of UVs)
  15973. normalizeUVs: function ( geometry ) {
  15974. var uvSet = geometry.faceVertexUvs[ 0 ];
  15975. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15976. var uvs = uvSet[ i ];
  15977. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15978. // texture repeat
  15979. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15980. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15981. }
  15982. }
  15983. },
  15984. triangulateQuads: function ( geometry ) {
  15985. var i, il, j, jl;
  15986. var faces = [];
  15987. var faceUvs = [];
  15988. var faceVertexUvs = [];
  15989. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15990. faceUvs[ i ] = [];
  15991. }
  15992. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15993. faceVertexUvs[ i ] = [];
  15994. }
  15995. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15996. var face = geometry.faces[ i ];
  15997. if ( face instanceof THREE.Face4 ) {
  15998. var a = face.a;
  15999. var b = face.b;
  16000. var c = face.c;
  16001. var d = face.d;
  16002. var triA = new THREE.Face3();
  16003. var triB = new THREE.Face3();
  16004. triA.color.copy( face.color );
  16005. triB.color.copy( face.color );
  16006. triA.materialIndex = face.materialIndex;
  16007. triB.materialIndex = face.materialIndex;
  16008. triA.a = a;
  16009. triA.b = b;
  16010. triA.c = d;
  16011. triB.a = b;
  16012. triB.b = c;
  16013. triB.c = d;
  16014. if ( face.vertexColors.length === 4 ) {
  16015. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  16016. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  16017. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16018. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  16019. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  16020. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16021. }
  16022. faces.push( triA, triB );
  16023. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16024. if ( geometry.faceVertexUvs[ j ].length ) {
  16025. var uvs = geometry.faceVertexUvs[ j ][ i ];
  16026. var uvA = uvs[ 0 ];
  16027. var uvB = uvs[ 1 ];
  16028. var uvC = uvs[ 2 ];
  16029. var uvD = uvs[ 3 ];
  16030. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  16031. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  16032. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  16033. }
  16034. }
  16035. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16036. if ( geometry.faceUvs[ j ].length ) {
  16037. var faceUv = geometry.faceUvs[ j ][ i ];
  16038. faceUvs[ j ].push( faceUv, faceUv );
  16039. }
  16040. }
  16041. } else {
  16042. faces.push( face );
  16043. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16044. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  16045. }
  16046. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16047. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  16048. }
  16049. }
  16050. }
  16051. geometry.faces = faces;
  16052. geometry.faceUvs = faceUvs;
  16053. geometry.faceVertexUvs = faceVertexUvs;
  16054. geometry.computeCentroids();
  16055. geometry.computeFaceNormals();
  16056. geometry.computeVertexNormals();
  16057. if ( geometry.hasTangents ) geometry.computeTangents();
  16058. },
  16059. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  16060. var faces = geometry.faces;
  16061. var start = startFace || 0;
  16062. var end = endFace || faces.length - 1;
  16063. for ( var i = start; i <= end; i ++ ) {
  16064. faces[i].materialIndex = index;
  16065. }
  16066. }
  16067. };
  16068. THREE.GeometryUtils.random = THREE.Math.random16;
  16069. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  16070. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  16071. /**
  16072. * @author alteredq / http://alteredqualia.com/
  16073. * @author mrdoob / http://mrdoob.com/
  16074. */
  16075. THREE.ImageUtils = {
  16076. crossOrigin: 'anonymous',
  16077. loadTexture: function ( url, mapping, onLoad, onError ) {
  16078. var image = new Image();
  16079. var texture = new THREE.Texture( image, mapping );
  16080. var loader = new THREE.ImageLoader();
  16081. loader.crossOrigin = this.crossOrigin;
  16082. loader.load( url, function ( image ) {
  16083. texture.image = image;
  16084. texture.needsUpdate = true;
  16085. if ( onLoad ) onLoad( texture );
  16086. } );
  16087. texture.sourceFile = url;
  16088. return texture;
  16089. },
  16090. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16091. var texture = new THREE.CompressedTexture();
  16092. texture.mapping = mapping;
  16093. var request = new XMLHttpRequest();
  16094. request.onload = function () {
  16095. var buffer = request.response;
  16096. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16097. texture.format = dds.format;
  16098. texture.mipmaps = dds.mipmaps;
  16099. texture.image.width = dds.width;
  16100. texture.image.height = dds.height;
  16101. // gl.generateMipmap fails for compressed textures
  16102. // mipmaps must be embedded in the DDS file
  16103. // or texture filters must not use mipmapping
  16104. texture.generateMipmaps = false;
  16105. texture.needsUpdate = true;
  16106. if ( onLoad ) onLoad( texture );
  16107. }
  16108. request.onerror = onError;
  16109. request.open( 'GET', url, true );
  16110. request.responseType = "arraybuffer";
  16111. request.send( null );
  16112. return texture;
  16113. },
  16114. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16115. var images = [];
  16116. images.loadCount = 0;
  16117. var texture = new THREE.Texture();
  16118. texture.image = images;
  16119. if ( mapping !== undefined ) texture.mapping = mapping;
  16120. // no flipping needed for cube textures
  16121. texture.flipY = false;
  16122. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16123. var cubeImage = new Image();
  16124. images[ i ] = cubeImage;
  16125. cubeImage.onload = function () {
  16126. images.loadCount += 1;
  16127. if ( images.loadCount === 6 ) {
  16128. texture.needsUpdate = true;
  16129. if ( onLoad ) onLoad( texture );
  16130. }
  16131. };
  16132. cubeImage.onerror = onError;
  16133. cubeImage.crossOrigin = this.crossOrigin;
  16134. cubeImage.src = array[ i ];
  16135. }
  16136. return texture;
  16137. },
  16138. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16139. var images = [];
  16140. images.loadCount = 0;
  16141. var texture = new THREE.CompressedTexture();
  16142. texture.image = images;
  16143. if ( mapping !== undefined ) texture.mapping = mapping;
  16144. // no flipping for cube textures
  16145. // (also flipping doesn't work for compressed textures )
  16146. texture.flipY = false;
  16147. // can't generate mipmaps for compressed textures
  16148. // mips must be embedded in DDS files
  16149. texture.generateMipmaps = false;
  16150. var generateCubeFaceCallback = function ( rq, img ) {
  16151. return function () {
  16152. var buffer = rq.response;
  16153. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16154. img.format = dds.format;
  16155. img.mipmaps = dds.mipmaps;
  16156. img.width = dds.width;
  16157. img.height = dds.height;
  16158. images.loadCount += 1;
  16159. if ( images.loadCount === 6 ) {
  16160. texture.format = dds.format;
  16161. texture.needsUpdate = true;
  16162. if ( onLoad ) onLoad( texture );
  16163. }
  16164. }
  16165. }
  16166. // compressed cubemap textures as 6 separate DDS files
  16167. if ( array instanceof Array ) {
  16168. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16169. var cubeImage = {};
  16170. images[ i ] = cubeImage;
  16171. var request = new XMLHttpRequest();
  16172. request.onload = generateCubeFaceCallback( request, cubeImage );
  16173. request.onerror = onError;
  16174. var url = array[ i ];
  16175. request.open( 'GET', url, true );
  16176. request.responseType = "arraybuffer";
  16177. request.send( null );
  16178. }
  16179. // compressed cubemap texture stored in a single DDS file
  16180. } else {
  16181. var url = array;
  16182. var request = new XMLHttpRequest();
  16183. request.onload = function( ) {
  16184. var buffer = request.response;
  16185. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16186. if ( dds.isCubemap ) {
  16187. var faces = dds.mipmaps.length / dds.mipmapCount;
  16188. for ( var f = 0; f < faces; f ++ ) {
  16189. images[ f ] = { mipmaps : [] };
  16190. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16191. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16192. images[ f ].format = dds.format;
  16193. images[ f ].width = dds.width;
  16194. images[ f ].height = dds.height;
  16195. }
  16196. }
  16197. texture.format = dds.format;
  16198. texture.needsUpdate = true;
  16199. if ( onLoad ) onLoad( texture );
  16200. }
  16201. }
  16202. request.onerror = onError;
  16203. request.open( 'GET', url, true );
  16204. request.responseType = "arraybuffer";
  16205. request.send( null );
  16206. }
  16207. return texture;
  16208. },
  16209. parseDDS: function ( buffer, loadMipmaps ) {
  16210. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16211. // Adapted from @toji's DDS utils
  16212. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16213. // All values and structures referenced from:
  16214. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16215. var DDS_MAGIC = 0x20534444;
  16216. var DDSD_CAPS = 0x1,
  16217. DDSD_HEIGHT = 0x2,
  16218. DDSD_WIDTH = 0x4,
  16219. DDSD_PITCH = 0x8,
  16220. DDSD_PIXELFORMAT = 0x1000,
  16221. DDSD_MIPMAPCOUNT = 0x20000,
  16222. DDSD_LINEARSIZE = 0x80000,
  16223. DDSD_DEPTH = 0x800000;
  16224. var DDSCAPS_COMPLEX = 0x8,
  16225. DDSCAPS_MIPMAP = 0x400000,
  16226. DDSCAPS_TEXTURE = 0x1000;
  16227. var DDSCAPS2_CUBEMAP = 0x200,
  16228. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16229. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16230. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16231. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16232. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16233. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16234. DDSCAPS2_VOLUME = 0x200000;
  16235. var DDPF_ALPHAPIXELS = 0x1,
  16236. DDPF_ALPHA = 0x2,
  16237. DDPF_FOURCC = 0x4,
  16238. DDPF_RGB = 0x40,
  16239. DDPF_YUV = 0x200,
  16240. DDPF_LUMINANCE = 0x20000;
  16241. function fourCCToInt32( value ) {
  16242. return value.charCodeAt(0) +
  16243. (value.charCodeAt(1) << 8) +
  16244. (value.charCodeAt(2) << 16) +
  16245. (value.charCodeAt(3) << 24);
  16246. }
  16247. function int32ToFourCC( value ) {
  16248. return String.fromCharCode(
  16249. value & 0xff,
  16250. (value >> 8) & 0xff,
  16251. (value >> 16) & 0xff,
  16252. (value >> 24) & 0xff
  16253. );
  16254. }
  16255. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16256. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16257. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16258. var headerLengthInt = 31; // The header length in 32 bit ints
  16259. // Offsets into the header array
  16260. var off_magic = 0;
  16261. var off_size = 1;
  16262. var off_flags = 2;
  16263. var off_height = 3;
  16264. var off_width = 4;
  16265. var off_mipmapCount = 7;
  16266. var off_pfFlags = 20;
  16267. var off_pfFourCC = 21;
  16268. var off_caps = 27;
  16269. var off_caps2 = 28;
  16270. var off_caps3 = 29;
  16271. var off_caps4 = 30;
  16272. // Parse header
  16273. var header = new Int32Array( buffer, 0, headerLengthInt );
  16274. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16275. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16276. return dds;
  16277. }
  16278. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16279. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16280. return dds;
  16281. }
  16282. var blockBytes;
  16283. var fourCC = header[ off_pfFourCC ];
  16284. switch ( fourCC ) {
  16285. case FOURCC_DXT1:
  16286. blockBytes = 8;
  16287. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16288. break;
  16289. case FOURCC_DXT3:
  16290. blockBytes = 16;
  16291. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16292. break;
  16293. case FOURCC_DXT5:
  16294. blockBytes = 16;
  16295. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16296. break;
  16297. default:
  16298. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16299. return dds;
  16300. }
  16301. dds.mipmapCount = 1;
  16302. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16303. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16304. }
  16305. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16306. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16307. dds.width = header[ off_width ];
  16308. dds.height = header[ off_height ];
  16309. var dataOffset = header[ off_size ] + 4;
  16310. // Extract mipmaps buffers
  16311. var width = dds.width;
  16312. var height = dds.height;
  16313. var faces = dds.isCubemap ? 6 : 1;
  16314. for ( var face = 0; face < faces; face ++ ) {
  16315. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16316. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16317. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16318. var mipmap = { "data": byteArray, "width": width, "height": height };
  16319. dds.mipmaps.push( mipmap );
  16320. dataOffset += dataLength;
  16321. width = Math.max( width * 0.5, 1 );
  16322. height = Math.max( height * 0.5, 1 );
  16323. }
  16324. width = dds.width;
  16325. height = dds.height;
  16326. }
  16327. return dds;
  16328. },
  16329. getNormalMap: function ( image, depth ) {
  16330. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16331. var cross = function ( a, b ) {
  16332. 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 ] ];
  16333. }
  16334. var subtract = function ( a, b ) {
  16335. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16336. }
  16337. var normalize = function ( a ) {
  16338. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16339. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16340. }
  16341. depth = depth | 1;
  16342. var width = image.width;
  16343. var height = image.height;
  16344. var canvas = document.createElement( 'canvas' );
  16345. canvas.width = width;
  16346. canvas.height = height;
  16347. var context = canvas.getContext( '2d' );
  16348. context.drawImage( image, 0, 0 );
  16349. var data = context.getImageData( 0, 0, width, height ).data;
  16350. var imageData = context.createImageData( width, height );
  16351. var output = imageData.data;
  16352. for ( var x = 0; x < width; x ++ ) {
  16353. for ( var y = 0; y < height; y ++ ) {
  16354. var ly = y - 1 < 0 ? 0 : y - 1;
  16355. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16356. var lx = x - 1 < 0 ? 0 : x - 1;
  16357. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16358. var points = [];
  16359. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16360. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16361. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16362. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16363. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16364. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16365. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16366. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16367. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16368. var normals = [];
  16369. var num_points = points.length;
  16370. for ( var i = 0; i < num_points; i ++ ) {
  16371. var v1 = points[ i ];
  16372. var v2 = points[ ( i + 1 ) % num_points ];
  16373. v1 = subtract( v1, origin );
  16374. v2 = subtract( v2, origin );
  16375. normals.push( normalize( cross( v1, v2 ) ) );
  16376. }
  16377. var normal = [ 0, 0, 0 ];
  16378. for ( var i = 0; i < normals.length; i ++ ) {
  16379. normal[ 0 ] += normals[ i ][ 0 ];
  16380. normal[ 1 ] += normals[ i ][ 1 ];
  16381. normal[ 2 ] += normals[ i ][ 2 ];
  16382. }
  16383. normal[ 0 ] /= normals.length;
  16384. normal[ 1 ] /= normals.length;
  16385. normal[ 2 ] /= normals.length;
  16386. var idx = ( y * width + x ) * 4;
  16387. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16388. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16389. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16390. output[ idx + 3 ] = 255;
  16391. }
  16392. }
  16393. context.putImageData( imageData, 0, 0 );
  16394. return canvas;
  16395. },
  16396. generateDataTexture: function ( width, height, color ) {
  16397. var size = width * height;
  16398. var data = new Uint8Array( 3 * size );
  16399. var r = Math.floor( color.r * 255 );
  16400. var g = Math.floor( color.g * 255 );
  16401. var b = Math.floor( color.b * 255 );
  16402. for ( var i = 0; i < size; i ++ ) {
  16403. data[ i * 3 ] = r;
  16404. data[ i * 3 + 1 ] = g;
  16405. data[ i * 3 + 2 ] = b;
  16406. }
  16407. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16408. texture.needsUpdate = true;
  16409. return texture;
  16410. }
  16411. };
  16412. /**
  16413. * @author alteredq / http://alteredqualia.com/
  16414. */
  16415. THREE.SceneUtils = {
  16416. createMultiMaterialObject: function ( geometry, materials ) {
  16417. var group = new THREE.Object3D();
  16418. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16419. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16420. }
  16421. return group;
  16422. },
  16423. detach : function ( child, parent, scene ) {
  16424. child.applyMatrix( parent.matrixWorld );
  16425. parent.remove( child );
  16426. scene.add( child );
  16427. },
  16428. attach: function ( child, scene, parent ) {
  16429. var matrixWorldInverse = new THREE.Matrix4();
  16430. matrixWorldInverse.getInverse( parent.matrixWorld );
  16431. child.applyMatrix( matrixWorldInverse );
  16432. scene.remove( child );
  16433. parent.add( child );
  16434. }
  16435. };
  16436. /**
  16437. * @author zz85 / http://www.lab4games.net/zz85/blog
  16438. * @author alteredq / http://alteredqualia.com/
  16439. *
  16440. * For Text operations in three.js (See TextGeometry)
  16441. *
  16442. * It uses techniques used in:
  16443. *
  16444. * typeface.js and canvastext
  16445. * For converting fonts and rendering with javascript
  16446. * http://typeface.neocracy.org
  16447. *
  16448. * Triangulation ported from AS3
  16449. * Simple Polygon Triangulation
  16450. * http://actionsnippet.com/?p=1462
  16451. *
  16452. * A Method to triangulate shapes with holes
  16453. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16454. *
  16455. */
  16456. THREE.FontUtils = {
  16457. faces : {},
  16458. // Just for now. face[weight][style]
  16459. face : "helvetiker",
  16460. weight: "normal",
  16461. style : "normal",
  16462. size : 150,
  16463. divisions : 10,
  16464. getFace : function() {
  16465. return this.faces[ this.face ][ this.weight ][ this.style ];
  16466. },
  16467. loadFace : function( data ) {
  16468. var family = data.familyName.toLowerCase();
  16469. var ThreeFont = this;
  16470. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16471. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16472. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16473. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16474. return data;
  16475. },
  16476. drawText : function( text ) {
  16477. var characterPts = [], allPts = [];
  16478. // RenderText
  16479. var i, p,
  16480. face = this.getFace(),
  16481. scale = this.size / face.resolution,
  16482. offset = 0,
  16483. chars = String( text ).split( '' ),
  16484. length = chars.length;
  16485. var fontPaths = [];
  16486. for ( i = 0; i < length; i ++ ) {
  16487. var path = new THREE.Path();
  16488. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16489. offset += ret.offset;
  16490. fontPaths.push( ret.path );
  16491. }
  16492. // get the width
  16493. var width = offset / 2;
  16494. //
  16495. // for ( p = 0; p < allPts.length; p++ ) {
  16496. //
  16497. // allPts[ p ].x -= width;
  16498. //
  16499. // }
  16500. //var extract = this.extractPoints( allPts, characterPts );
  16501. //extract.contour = allPts;
  16502. //extract.paths = fontPaths;
  16503. //extract.offset = width;
  16504. return { paths : fontPaths, offset : width };
  16505. },
  16506. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16507. var pts = [];
  16508. var i, i2, divisions,
  16509. outline, action, length,
  16510. scaleX, scaleY,
  16511. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16512. laste,
  16513. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16514. if ( !glyph ) return;
  16515. if ( glyph.o ) {
  16516. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16517. length = outline.length;
  16518. scaleX = scale;
  16519. scaleY = scale;
  16520. for ( i = 0; i < length; ) {
  16521. action = outline[ i ++ ];
  16522. //console.log( action );
  16523. switch( action ) {
  16524. case 'm':
  16525. // Move To
  16526. x = outline[ i++ ] * scaleX + offset;
  16527. y = outline[ i++ ] * scaleY;
  16528. path.moveTo( x, y );
  16529. break;
  16530. case 'l':
  16531. // Line To
  16532. x = outline[ i++ ] * scaleX + offset;
  16533. y = outline[ i++ ] * scaleY;
  16534. path.lineTo(x,y);
  16535. break;
  16536. case 'q':
  16537. // QuadraticCurveTo
  16538. cpx = outline[ i++ ] * scaleX + offset;
  16539. cpy = outline[ i++ ] * scaleY;
  16540. cpx1 = outline[ i++ ] * scaleX + offset;
  16541. cpy1 = outline[ i++ ] * scaleY;
  16542. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16543. laste = pts[ pts.length - 1 ];
  16544. if ( laste ) {
  16545. cpx0 = laste.x;
  16546. cpy0 = laste.y;
  16547. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16548. var t = i2 / divisions;
  16549. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16550. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16551. }
  16552. }
  16553. break;
  16554. case 'b':
  16555. // Cubic Bezier Curve
  16556. cpx = outline[ i++ ] * scaleX + offset;
  16557. cpy = outline[ i++ ] * scaleY;
  16558. cpx1 = outline[ i++ ] * scaleX + offset;
  16559. cpy1 = outline[ i++ ] * -scaleY;
  16560. cpx2 = outline[ i++ ] * scaleX + offset;
  16561. cpy2 = outline[ i++ ] * -scaleY;
  16562. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16563. laste = pts[ pts.length - 1 ];
  16564. if ( laste ) {
  16565. cpx0 = laste.x;
  16566. cpy0 = laste.y;
  16567. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16568. var t = i2 / divisions;
  16569. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16570. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16571. }
  16572. }
  16573. break;
  16574. }
  16575. }
  16576. }
  16577. return { offset: glyph.ha*scale, path:path};
  16578. }
  16579. };
  16580. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16581. // Parameters
  16582. parameters = parameters || {};
  16583. var size = parameters.size !== undefined ? parameters.size : 100;
  16584. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16585. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16586. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16587. var style = parameters.style !== undefined ? parameters.style : "normal";
  16588. THREE.FontUtils.size = size;
  16589. THREE.FontUtils.divisions = curveSegments;
  16590. THREE.FontUtils.face = font;
  16591. THREE.FontUtils.weight = weight;
  16592. THREE.FontUtils.style = style;
  16593. // Get a Font data json object
  16594. var data = THREE.FontUtils.drawText( text );
  16595. var paths = data.paths;
  16596. var shapes = [];
  16597. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16598. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16599. }
  16600. return shapes;
  16601. };
  16602. /**
  16603. * This code is a quick port of code written in C++ which was submitted to
  16604. * flipcode.com by John W. Ratcliff // July 22, 2000
  16605. * See original code and more information here:
  16606. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16607. *
  16608. * ported to actionscript by Zevan Rosser
  16609. * www.actionsnippet.com
  16610. *
  16611. * ported to javascript by Joshua Koo
  16612. * http://www.lab4games.net/zz85/blog
  16613. *
  16614. */
  16615. ( function( namespace ) {
  16616. var EPSILON = 0.0000000001;
  16617. // takes in an contour array and returns
  16618. var process = function( contour, indices ) {
  16619. var n = contour.length;
  16620. if ( n < 3 ) return null;
  16621. var result = [],
  16622. verts = [],
  16623. vertIndices = [];
  16624. /* we want a counter-clockwise polygon in verts */
  16625. var u, v, w;
  16626. if ( area( contour ) > 0.0 ) {
  16627. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16628. } else {
  16629. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16630. }
  16631. var nv = n;
  16632. /* remove nv - 2 vertices, creating 1 triangle every time */
  16633. var count = 2 * nv; /* error detection */
  16634. for( v = nv - 1; nv > 2; ) {
  16635. /* if we loop, it is probably a non-simple polygon */
  16636. if ( ( count-- ) <= 0 ) {
  16637. //** Triangulate: ERROR - probable bad polygon!
  16638. //throw ( "Warning, unable to triangulate polygon!" );
  16639. //return null;
  16640. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16641. console.log( "Warning, unable to triangulate polygon!" );
  16642. if ( indices ) return vertIndices;
  16643. return result;
  16644. }
  16645. /* three consecutive vertices in current polygon, <u,v,w> */
  16646. u = v; if ( nv <= u ) u = 0; /* previous */
  16647. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16648. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16649. if ( snip( contour, u, v, w, nv, verts ) ) {
  16650. var a, b, c, s, t;
  16651. /* true names of the vertices */
  16652. a = verts[ u ];
  16653. b = verts[ v ];
  16654. c = verts[ w ];
  16655. /* output Triangle */
  16656. result.push( [ contour[ a ],
  16657. contour[ b ],
  16658. contour[ c ] ] );
  16659. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16660. /* remove v from the remaining polygon */
  16661. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16662. verts[ s ] = verts[ t ];
  16663. }
  16664. nv--;
  16665. /* reset error detection counter */
  16666. count = 2 * nv;
  16667. }
  16668. }
  16669. if ( indices ) return vertIndices;
  16670. return result;
  16671. };
  16672. // calculate area of the contour polygon
  16673. var area = function ( contour ) {
  16674. var n = contour.length;
  16675. var a = 0.0;
  16676. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16677. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16678. }
  16679. return a * 0.5;
  16680. };
  16681. var snip = function ( contour, u, v, w, n, verts ) {
  16682. var p;
  16683. var ax, ay, bx, by;
  16684. var cx, cy, px, py;
  16685. ax = contour[ verts[ u ] ].x;
  16686. ay = contour[ verts[ u ] ].y;
  16687. bx = contour[ verts[ v ] ].x;
  16688. by = contour[ verts[ v ] ].y;
  16689. cx = contour[ verts[ w ] ].x;
  16690. cy = contour[ verts[ w ] ].y;
  16691. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16692. var aX, aY, bX, bY, cX, cY;
  16693. var apx, apy, bpx, bpy, cpx, cpy;
  16694. var cCROSSap, bCROSScp, aCROSSbp;
  16695. aX = cx - bx; aY = cy - by;
  16696. bX = ax - cx; bY = ay - cy;
  16697. cX = bx - ax; cY = by - ay;
  16698. for ( p = 0; p < n; p++ ) {
  16699. if( (p === u) || (p === v) || (p === w) ) continue;
  16700. px = contour[ verts[ p ] ].x
  16701. py = contour[ verts[ p ] ].y
  16702. apx = px - ax; apy = py - ay;
  16703. bpx = px - bx; bpy = py - by;
  16704. cpx = px - cx; cpy = py - cy;
  16705. // see if p is inside triangle abc
  16706. aCROSSbp = aX*bpy - aY*bpx;
  16707. cCROSSap = cX*apy - cY*apx;
  16708. bCROSScp = bX*cpy - bY*cpx;
  16709. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16710. }
  16711. return true;
  16712. };
  16713. namespace.Triangulate = process;
  16714. namespace.Triangulate.area = area;
  16715. return namespace;
  16716. })(THREE.FontUtils);
  16717. // To use the typeface.js face files, hook up the API
  16718. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16719. THREE.typeface_js = self._typeface_js;
  16720. /**
  16721. * @author zz85 / http://www.lab4games.net/zz85/blog
  16722. * Extensible curve object
  16723. *
  16724. * Some common of Curve methods
  16725. * .getPoint(t), getTangent(t)
  16726. * .getPointAt(u), getTagentAt(u)
  16727. * .getPoints(), .getSpacedPoints()
  16728. * .getLength()
  16729. * .updateArcLengths()
  16730. *
  16731. * This following classes subclasses THREE.Curve:
  16732. *
  16733. * -- 2d classes --
  16734. * THREE.LineCurve
  16735. * THREE.QuadraticBezierCurve
  16736. * THREE.CubicBezierCurve
  16737. * THREE.SplineCurve
  16738. * THREE.ArcCurve
  16739. * THREE.EllipseCurve
  16740. *
  16741. * -- 3d classes --
  16742. * THREE.LineCurve3
  16743. * THREE.QuadraticBezierCurve3
  16744. * THREE.CubicBezierCurve3
  16745. * THREE.SplineCurve3
  16746. * THREE.ClosedSplineCurve3
  16747. *
  16748. * A series of curves can be represented as a THREE.CurvePath
  16749. *
  16750. **/
  16751. /**************************************************************
  16752. * Abstract Curve base class
  16753. **************************************************************/
  16754. THREE.Curve = function () {
  16755. };
  16756. // Virtual base class method to overwrite and implement in subclasses
  16757. // - t [0 .. 1]
  16758. THREE.Curve.prototype.getPoint = function ( t ) {
  16759. console.log( "Warning, getPoint() not implemented!" );
  16760. return null;
  16761. };
  16762. // Get point at relative position in curve according to arc length
  16763. // - u [0 .. 1]
  16764. THREE.Curve.prototype.getPointAt = function ( u ) {
  16765. var t = this.getUtoTmapping( u );
  16766. return this.getPoint( t );
  16767. };
  16768. // Get sequence of points using getPoint( t )
  16769. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16770. if ( !divisions ) divisions = 5;
  16771. var d, pts = [];
  16772. for ( d = 0; d <= divisions; d ++ ) {
  16773. pts.push( this.getPoint( d / divisions ) );
  16774. }
  16775. return pts;
  16776. };
  16777. // Get sequence of points using getPointAt( u )
  16778. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16779. if ( !divisions ) divisions = 5;
  16780. var d, pts = [];
  16781. for ( d = 0; d <= divisions; d ++ ) {
  16782. pts.push( this.getPointAt( d / divisions ) );
  16783. }
  16784. return pts;
  16785. };
  16786. // Get total curve arc length
  16787. THREE.Curve.prototype.getLength = function () {
  16788. var lengths = this.getLengths();
  16789. return lengths[ lengths.length - 1 ];
  16790. };
  16791. // Get list of cumulative segment lengths
  16792. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16793. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16794. if ( this.cacheArcLengths
  16795. && ( this.cacheArcLengths.length == divisions + 1 )
  16796. && !this.needsUpdate) {
  16797. //console.log( "cached", this.cacheArcLengths );
  16798. return this.cacheArcLengths;
  16799. }
  16800. this.needsUpdate = false;
  16801. var cache = [];
  16802. var current, last = this.getPoint( 0 );
  16803. var p, sum = 0;
  16804. cache.push( 0 );
  16805. for ( p = 1; p <= divisions; p ++ ) {
  16806. current = this.getPoint ( p / divisions );
  16807. sum += current.distanceTo( last );
  16808. cache.push( sum );
  16809. last = current;
  16810. }
  16811. this.cacheArcLengths = cache;
  16812. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16813. };
  16814. THREE.Curve.prototype.updateArcLengths = function() {
  16815. this.needsUpdate = true;
  16816. this.getLengths();
  16817. };
  16818. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16819. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16820. var arcLengths = this.getLengths();
  16821. var i = 0, il = arcLengths.length;
  16822. var targetArcLength; // The targeted u distance value to get
  16823. if ( distance ) {
  16824. targetArcLength = distance;
  16825. } else {
  16826. targetArcLength = u * arcLengths[ il - 1 ];
  16827. }
  16828. //var time = Date.now();
  16829. // binary search for the index with largest value smaller than target u distance
  16830. var low = 0, high = il - 1, comparison;
  16831. while ( low <= high ) {
  16832. 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
  16833. comparison = arcLengths[ i ] - targetArcLength;
  16834. if ( comparison < 0 ) {
  16835. low = i + 1;
  16836. continue;
  16837. } else if ( comparison > 0 ) {
  16838. high = i - 1;
  16839. continue;
  16840. } else {
  16841. high = i;
  16842. break;
  16843. // DONE
  16844. }
  16845. }
  16846. i = high;
  16847. //console.log('b' , i, low, high, Date.now()- time);
  16848. if ( arcLengths[ i ] == targetArcLength ) {
  16849. var t = i / ( il - 1 );
  16850. return t;
  16851. }
  16852. // we could get finer grain at lengths, or use simple interpolatation between two points
  16853. var lengthBefore = arcLengths[ i ];
  16854. var lengthAfter = arcLengths[ i + 1 ];
  16855. var segmentLength = lengthAfter - lengthBefore;
  16856. // determine where we are between the 'before' and 'after' points
  16857. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16858. // add that fractional amount to t
  16859. var t = ( i + segmentFraction ) / ( il -1 );
  16860. return t;
  16861. };
  16862. // Returns a unit vector tangent at t
  16863. // In case any sub curve does not implement its tangent derivation,
  16864. // 2 points a small delta apart will be used to find its gradient
  16865. // which seems to give a reasonable approximation
  16866. THREE.Curve.prototype.getTangent = function( t ) {
  16867. var delta = 0.0001;
  16868. var t1 = t - delta;
  16869. var t2 = t + delta;
  16870. // Capping in case of danger
  16871. if ( t1 < 0 ) t1 = 0;
  16872. if ( t2 > 1 ) t2 = 1;
  16873. var pt1 = this.getPoint( t1 );
  16874. var pt2 = this.getPoint( t2 );
  16875. var vec = pt2.clone().sub(pt1);
  16876. return vec.normalize();
  16877. };
  16878. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16879. var t = this.getUtoTmapping( u );
  16880. return this.getTangent( t );
  16881. };
  16882. /**************************************************************
  16883. * Utils
  16884. **************************************************************/
  16885. THREE.Curve.Utils = {
  16886. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16887. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16888. },
  16889. // Puay Bing, thanks for helping with this derivative!
  16890. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16891. return -3 * p0 * (1 - t) * (1 - t) +
  16892. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16893. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16894. 3 * t * t * p3;
  16895. },
  16896. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16897. // To check if my formulas are correct
  16898. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16899. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16900. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16901. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16902. return h00 + h10 + h01 + h11;
  16903. },
  16904. // Catmull-Rom
  16905. interpolate: function( p0, p1, p2, p3, t ) {
  16906. var v0 = ( p2 - p0 ) * 0.5;
  16907. var v1 = ( p3 - p1 ) * 0.5;
  16908. var t2 = t * t;
  16909. var t3 = t * t2;
  16910. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16911. }
  16912. };
  16913. // TODO: Transformation for Curves?
  16914. /**************************************************************
  16915. * 3D Curves
  16916. **************************************************************/
  16917. // A Factory method for creating new curve subclasses
  16918. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16919. constructor.prototype = Object.create( THREE.Curve.prototype );
  16920. constructor.prototype.getPoint = getPointFunc;
  16921. return constructor;
  16922. };
  16923. /**
  16924. * @author zz85 / http://www.lab4games.net/zz85/blog
  16925. *
  16926. **/
  16927. /**************************************************************
  16928. * Curved Path - a curve path is simply a array of connected
  16929. * curves, but retains the api of a curve
  16930. **************************************************************/
  16931. THREE.CurvePath = function () {
  16932. this.curves = [];
  16933. this.bends = [];
  16934. this.autoClose = false; // Automatically closes the path
  16935. };
  16936. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16937. THREE.CurvePath.prototype.add = function ( curve ) {
  16938. this.curves.push( curve );
  16939. };
  16940. THREE.CurvePath.prototype.checkConnection = function() {
  16941. // TODO
  16942. // If the ending of curve is not connected to the starting
  16943. // or the next curve, then, this is not a real path
  16944. };
  16945. THREE.CurvePath.prototype.closePath = function() {
  16946. // TODO Test
  16947. // and verify for vector3 (needs to implement equals)
  16948. // Add a line curve if start and end of lines are not connected
  16949. var startPoint = this.curves[0].getPoint(0);
  16950. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16951. if (!startPoint.equals(endPoint)) {
  16952. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16953. }
  16954. };
  16955. // To get accurate point with reference to
  16956. // entire path distance at time t,
  16957. // following has to be done:
  16958. // 1. Length of each sub path have to be known
  16959. // 2. Locate and identify type of curve
  16960. // 3. Get t for the curve
  16961. // 4. Return curve.getPointAt(t')
  16962. THREE.CurvePath.prototype.getPoint = function( t ) {
  16963. var d = t * this.getLength();
  16964. var curveLengths = this.getCurveLengths();
  16965. var i = 0, diff, curve;
  16966. // To think about boundaries points.
  16967. while ( i < curveLengths.length ) {
  16968. if ( curveLengths[ i ] >= d ) {
  16969. diff = curveLengths[ i ] - d;
  16970. curve = this.curves[ i ];
  16971. var u = 1 - diff / curve.getLength();
  16972. return curve.getPointAt( u );
  16973. break;
  16974. }
  16975. i ++;
  16976. }
  16977. return null;
  16978. // loop where sum != 0, sum > d , sum+1 <d
  16979. };
  16980. /*
  16981. THREE.CurvePath.prototype.getTangent = function( t ) {
  16982. };*/
  16983. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16984. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16985. // getPoint() depends on getLength
  16986. THREE.CurvePath.prototype.getLength = function() {
  16987. var lens = this.getCurveLengths();
  16988. return lens[ lens.length - 1 ];
  16989. };
  16990. // Compute lengths and cache them
  16991. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16992. THREE.CurvePath.prototype.getCurveLengths = function() {
  16993. // We use cache values if curves and cache array are same length
  16994. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16995. return this.cacheLengths;
  16996. };
  16997. // Get length of subsurve
  16998. // Push sums into cached array
  16999. var lengths = [], sums = 0;
  17000. var i, il = this.curves.length;
  17001. for ( i = 0; i < il; i ++ ) {
  17002. sums += this.curves[ i ].getLength();
  17003. lengths.push( sums );
  17004. }
  17005. this.cacheLengths = lengths;
  17006. return lengths;
  17007. };
  17008. // Returns min and max coordinates, as well as centroid
  17009. THREE.CurvePath.prototype.getBoundingBox = function () {
  17010. var points = this.getPoints();
  17011. var maxX, maxY, maxZ;
  17012. var minX, minY, minZ;
  17013. maxX = maxY = Number.NEGATIVE_INFINITY;
  17014. minX = minY = Number.POSITIVE_INFINITY;
  17015. var p, i, il, sum;
  17016. var v3 = points[0] instanceof THREE.Vector3;
  17017. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17018. for ( i = 0, il = points.length; i < il; i ++ ) {
  17019. p = points[ i ];
  17020. if ( p.x > maxX ) maxX = p.x;
  17021. else if ( p.x < minX ) minX = p.x;
  17022. if ( p.y > maxY ) maxY = p.y;
  17023. else if ( p.y < minY ) minY = p.y;
  17024. if ( v3 ) {
  17025. if ( p.z > maxZ ) maxZ = p.z;
  17026. else if ( p.z < minZ ) minZ = p.z;
  17027. }
  17028. sum.add( p );
  17029. }
  17030. var ret = {
  17031. minX: minX,
  17032. minY: minY,
  17033. maxX: maxX,
  17034. maxY: maxY,
  17035. centroid: sum.divideScalar( il )
  17036. };
  17037. if ( v3 ) {
  17038. ret.maxZ = maxZ;
  17039. ret.minZ = minZ;
  17040. }
  17041. return ret;
  17042. };
  17043. /**************************************************************
  17044. * Create Geometries Helpers
  17045. **************************************************************/
  17046. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17047. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17048. var pts = this.getPoints( divisions, true );
  17049. return this.createGeometry( pts );
  17050. };
  17051. // Generate geometry from equidistance sampling along the path
  17052. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17053. var pts = this.getSpacedPoints( divisions, true );
  17054. return this.createGeometry( pts );
  17055. };
  17056. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17057. var geometry = new THREE.Geometry();
  17058. for ( var i = 0; i < points.length; i ++ ) {
  17059. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17060. }
  17061. return geometry;
  17062. };
  17063. /**************************************************************
  17064. * Bend / Wrap Helper Methods
  17065. **************************************************************/
  17066. // Wrap path / Bend modifiers?
  17067. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17068. this.bends.push( bendpath );
  17069. };
  17070. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17071. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17072. var i, il;
  17073. if ( !bends ) {
  17074. bends = this.bends;
  17075. }
  17076. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17077. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17078. }
  17079. return oldPts;
  17080. };
  17081. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17082. var oldPts = this.getSpacedPoints( segments );
  17083. var i, il;
  17084. if ( !bends ) {
  17085. bends = this.bends;
  17086. }
  17087. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17088. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17089. }
  17090. return oldPts;
  17091. };
  17092. // This returns getPoints() bend/wrapped around the contour of a path.
  17093. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17094. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17095. var bounds = this.getBoundingBox();
  17096. var i, il, p, oldX, oldY, xNorm;
  17097. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17098. p = oldPts[ i ];
  17099. oldX = p.x;
  17100. oldY = p.y;
  17101. xNorm = oldX / bounds.maxX;
  17102. // If using actual distance, for length > path, requires line extrusions
  17103. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17104. xNorm = path.getUtoTmapping( xNorm, oldX );
  17105. // check for out of bounds?
  17106. var pathPt = path.getPoint( xNorm );
  17107. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17108. p.x = pathPt.x + normal.x;
  17109. p.y = pathPt.y + normal.y;
  17110. }
  17111. return oldPts;
  17112. };
  17113. /**
  17114. * @author alteredq / http://alteredqualia.com/
  17115. */
  17116. THREE.Gyroscope = function () {
  17117. THREE.Object3D.call( this );
  17118. };
  17119. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17120. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17121. this.matrixAutoUpdate && this.updateMatrix();
  17122. // update matrixWorld
  17123. if ( this.matrixWorldNeedsUpdate || force ) {
  17124. if ( this.parent ) {
  17125. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17126. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  17127. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  17128. this.matrixWorld.makeFromPositionQuaternionScale( this.translationWorld, this.rotationObject, this.scaleWorld );
  17129. } else {
  17130. this.matrixWorld.copy( this.matrix );
  17131. }
  17132. this.matrixWorldNeedsUpdate = false;
  17133. force = true;
  17134. }
  17135. // update children
  17136. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17137. this.children[ i ].updateMatrixWorld( force );
  17138. }
  17139. };
  17140. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17141. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17142. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  17143. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  17144. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17145. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17146. /**
  17147. * @author zz85 / http://www.lab4games.net/zz85/blog
  17148. * Creates free form 2d path using series of points, lines or curves.
  17149. *
  17150. **/
  17151. THREE.Path = function ( points ) {
  17152. THREE.CurvePath.call(this);
  17153. this.actions = [];
  17154. if ( points ) {
  17155. this.fromPoints( points );
  17156. }
  17157. };
  17158. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17159. THREE.PathActions = {
  17160. MOVE_TO: 'moveTo',
  17161. LINE_TO: 'lineTo',
  17162. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17163. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17164. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17165. ARC: 'arc', // Circle
  17166. ELLIPSE: 'ellipse'
  17167. };
  17168. // TODO Clean up PATH API
  17169. // Create path using straight lines to connect all points
  17170. // - vectors: array of Vector2
  17171. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17172. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17173. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17174. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17175. };
  17176. };
  17177. // startPath() endPath()?
  17178. THREE.Path.prototype.moveTo = function ( x, y ) {
  17179. var args = Array.prototype.slice.call( arguments );
  17180. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17181. };
  17182. THREE.Path.prototype.lineTo = function ( x, y ) {
  17183. var args = Array.prototype.slice.call( arguments );
  17184. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17185. var x0 = lastargs[ lastargs.length - 2 ];
  17186. var y0 = lastargs[ lastargs.length - 1 ];
  17187. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17188. this.curves.push( curve );
  17189. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17190. };
  17191. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17192. var args = Array.prototype.slice.call( arguments );
  17193. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17194. var x0 = lastargs[ lastargs.length - 2 ];
  17195. var y0 = lastargs[ lastargs.length - 1 ];
  17196. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17197. new THREE.Vector2( aCPx, aCPy ),
  17198. new THREE.Vector2( aX, aY ) );
  17199. this.curves.push( curve );
  17200. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17201. };
  17202. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17203. aCP2x, aCP2y,
  17204. aX, aY ) {
  17205. var args = Array.prototype.slice.call( arguments );
  17206. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17207. var x0 = lastargs[ lastargs.length - 2 ];
  17208. var y0 = lastargs[ lastargs.length - 1 ];
  17209. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17210. new THREE.Vector2( aCP1x, aCP1y ),
  17211. new THREE.Vector2( aCP2x, aCP2y ),
  17212. new THREE.Vector2( aX, aY ) );
  17213. this.curves.push( curve );
  17214. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17215. };
  17216. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17217. var args = Array.prototype.slice.call( arguments );
  17218. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17219. var x0 = lastargs[ lastargs.length - 2 ];
  17220. var y0 = lastargs[ lastargs.length - 1 ];
  17221. //---
  17222. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17223. Array.prototype.push.apply( npts, pts );
  17224. var curve = new THREE.SplineCurve( npts );
  17225. this.curves.push( curve );
  17226. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17227. };
  17228. // FUTURE: Change the API or follow canvas API?
  17229. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17230. aStartAngle, aEndAngle, aClockwise ) {
  17231. var lastargs = this.actions[ this.actions.length - 1].args;
  17232. var x0 = lastargs[ lastargs.length - 2 ];
  17233. var y0 = lastargs[ lastargs.length - 1 ];
  17234. this.absarc(aX + x0, aY + y0, aRadius,
  17235. aStartAngle, aEndAngle, aClockwise );
  17236. };
  17237. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17238. aStartAngle, aEndAngle, aClockwise ) {
  17239. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17240. };
  17241. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17242. aStartAngle, aEndAngle, aClockwise ) {
  17243. var lastargs = this.actions[ this.actions.length - 1].args;
  17244. var x0 = lastargs[ lastargs.length - 2 ];
  17245. var y0 = lastargs[ lastargs.length - 1 ];
  17246. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17247. aStartAngle, aEndAngle, aClockwise );
  17248. };
  17249. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17250. aStartAngle, aEndAngle, aClockwise ) {
  17251. var args = Array.prototype.slice.call( arguments );
  17252. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17253. aStartAngle, aEndAngle, aClockwise );
  17254. this.curves.push( curve );
  17255. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17256. args.push(lastPoint.x);
  17257. args.push(lastPoint.y);
  17258. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17259. };
  17260. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17261. if ( ! divisions ) divisions = 40;
  17262. var points = [];
  17263. for ( var i = 0; i < divisions; i ++ ) {
  17264. points.push( this.getPoint( i / divisions ) );
  17265. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17266. }
  17267. // if ( closedPath ) {
  17268. //
  17269. // points.push( points[ 0 ] );
  17270. //
  17271. // }
  17272. return points;
  17273. };
  17274. /* Return an array of vectors based on contour of the path */
  17275. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17276. if (this.useSpacedPoints) {
  17277. console.log('tata');
  17278. return this.getSpacedPoints( divisions, closedPath );
  17279. }
  17280. divisions = divisions || 12;
  17281. var points = [];
  17282. var i, il, item, action, args;
  17283. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17284. laste, j,
  17285. t, tx, ty;
  17286. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17287. item = this.actions[ i ];
  17288. action = item.action;
  17289. args = item.args;
  17290. switch( action ) {
  17291. case THREE.PathActions.MOVE_TO:
  17292. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17293. break;
  17294. case THREE.PathActions.LINE_TO:
  17295. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17296. break;
  17297. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17298. cpx = args[ 2 ];
  17299. cpy = args[ 3 ];
  17300. cpx1 = args[ 0 ];
  17301. cpy1 = args[ 1 ];
  17302. if ( points.length > 0 ) {
  17303. laste = points[ points.length - 1 ];
  17304. cpx0 = laste.x;
  17305. cpy0 = laste.y;
  17306. } else {
  17307. laste = this.actions[ i - 1 ].args;
  17308. cpx0 = laste[ laste.length - 2 ];
  17309. cpy0 = laste[ laste.length - 1 ];
  17310. }
  17311. for ( j = 1; j <= divisions; j ++ ) {
  17312. t = j / divisions;
  17313. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17314. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17315. points.push( new THREE.Vector2( tx, ty ) );
  17316. }
  17317. break;
  17318. case THREE.PathActions.BEZIER_CURVE_TO:
  17319. cpx = args[ 4 ];
  17320. cpy = args[ 5 ];
  17321. cpx1 = args[ 0 ];
  17322. cpy1 = args[ 1 ];
  17323. cpx2 = args[ 2 ];
  17324. cpy2 = args[ 3 ];
  17325. if ( points.length > 0 ) {
  17326. laste = points[ points.length - 1 ];
  17327. cpx0 = laste.x;
  17328. cpy0 = laste.y;
  17329. } else {
  17330. laste = this.actions[ i - 1 ].args;
  17331. cpx0 = laste[ laste.length - 2 ];
  17332. cpy0 = laste[ laste.length - 1 ];
  17333. }
  17334. for ( j = 1; j <= divisions; j ++ ) {
  17335. t = j / divisions;
  17336. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17337. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17338. points.push( new THREE.Vector2( tx, ty ) );
  17339. }
  17340. break;
  17341. case THREE.PathActions.CSPLINE_THRU:
  17342. laste = this.actions[ i - 1 ].args;
  17343. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17344. var spts = [ last ];
  17345. var n = divisions * args[ 0 ].length;
  17346. spts = spts.concat( args[ 0 ] );
  17347. var spline = new THREE.SplineCurve( spts );
  17348. for ( j = 1; j <= n; j ++ ) {
  17349. points.push( spline.getPointAt( j / n ) ) ;
  17350. }
  17351. break;
  17352. case THREE.PathActions.ARC:
  17353. var aX = args[ 0 ], aY = args[ 1 ],
  17354. aRadius = args[ 2 ],
  17355. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17356. aClockwise = !!args[ 5 ];
  17357. var deltaAngle = aEndAngle - aStartAngle;
  17358. var angle;
  17359. var tdivisions = divisions * 2;
  17360. for ( j = 1; j <= tdivisions; j ++ ) {
  17361. t = j / tdivisions;
  17362. if ( ! aClockwise ) {
  17363. t = 1 - t;
  17364. }
  17365. angle = aStartAngle + t * deltaAngle;
  17366. tx = aX + aRadius * Math.cos( angle );
  17367. ty = aY + aRadius * Math.sin( angle );
  17368. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17369. points.push( new THREE.Vector2( tx, ty ) );
  17370. }
  17371. //console.log(points);
  17372. break;
  17373. case THREE.PathActions.ELLIPSE:
  17374. var aX = args[ 0 ], aY = args[ 1 ],
  17375. xRadius = args[ 2 ],
  17376. yRadius = args[ 3 ],
  17377. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17378. aClockwise = !!args[ 6 ];
  17379. var deltaAngle = aEndAngle - aStartAngle;
  17380. var angle;
  17381. var tdivisions = divisions * 2;
  17382. for ( j = 1; j <= tdivisions; j ++ ) {
  17383. t = j / tdivisions;
  17384. if ( ! aClockwise ) {
  17385. t = 1 - t;
  17386. }
  17387. angle = aStartAngle + t * deltaAngle;
  17388. tx = aX + xRadius * Math.cos( angle );
  17389. ty = aY + yRadius * Math.sin( angle );
  17390. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17391. points.push( new THREE.Vector2( tx, ty ) );
  17392. }
  17393. //console.log(points);
  17394. break;
  17395. } // end switch
  17396. }
  17397. // Normalize to remove the closing point by default.
  17398. var lastPoint = points[ points.length - 1];
  17399. var EPSILON = 0.0000000001;
  17400. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17401. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17402. points.splice( points.length - 1, 1);
  17403. if ( closedPath ) {
  17404. points.push( points[ 0 ] );
  17405. }
  17406. return points;
  17407. };
  17408. // Breaks path into shapes
  17409. THREE.Path.prototype.toShapes = function() {
  17410. var i, il, item, action, args;
  17411. var subPaths = [], lastPath = new THREE.Path();
  17412. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17413. item = this.actions[ i ];
  17414. args = item.args;
  17415. action = item.action;
  17416. if ( action == THREE.PathActions.MOVE_TO ) {
  17417. if ( lastPath.actions.length != 0 ) {
  17418. subPaths.push( lastPath );
  17419. lastPath = new THREE.Path();
  17420. }
  17421. }
  17422. lastPath[ action ].apply( lastPath, args );
  17423. }
  17424. if ( lastPath.actions.length != 0 ) {
  17425. subPaths.push( lastPath );
  17426. }
  17427. // console.log(subPaths);
  17428. if ( subPaths.length == 0 ) return [];
  17429. var tmpPath, tmpShape, shapes = [];
  17430. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17431. // console.log("Holes first", holesFirst);
  17432. if ( subPaths.length == 1) {
  17433. tmpPath = subPaths[0];
  17434. tmpShape = new THREE.Shape();
  17435. tmpShape.actions = tmpPath.actions;
  17436. tmpShape.curves = tmpPath.curves;
  17437. shapes.push( tmpShape );
  17438. return shapes;
  17439. };
  17440. if ( holesFirst ) {
  17441. tmpShape = new THREE.Shape();
  17442. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17443. tmpPath = subPaths[ i ];
  17444. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17445. tmpShape.actions = tmpPath.actions;
  17446. tmpShape.curves = tmpPath.curves;
  17447. shapes.push( tmpShape );
  17448. tmpShape = new THREE.Shape();
  17449. //console.log('cw', i);
  17450. } else {
  17451. tmpShape.holes.push( tmpPath );
  17452. //console.log('ccw', i);
  17453. }
  17454. }
  17455. } else {
  17456. // Shapes first
  17457. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17458. tmpPath = subPaths[ i ];
  17459. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17460. if ( tmpShape ) shapes.push( tmpShape );
  17461. tmpShape = new THREE.Shape();
  17462. tmpShape.actions = tmpPath.actions;
  17463. tmpShape.curves = tmpPath.curves;
  17464. } else {
  17465. tmpShape.holes.push( tmpPath );
  17466. }
  17467. }
  17468. shapes.push( tmpShape );
  17469. }
  17470. //console.log("shape", shapes);
  17471. return shapes;
  17472. };
  17473. /**
  17474. * @author zz85 / http://www.lab4games.net/zz85/blog
  17475. * Defines a 2d shape plane using paths.
  17476. **/
  17477. // STEP 1 Create a path.
  17478. // STEP 2 Turn path into shape.
  17479. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17480. // STEP 3a - Extract points from each shape, turn to vertices
  17481. // STEP 3b - Triangulate each shape, add faces.
  17482. THREE.Shape = function () {
  17483. THREE.Path.apply( this, arguments );
  17484. this.holes = [];
  17485. };
  17486. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17487. // Convenience method to return ExtrudeGeometry
  17488. THREE.Shape.prototype.extrude = function ( options ) {
  17489. var extruded = new THREE.ExtrudeGeometry( this, options );
  17490. return extruded;
  17491. };
  17492. // Convenience method to return ShapeGeometry
  17493. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17494. var geometry = new THREE.ShapeGeometry( this, options );
  17495. return geometry;
  17496. };
  17497. // Get points of holes
  17498. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17499. var i, il = this.holes.length, holesPts = [];
  17500. for ( i = 0; i < il; i ++ ) {
  17501. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17502. }
  17503. return holesPts;
  17504. };
  17505. // Get points of holes (spaced by regular distance)
  17506. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17507. var i, il = this.holes.length, holesPts = [];
  17508. for ( i = 0; i < il; i ++ ) {
  17509. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17510. }
  17511. return holesPts;
  17512. };
  17513. // Get points of shape and holes (keypoints based on segments parameter)
  17514. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17515. return {
  17516. shape: this.getTransformedPoints( divisions ),
  17517. holes: this.getPointsHoles( divisions )
  17518. };
  17519. };
  17520. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17521. if (this.useSpacedPoints) {
  17522. return this.extractAllSpacedPoints(divisions);
  17523. }
  17524. return this.extractAllPoints(divisions);
  17525. };
  17526. //
  17527. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17528. //
  17529. // return {
  17530. //
  17531. // shape: this.transform( bend, divisions ),
  17532. // holes: this.getPointsHoles( divisions, bend )
  17533. //
  17534. // };
  17535. //
  17536. // };
  17537. // Get points of shape and holes (spaced by regular distance)
  17538. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17539. return {
  17540. shape: this.getTransformedSpacedPoints( divisions ),
  17541. holes: this.getSpacedPointsHoles( divisions )
  17542. };
  17543. };
  17544. /**************************************************************
  17545. * Utils
  17546. **************************************************************/
  17547. THREE.Shape.Utils = {
  17548. /*
  17549. contour - array of vector2 for contour
  17550. holes - array of array of vector2
  17551. */
  17552. removeHoles: function ( contour, holes ) {
  17553. var shape = contour.concat(); // work on this shape
  17554. var allpoints = shape.concat();
  17555. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17556. var prevShapeVert, nextShapeVert,
  17557. prevHoleVert, nextHoleVert,
  17558. holeIndex, shapeIndex,
  17559. shapeId, shapeGroup,
  17560. h, h2,
  17561. hole, shortest, d,
  17562. p, pts1, pts2,
  17563. tmpShape1, tmpShape2,
  17564. tmpHole1, tmpHole2,
  17565. verts = [];
  17566. for ( h = 0; h < holes.length; h ++ ) {
  17567. hole = holes[ h ];
  17568. /*
  17569. shapeholes[ h ].concat(); // preserves original
  17570. holes.push( hole );
  17571. */
  17572. Array.prototype.push.apply( allpoints, hole );
  17573. shortest = Number.POSITIVE_INFINITY;
  17574. // Find the shortest pair of pts between shape and hole
  17575. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17576. // Using distanceToSquared() intead of distanceTo() should speed a little
  17577. // since running square roots operations are reduced.
  17578. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17579. pts1 = hole[ h2 ];
  17580. var dist = [];
  17581. for ( p = 0; p < shape.length; p++ ) {
  17582. pts2 = shape[ p ];
  17583. d = pts1.distanceToSquared( pts2 );
  17584. dist.push( d );
  17585. if ( d < shortest ) {
  17586. shortest = d;
  17587. holeIndex = h2;
  17588. shapeIndex = p;
  17589. }
  17590. }
  17591. }
  17592. //console.log("shortest", shortest, dist);
  17593. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17594. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17595. var areaapts = [
  17596. hole[ holeIndex ],
  17597. shape[ shapeIndex ],
  17598. shape[ prevShapeVert ]
  17599. ];
  17600. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17601. var areabpts = [
  17602. hole[ holeIndex ],
  17603. hole[ prevHoleVert ],
  17604. shape[ shapeIndex ]
  17605. ];
  17606. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17607. var shapeOffset = 1;
  17608. var holeOffset = -1;
  17609. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17610. shapeIndex += shapeOffset;
  17611. holeIndex += holeOffset;
  17612. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17613. shapeIndex %= shape.length;
  17614. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17615. holeIndex %= hole.length;
  17616. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17617. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17618. areaapts = [
  17619. hole[ holeIndex ],
  17620. shape[ shapeIndex ],
  17621. shape[ prevShapeVert ]
  17622. ];
  17623. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17624. areabpts = [
  17625. hole[ holeIndex ],
  17626. hole[ prevHoleVert ],
  17627. shape[ shapeIndex ]
  17628. ];
  17629. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17630. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17631. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17632. // In case areas are not correct.
  17633. //console.log("USE THIS");
  17634. shapeIndex = oldShapeIndex;
  17635. holeIndex = oldHoleIndex ;
  17636. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17637. shapeIndex %= shape.length;
  17638. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17639. holeIndex %= hole.length;
  17640. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17641. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17642. } else {
  17643. //console.log("USE THAT ")
  17644. }
  17645. tmpShape1 = shape.slice( 0, shapeIndex );
  17646. tmpShape2 = shape.slice( shapeIndex );
  17647. tmpHole1 = hole.slice( holeIndex );
  17648. tmpHole2 = hole.slice( 0, holeIndex );
  17649. // Should check orders here again?
  17650. var trianglea = [
  17651. hole[ holeIndex ],
  17652. shape[ shapeIndex ],
  17653. shape[ prevShapeVert ]
  17654. ];
  17655. var triangleb = [
  17656. hole[ holeIndex ] ,
  17657. hole[ prevHoleVert ],
  17658. shape[ shapeIndex ]
  17659. ];
  17660. verts.push( trianglea );
  17661. verts.push( triangleb );
  17662. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17663. }
  17664. return {
  17665. shape:shape, /* shape with no holes */
  17666. isolatedPts: verts, /* isolated faces */
  17667. allpoints: allpoints
  17668. }
  17669. },
  17670. triangulateShape: function ( contour, holes ) {
  17671. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17672. var shape = shapeWithoutHoles.shape,
  17673. allpoints = shapeWithoutHoles.allpoints,
  17674. isolatedPts = shapeWithoutHoles.isolatedPts;
  17675. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17676. // 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.
  17677. //console.log( "triangles",triangles, triangles.length );
  17678. //console.log( "allpoints",allpoints, allpoints.length );
  17679. var i, il, f, face,
  17680. key, index,
  17681. allPointsMap = {},
  17682. isolatedPointsMap = {};
  17683. // prepare all points map
  17684. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17685. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17686. if ( allPointsMap[ key ] !== undefined ) {
  17687. console.log( "Duplicate point", key );
  17688. }
  17689. allPointsMap[ key ] = i;
  17690. }
  17691. // check all face vertices against all points map
  17692. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17693. face = triangles[ i ];
  17694. for ( f = 0; f < 3; f ++ ) {
  17695. key = face[ f ].x + ":" + face[ f ].y;
  17696. index = allPointsMap[ key ];
  17697. if ( index !== undefined ) {
  17698. face[ f ] = index;
  17699. }
  17700. }
  17701. }
  17702. // check isolated points vertices against all points map
  17703. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17704. face = isolatedPts[ i ];
  17705. for ( f = 0; f < 3; f ++ ) {
  17706. key = face[ f ].x + ":" + face[ f ].y;
  17707. index = allPointsMap[ key ];
  17708. if ( index !== undefined ) {
  17709. face[ f ] = index;
  17710. }
  17711. }
  17712. }
  17713. return triangles.concat( isolatedPts );
  17714. }, // end triangulate shapes
  17715. /*
  17716. triangulate2 : function( pts, holes ) {
  17717. // For use with Poly2Tri.js
  17718. var allpts = pts.concat();
  17719. var shape = [];
  17720. for (var p in pts) {
  17721. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17722. }
  17723. var swctx = new js.poly2tri.SweepContext(shape);
  17724. for (var h in holes) {
  17725. var aHole = holes[h];
  17726. var newHole = []
  17727. for (i in aHole) {
  17728. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17729. allpts.push(aHole[i]);
  17730. }
  17731. swctx.AddHole(newHole);
  17732. }
  17733. var find;
  17734. var findIndexForPt = function (pt) {
  17735. find = new THREE.Vector2(pt.x, pt.y);
  17736. var p;
  17737. for (p=0, pl = allpts.length; p<pl; p++) {
  17738. if (allpts[p].equals(find)) return p;
  17739. }
  17740. return -1;
  17741. };
  17742. // triangulate
  17743. js.poly2tri.sweep.Triangulate(swctx);
  17744. var triangles = swctx.GetTriangles();
  17745. var tr ;
  17746. var facesPts = [];
  17747. for (var t in triangles) {
  17748. tr = triangles[t];
  17749. facesPts.push([
  17750. findIndexForPt(tr.GetPoint(0)),
  17751. findIndexForPt(tr.GetPoint(1)),
  17752. findIndexForPt(tr.GetPoint(2))
  17753. ]);
  17754. }
  17755. // console.log(facesPts);
  17756. // console.log("triangles", triangles.length, triangles);
  17757. // Returns array of faces with 3 element each
  17758. return facesPts;
  17759. },
  17760. */
  17761. isClockWise: function ( pts ) {
  17762. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17763. },
  17764. // Bezier Curves formulas obtained from
  17765. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17766. // Quad Bezier Functions
  17767. b2p0: function ( t, p ) {
  17768. var k = 1 - t;
  17769. return k * k * p;
  17770. },
  17771. b2p1: function ( t, p ) {
  17772. return 2 * ( 1 - t ) * t * p;
  17773. },
  17774. b2p2: function ( t, p ) {
  17775. return t * t * p;
  17776. },
  17777. b2: function ( t, p0, p1, p2 ) {
  17778. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17779. },
  17780. // Cubic Bezier Functions
  17781. b3p0: function ( t, p ) {
  17782. var k = 1 - t;
  17783. return k * k * k * p;
  17784. },
  17785. b3p1: function ( t, p ) {
  17786. var k = 1 - t;
  17787. return 3 * k * k * t * p;
  17788. },
  17789. b3p2: function ( t, p ) {
  17790. var k = 1 - t;
  17791. return 3 * k * t * t * p;
  17792. },
  17793. b3p3: function ( t, p ) {
  17794. return t * t * t * p;
  17795. },
  17796. b3: function ( t, p0, p1, p2, p3 ) {
  17797. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17798. }
  17799. };
  17800. /**************************************************************
  17801. * Line
  17802. **************************************************************/
  17803. THREE.LineCurve = function ( v1, v2 ) {
  17804. this.v1 = v1;
  17805. this.v2 = v2;
  17806. };
  17807. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17808. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17809. var point = this.v2.clone().sub(this.v1);
  17810. point.multiplyScalar( t ).add( this.v1 );
  17811. return point;
  17812. };
  17813. // Line curve is linear, so we can overwrite default getPointAt
  17814. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17815. return this.getPoint( u );
  17816. };
  17817. THREE.LineCurve.prototype.getTangent = function( t ) {
  17818. var tangent = this.v2.clone().sub(this.v1);
  17819. return tangent.normalize();
  17820. };
  17821. /**************************************************************
  17822. * Quadratic Bezier curve
  17823. **************************************************************/
  17824. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17825. this.v0 = v0;
  17826. this.v1 = v1;
  17827. this.v2 = v2;
  17828. };
  17829. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17830. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17831. var tx, ty;
  17832. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17833. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17834. return new THREE.Vector2( tx, ty );
  17835. };
  17836. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17837. var tx, ty;
  17838. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17839. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17840. // returns unit vector
  17841. var tangent = new THREE.Vector2( tx, ty );
  17842. tangent.normalize();
  17843. return tangent;
  17844. };
  17845. /**************************************************************
  17846. * Cubic Bezier curve
  17847. **************************************************************/
  17848. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17849. this.v0 = v0;
  17850. this.v1 = v1;
  17851. this.v2 = v2;
  17852. this.v3 = v3;
  17853. };
  17854. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17855. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17856. var tx, ty;
  17857. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17858. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17859. return new THREE.Vector2( tx, ty );
  17860. };
  17861. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17862. var tx, ty;
  17863. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17864. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17865. var tangent = new THREE.Vector2( tx, ty );
  17866. tangent.normalize();
  17867. return tangent;
  17868. };
  17869. /**************************************************************
  17870. * Spline curve
  17871. **************************************************************/
  17872. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17873. this.points = (points == undefined) ? [] : points;
  17874. };
  17875. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17876. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17877. var v = new THREE.Vector2();
  17878. var c = [];
  17879. var points = this.points, point, intPoint, weight;
  17880. point = ( points.length - 1 ) * t;
  17881. intPoint = Math.floor( point );
  17882. weight = point - intPoint;
  17883. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17884. c[ 1 ] = intPoint;
  17885. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17886. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17887. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17888. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17889. return v;
  17890. };
  17891. /**************************************************************
  17892. * Ellipse curve
  17893. **************************************************************/
  17894. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  17895. aStartAngle, aEndAngle,
  17896. aClockwise ) {
  17897. this.aX = aX;
  17898. this.aY = aY;
  17899. this.xRadius = xRadius;
  17900. this.yRadius = yRadius;
  17901. this.aStartAngle = aStartAngle;
  17902. this.aEndAngle = aEndAngle;
  17903. this.aClockwise = aClockwise;
  17904. };
  17905. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17906. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17907. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17908. if ( !this.aClockwise ) {
  17909. t = 1 - t;
  17910. }
  17911. var angle = this.aStartAngle + t * deltaAngle;
  17912. var tx = this.aX + this.xRadius * Math.cos( angle );
  17913. var ty = this.aY + this.yRadius * Math.sin( angle );
  17914. return new THREE.Vector2( tx, ty );
  17915. };
  17916. /**************************************************************
  17917. * Arc curve
  17918. **************************************************************/
  17919. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17920. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17921. };
  17922. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17923. /**************************************************************
  17924. * Line3D
  17925. **************************************************************/
  17926. THREE.LineCurve3 = THREE.Curve.create(
  17927. function ( v1, v2 ) {
  17928. this.v1 = v1;
  17929. this.v2 = v2;
  17930. },
  17931. function ( t ) {
  17932. var r = new THREE.Vector3();
  17933. r.subVectors( this.v2, this.v1 ); // diff
  17934. r.multiplyScalar( t );
  17935. r.add( this.v1 );
  17936. return r;
  17937. }
  17938. );
  17939. /**************************************************************
  17940. * Quadratic Bezier 3D curve
  17941. **************************************************************/
  17942. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17943. function ( v0, v1, v2 ) {
  17944. this.v0 = v0;
  17945. this.v1 = v1;
  17946. this.v2 = v2;
  17947. },
  17948. function ( t ) {
  17949. var tx, ty, tz;
  17950. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17951. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17952. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17953. return new THREE.Vector3( tx, ty, tz );
  17954. }
  17955. );
  17956. /**************************************************************
  17957. * Cubic Bezier 3D curve
  17958. **************************************************************/
  17959. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17960. function ( v0, v1, v2, v3 ) {
  17961. this.v0 = v0;
  17962. this.v1 = v1;
  17963. this.v2 = v2;
  17964. this.v3 = v3;
  17965. },
  17966. function ( t ) {
  17967. var tx, ty, tz;
  17968. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17969. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17970. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17971. return new THREE.Vector3( tx, ty, tz );
  17972. }
  17973. );
  17974. /**************************************************************
  17975. * Spline 3D curve
  17976. **************************************************************/
  17977. THREE.SplineCurve3 = THREE.Curve.create(
  17978. function ( points /* array of Vector3 */) {
  17979. this.points = (points == undefined) ? [] : points;
  17980. },
  17981. function ( t ) {
  17982. var v = new THREE.Vector3();
  17983. var c = [];
  17984. var points = this.points, point, intPoint, weight;
  17985. point = ( points.length - 1 ) * t;
  17986. intPoint = Math.floor( point );
  17987. weight = point - intPoint;
  17988. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17989. c[ 1 ] = intPoint;
  17990. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17991. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17992. var pt0 = points[ c[0] ],
  17993. pt1 = points[ c[1] ],
  17994. pt2 = points[ c[2] ],
  17995. pt3 = points[ c[3] ];
  17996. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  17997. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  17998. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  17999. return v;
  18000. }
  18001. );
  18002. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18003. // var v = new THREE.Vector3();
  18004. // var c = [];
  18005. // var points = this.points, point, intPoint, weight;
  18006. // point = ( points.length - 1 ) * t;
  18007. // intPoint = Math.floor( point );
  18008. // weight = point - intPoint;
  18009. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18010. // c[ 1 ] = intPoint;
  18011. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18012. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18013. // var pt0 = points[ c[0] ],
  18014. // pt1 = points[ c[1] ],
  18015. // pt2 = points[ c[2] ],
  18016. // pt3 = points[ c[3] ];
  18017. // // t = weight;
  18018. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18019. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18020. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18021. // return v;
  18022. // }
  18023. /**************************************************************
  18024. * Closed Spline 3D curve
  18025. **************************************************************/
  18026. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18027. function ( points /* array of Vector3 */) {
  18028. this.points = (points == undefined) ? [] : points;
  18029. },
  18030. function ( t ) {
  18031. var v = new THREE.Vector3();
  18032. var c = [];
  18033. var points = this.points, point, intPoint, weight;
  18034. point = ( points.length - 0 ) * t;
  18035. // This needs to be from 0-length +1
  18036. intPoint = Math.floor( point );
  18037. weight = point - intPoint;
  18038. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18039. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18040. c[ 1 ] = ( intPoint ) % points.length;
  18041. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18042. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18043. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18044. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18045. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18046. return v;
  18047. }
  18048. );
  18049. /**
  18050. * @author mikael emtinger / http://gomo.se/
  18051. */
  18052. THREE.AnimationHandler = (function() {
  18053. var playing = [];
  18054. var library = {};
  18055. var that = {};
  18056. //--- update ---
  18057. that.update = function( deltaTimeMS ) {
  18058. for( var i = 0; i < playing.length; i ++ )
  18059. playing[ i ].update( deltaTimeMS );
  18060. };
  18061. //--- add ---
  18062. that.addToUpdate = function( animation ) {
  18063. if ( playing.indexOf( animation ) === -1 )
  18064. playing.push( animation );
  18065. };
  18066. //--- remove ---
  18067. that.removeFromUpdate = function( animation ) {
  18068. var index = playing.indexOf( animation );
  18069. if( index !== -1 )
  18070. playing.splice( index, 1 );
  18071. };
  18072. //--- add ---
  18073. that.add = function( data ) {
  18074. if ( library[ data.name ] !== undefined )
  18075. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18076. library[ data.name ] = data;
  18077. initData( data );
  18078. };
  18079. //--- get ---
  18080. that.get = function( name ) {
  18081. if ( typeof name === "string" ) {
  18082. if ( library[ name ] ) {
  18083. return library[ name ];
  18084. } else {
  18085. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18086. return null;
  18087. }
  18088. } else {
  18089. // todo: add simple tween library
  18090. }
  18091. };
  18092. //--- parse ---
  18093. that.parse = function( root ) {
  18094. // setup hierarchy
  18095. var hierarchy = [];
  18096. if ( root instanceof THREE.SkinnedMesh ) {
  18097. for( var b = 0; b < root.bones.length; b++ ) {
  18098. hierarchy.push( root.bones[ b ] );
  18099. }
  18100. } else {
  18101. parseRecurseHierarchy( root, hierarchy );
  18102. }
  18103. return hierarchy;
  18104. };
  18105. var parseRecurseHierarchy = function( root, hierarchy ) {
  18106. hierarchy.push( root );
  18107. for( var c = 0; c < root.children.length; c++ )
  18108. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18109. }
  18110. //--- init data ---
  18111. var initData = function( data ) {
  18112. if( data.initialized === true )
  18113. return;
  18114. // loop through all keys
  18115. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18116. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18117. // remove minus times
  18118. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18119. data.hierarchy[ h ].keys[ k ].time = 0;
  18120. // create quaternions
  18121. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18122. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18123. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18124. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18125. }
  18126. }
  18127. // prepare morph target keys
  18128. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18129. // get all used
  18130. var usedMorphTargets = {};
  18131. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18132. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18133. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18134. usedMorphTargets[ morphTargetName ] = -1;
  18135. }
  18136. }
  18137. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18138. // set all used on all frames
  18139. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18140. var influences = {};
  18141. for ( var morphTargetName in usedMorphTargets ) {
  18142. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18143. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18144. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18145. break;
  18146. }
  18147. }
  18148. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18149. influences[ morphTargetName ] = 0;
  18150. }
  18151. }
  18152. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18153. }
  18154. }
  18155. // remove all keys that are on the same time
  18156. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18157. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18158. data.hierarchy[ h ].keys.splice( k, 1 );
  18159. k --;
  18160. }
  18161. }
  18162. // set index
  18163. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18164. data.hierarchy[ h ].keys[ k ].index = k;
  18165. }
  18166. }
  18167. // JIT
  18168. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  18169. data.JIT = {};
  18170. data.JIT.hierarchy = [];
  18171. for( var h = 0; h < data.hierarchy.length; h ++ )
  18172. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  18173. // done
  18174. data.initialized = true;
  18175. };
  18176. // interpolation types
  18177. that.LINEAR = 0;
  18178. that.CATMULLROM = 1;
  18179. that.CATMULLROM_FORWARD = 2;
  18180. return that;
  18181. }());
  18182. /**
  18183. * @author mikael emtinger / http://gomo.se/
  18184. * @author mrdoob / http://mrdoob.com/
  18185. * @author alteredq / http://alteredqualia.com/
  18186. */
  18187. THREE.Animation = function ( root, name, interpolationType ) {
  18188. this.root = root;
  18189. this.data = THREE.AnimationHandler.get( name );
  18190. this.hierarchy = THREE.AnimationHandler.parse( root );
  18191. this.currentTime = 0;
  18192. this.timeScale = 1;
  18193. this.isPlaying = false;
  18194. this.isPaused = true;
  18195. this.loop = true;
  18196. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  18197. this.points = [];
  18198. this.target = new THREE.Vector3();
  18199. };
  18200. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  18201. if ( this.isPlaying === false ) {
  18202. this.isPlaying = true;
  18203. this.loop = loop !== undefined ? loop : true;
  18204. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18205. // reset key cache
  18206. var h, hl = this.hierarchy.length,
  18207. object;
  18208. for ( h = 0; h < hl; h ++ ) {
  18209. object = this.hierarchy[ h ];
  18210. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18211. object.useQuaternion = true;
  18212. }
  18213. object.matrixAutoUpdate = true;
  18214. if ( object.animationCache === undefined ) {
  18215. object.animationCache = {};
  18216. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18217. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18218. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18219. }
  18220. var prevKey = object.animationCache.prevKey;
  18221. var nextKey = object.animationCache.nextKey;
  18222. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18223. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18224. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18225. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18226. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18227. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18228. }
  18229. this.update( 0 );
  18230. }
  18231. this.isPaused = false;
  18232. THREE.AnimationHandler.addToUpdate( this );
  18233. };
  18234. THREE.Animation.prototype.pause = function() {
  18235. if ( this.isPaused === true ) {
  18236. THREE.AnimationHandler.addToUpdate( this );
  18237. } else {
  18238. THREE.AnimationHandler.removeFromUpdate( this );
  18239. }
  18240. this.isPaused = !this.isPaused;
  18241. };
  18242. THREE.Animation.prototype.stop = function() {
  18243. this.isPlaying = false;
  18244. this.isPaused = false;
  18245. THREE.AnimationHandler.removeFromUpdate( this );
  18246. };
  18247. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  18248. // early out
  18249. if ( this.isPlaying === false ) return;
  18250. // vars
  18251. var types = [ "pos", "rot", "scl" ];
  18252. var type;
  18253. var scale;
  18254. var vector;
  18255. var prevXYZ, nextXYZ;
  18256. var prevKey, nextKey;
  18257. var object;
  18258. var animationCache;
  18259. var frame;
  18260. var JIThierarchy = this.data.JIT.hierarchy;
  18261. var currentTime, unloopedCurrentTime;
  18262. var currentPoint, forwardPoint, angle;
  18263. this.currentTime += deltaTimeMS * this.timeScale;
  18264. unloopedCurrentTime = this.currentTime;
  18265. currentTime = this.currentTime = this.currentTime % this.data.length;
  18266. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18267. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18268. object = this.hierarchy[ h ];
  18269. animationCache = object.animationCache;
  18270. // loop through pos/rot/scl
  18271. for ( var t = 0; t < 3; t ++ ) {
  18272. // get keys
  18273. type = types[ t ];
  18274. prevKey = animationCache.prevKey[ type ];
  18275. nextKey = animationCache.nextKey[ type ];
  18276. // switch keys?
  18277. if ( nextKey.time <= unloopedCurrentTime ) {
  18278. // did we loop?
  18279. if ( currentTime < unloopedCurrentTime ) {
  18280. if ( this.loop ) {
  18281. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18282. nextKey = this.getNextKeyWith( type, h, 1 );
  18283. while( nextKey.time < currentTime ) {
  18284. prevKey = nextKey;
  18285. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18286. }
  18287. } else {
  18288. this.stop();
  18289. return;
  18290. }
  18291. } else {
  18292. do {
  18293. prevKey = nextKey;
  18294. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18295. } while( nextKey.time < currentTime )
  18296. }
  18297. animationCache.prevKey[ type ] = prevKey;
  18298. animationCache.nextKey[ type ] = nextKey;
  18299. }
  18300. object.matrixAutoUpdate = true;
  18301. object.matrixWorldNeedsUpdate = true;
  18302. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18303. prevXYZ = prevKey[ type ];
  18304. nextXYZ = nextKey[ type ];
  18305. // check scale error
  18306. if ( scale < 0 || scale > 1 ) {
  18307. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18308. scale = scale < 0 ? 0 : 1;
  18309. }
  18310. // interpolate
  18311. if ( type === "pos" ) {
  18312. vector = object.position;
  18313. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18314. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18315. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18316. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18317. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18318. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18319. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18320. this.points[ 1 ] = prevXYZ;
  18321. this.points[ 2 ] = nextXYZ;
  18322. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18323. scale = scale * 0.33 + 0.33;
  18324. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18325. vector.x = currentPoint[ 0 ];
  18326. vector.y = currentPoint[ 1 ];
  18327. vector.z = currentPoint[ 2 ];
  18328. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18329. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18330. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18331. this.target.sub( vector );
  18332. this.target.y = 0;
  18333. this.target.normalize();
  18334. angle = Math.atan2( this.target.x, this.target.z );
  18335. object.rotation.set( 0, angle, 0 );
  18336. }
  18337. }
  18338. } else if ( type === "rot" ) {
  18339. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18340. } else if ( type === "scl" ) {
  18341. vector = object.scale;
  18342. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18343. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18344. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18345. }
  18346. }
  18347. }
  18348. };
  18349. // Catmull-Rom spline
  18350. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18351. var c = [], v3 = [],
  18352. point, intPoint, weight, w2, w3,
  18353. pa, pb, pc, pd;
  18354. point = ( points.length - 1 ) * scale;
  18355. intPoint = Math.floor( point );
  18356. weight = point - intPoint;
  18357. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18358. c[ 1 ] = intPoint;
  18359. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18360. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18361. pa = points[ c[ 0 ] ];
  18362. pb = points[ c[ 1 ] ];
  18363. pc = points[ c[ 2 ] ];
  18364. pd = points[ c[ 3 ] ];
  18365. w2 = weight * weight;
  18366. w3 = weight * w2;
  18367. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18368. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18369. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18370. return v3;
  18371. };
  18372. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18373. var v0 = ( p2 - p0 ) * 0.5,
  18374. v1 = ( p3 - p1 ) * 0.5;
  18375. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18376. };
  18377. // Get next key with
  18378. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18379. var keys = this.data.hierarchy[ h ].keys;
  18380. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18381. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18382. key = key < keys.length - 1 ? key : keys.length - 1;
  18383. } else {
  18384. key = key % keys.length;
  18385. }
  18386. for ( ; key < keys.length; key++ ) {
  18387. if ( keys[ key ][ type ] !== undefined ) {
  18388. return keys[ key ];
  18389. }
  18390. }
  18391. return this.data.hierarchy[ h ].keys[ 0 ];
  18392. };
  18393. // Get previous key with
  18394. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18395. var keys = this.data.hierarchy[ h ].keys;
  18396. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18397. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18398. key = key > 0 ? key : 0;
  18399. } else {
  18400. key = key >= 0 ? key : key + keys.length;
  18401. }
  18402. for ( ; key >= 0; key -- ) {
  18403. if ( keys[ key ][ type ] !== undefined ) {
  18404. return keys[ key ];
  18405. }
  18406. }
  18407. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18408. };
  18409. /**
  18410. * @author mikael emtinger / http://gomo.se/
  18411. * @author mrdoob / http://mrdoob.com/
  18412. * @author alteredq / http://alteredqualia.com/
  18413. * @author khang duong
  18414. * @author erik kitson
  18415. */
  18416. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18417. this.root = root;
  18418. this.data = THREE.AnimationHandler.get( data );
  18419. this.hierarchy = THREE.AnimationHandler.parse( root );
  18420. this.currentTime = 0;
  18421. this.timeScale = 0.001;
  18422. this.isPlaying = false;
  18423. this.isPaused = true;
  18424. this.loop = true;
  18425. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18426. // initialize to first keyframes
  18427. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18428. var keys = this.data.hierarchy[h].keys,
  18429. sids = this.data.hierarchy[h].sids,
  18430. obj = this.hierarchy[h];
  18431. if ( keys.length && sids ) {
  18432. for ( var s = 0; s < sids.length; s++ ) {
  18433. var sid = sids[ s ],
  18434. next = this.getNextKeyWith( sid, h, 0 );
  18435. if ( next ) {
  18436. next.apply( sid );
  18437. }
  18438. }
  18439. obj.matrixAutoUpdate = false;
  18440. this.data.hierarchy[h].node.updateMatrix();
  18441. obj.matrixWorldNeedsUpdate = true;
  18442. }
  18443. }
  18444. };
  18445. // Play
  18446. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18447. if( !this.isPlaying ) {
  18448. this.isPlaying = true;
  18449. this.loop = loop !== undefined ? loop : true;
  18450. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18451. this.startTimeMs = startTimeMS;
  18452. this.startTime = 10000000;
  18453. this.endTime = -this.startTime;
  18454. // reset key cache
  18455. var h, hl = this.hierarchy.length,
  18456. object,
  18457. node;
  18458. for ( h = 0; h < hl; h++ ) {
  18459. object = this.hierarchy[ h ];
  18460. node = this.data.hierarchy[ h ];
  18461. object.useQuaternion = true;
  18462. if ( node.animationCache === undefined ) {
  18463. node.animationCache = {};
  18464. node.animationCache.prevKey = null;
  18465. node.animationCache.nextKey = null;
  18466. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18467. }
  18468. var keys = this.data.hierarchy[h].keys;
  18469. if (keys.length) {
  18470. node.animationCache.prevKey = keys[ 0 ];
  18471. node.animationCache.nextKey = keys[ 1 ];
  18472. this.startTime = Math.min( keys[0].time, this.startTime );
  18473. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18474. }
  18475. }
  18476. this.update( 0 );
  18477. }
  18478. this.isPaused = false;
  18479. THREE.AnimationHandler.addToUpdate( this );
  18480. };
  18481. // Pause
  18482. THREE.KeyFrameAnimation.prototype.pause = function() {
  18483. if( this.isPaused ) {
  18484. THREE.AnimationHandler.addToUpdate( this );
  18485. } else {
  18486. THREE.AnimationHandler.removeFromUpdate( this );
  18487. }
  18488. this.isPaused = !this.isPaused;
  18489. };
  18490. // Stop
  18491. THREE.KeyFrameAnimation.prototype.stop = function() {
  18492. this.isPlaying = false;
  18493. this.isPaused = false;
  18494. THREE.AnimationHandler.removeFromUpdate( this );
  18495. // reset JIT matrix and remove cache
  18496. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18497. var obj = this.hierarchy[ h ];
  18498. var node = this.data.hierarchy[ h ];
  18499. if ( node.animationCache !== undefined ) {
  18500. var original = node.animationCache.originalMatrix;
  18501. if( obj instanceof THREE.Bone ) {
  18502. original.copy( obj.skinMatrix );
  18503. obj.skinMatrix = original;
  18504. } else {
  18505. original.copy( obj.matrix );
  18506. obj.matrix = original;
  18507. }
  18508. delete node.animationCache;
  18509. }
  18510. }
  18511. };
  18512. // Update
  18513. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18514. // early out
  18515. if( !this.isPlaying ) return;
  18516. // vars
  18517. var prevKey, nextKey;
  18518. var object;
  18519. var node;
  18520. var frame;
  18521. var JIThierarchy = this.data.JIT.hierarchy;
  18522. var currentTime, unloopedCurrentTime;
  18523. var looped;
  18524. // update
  18525. this.currentTime += deltaTimeMS * this.timeScale;
  18526. unloopedCurrentTime = this.currentTime;
  18527. currentTime = this.currentTime = this.currentTime % this.data.length;
  18528. // if looped around, the current time should be based on the startTime
  18529. if ( currentTime < this.startTimeMs ) {
  18530. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18531. }
  18532. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18533. looped = currentTime < unloopedCurrentTime;
  18534. if ( looped && !this.loop ) {
  18535. // Set the animation to the last keyframes and stop
  18536. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18537. var keys = this.data.hierarchy[h].keys,
  18538. sids = this.data.hierarchy[h].sids,
  18539. end = keys.length-1,
  18540. obj = this.hierarchy[h];
  18541. if ( keys.length ) {
  18542. for ( var s = 0; s < sids.length; s++ ) {
  18543. var sid = sids[ s ],
  18544. prev = this.getPrevKeyWith( sid, h, end );
  18545. if ( prev ) {
  18546. prev.apply( sid );
  18547. }
  18548. }
  18549. this.data.hierarchy[h].node.updateMatrix();
  18550. obj.matrixWorldNeedsUpdate = true;
  18551. }
  18552. }
  18553. this.stop();
  18554. return;
  18555. }
  18556. // check pre-infinity
  18557. if ( currentTime < this.startTime ) {
  18558. return;
  18559. }
  18560. // update
  18561. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18562. object = this.hierarchy[ h ];
  18563. node = this.data.hierarchy[ h ];
  18564. var keys = node.keys,
  18565. animationCache = node.animationCache;
  18566. // use JIT?
  18567. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18568. if( object instanceof THREE.Bone ) {
  18569. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18570. object.matrixWorldNeedsUpdate = false;
  18571. } else {
  18572. object.matrix = JIThierarchy[ h ][ frame ];
  18573. object.matrixWorldNeedsUpdate = true;
  18574. }
  18575. // use interpolation
  18576. } else if ( keys.length ) {
  18577. // make sure so original matrix and not JIT matrix is set
  18578. if ( this.JITCompile && animationCache ) {
  18579. if( object instanceof THREE.Bone ) {
  18580. object.skinMatrix = animationCache.originalMatrix;
  18581. } else {
  18582. object.matrix = animationCache.originalMatrix;
  18583. }
  18584. }
  18585. prevKey = animationCache.prevKey;
  18586. nextKey = animationCache.nextKey;
  18587. if ( prevKey && nextKey ) {
  18588. // switch keys?
  18589. if ( nextKey.time <= unloopedCurrentTime ) {
  18590. // did we loop?
  18591. if ( looped && this.loop ) {
  18592. prevKey = keys[ 0 ];
  18593. nextKey = keys[ 1 ];
  18594. while ( nextKey.time < currentTime ) {
  18595. prevKey = nextKey;
  18596. nextKey = keys[ prevKey.index + 1 ];
  18597. }
  18598. } else if ( !looped ) {
  18599. var lastIndex = keys.length - 1;
  18600. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18601. prevKey = nextKey;
  18602. nextKey = keys[ prevKey.index + 1 ];
  18603. }
  18604. }
  18605. animationCache.prevKey = prevKey;
  18606. animationCache.nextKey = nextKey;
  18607. }
  18608. if(nextKey.time >= currentTime)
  18609. prevKey.interpolate( nextKey, currentTime );
  18610. else
  18611. prevKey.interpolate( nextKey, nextKey.time);
  18612. }
  18613. this.data.hierarchy[h].node.updateMatrix();
  18614. object.matrixWorldNeedsUpdate = true;
  18615. }
  18616. }
  18617. // update JIT?
  18618. if ( this.JITCompile ) {
  18619. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18620. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18621. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18622. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18623. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18624. } else {
  18625. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18626. }
  18627. }
  18628. }
  18629. }
  18630. };
  18631. // Get next key with
  18632. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18633. var keys = this.data.hierarchy[ h ].keys;
  18634. key = key % keys.length;
  18635. for ( ; key < keys.length; key++ ) {
  18636. if ( keys[ key ].hasTarget( sid ) ) {
  18637. return keys[ key ];
  18638. }
  18639. }
  18640. return keys[ 0 ];
  18641. };
  18642. // Get previous key with
  18643. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18644. var keys = this.data.hierarchy[ h ].keys;
  18645. key = key >= 0 ? key : key + keys.length;
  18646. for ( ; key >= 0; key-- ) {
  18647. if ( keys[ key ].hasTarget( sid ) ) {
  18648. return keys[ key ];
  18649. }
  18650. }
  18651. return keys[ keys.length - 1 ];
  18652. };
  18653. /**
  18654. * Camera for rendering cube maps
  18655. * - renders scene into axis-aligned cube
  18656. *
  18657. * @author alteredq / http://alteredqualia.com/
  18658. */
  18659. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18660. THREE.Object3D.call( this );
  18661. var fov = 90, aspect = 1;
  18662. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18663. cameraPX.up.set( 0, -1, 0 );
  18664. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18665. this.add( cameraPX );
  18666. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18667. cameraNX.up.set( 0, -1, 0 );
  18668. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18669. this.add( cameraNX );
  18670. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18671. cameraPY.up.set( 0, 0, 1 );
  18672. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18673. this.add( cameraPY );
  18674. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18675. cameraNY.up.set( 0, 0, -1 );
  18676. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18677. this.add( cameraNY );
  18678. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18679. cameraPZ.up.set( 0, -1, 0 );
  18680. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18681. this.add( cameraPZ );
  18682. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18683. cameraNZ.up.set( 0, -1, 0 );
  18684. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18685. this.add( cameraNZ );
  18686. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18687. this.updateCubeMap = function ( renderer, scene ) {
  18688. var renderTarget = this.renderTarget;
  18689. var generateMipmaps = renderTarget.generateMipmaps;
  18690. renderTarget.generateMipmaps = false;
  18691. renderTarget.activeCubeFace = 0;
  18692. renderer.render( scene, cameraPX, renderTarget );
  18693. renderTarget.activeCubeFace = 1;
  18694. renderer.render( scene, cameraNX, renderTarget );
  18695. renderTarget.activeCubeFace = 2;
  18696. renderer.render( scene, cameraPY, renderTarget );
  18697. renderTarget.activeCubeFace = 3;
  18698. renderer.render( scene, cameraNY, renderTarget );
  18699. renderTarget.activeCubeFace = 4;
  18700. renderer.render( scene, cameraPZ, renderTarget );
  18701. renderTarget.generateMipmaps = generateMipmaps;
  18702. renderTarget.activeCubeFace = 5;
  18703. renderer.render( scene, cameraNZ, renderTarget );
  18704. };
  18705. };
  18706. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18707. /*
  18708. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18709. *
  18710. * A general perpose camera, for setting FOV, Lens Focal Length,
  18711. * and switching between perspective and orthographic views easily.
  18712. * Use this only if you do not wish to manage
  18713. * both a Orthographic and Perspective Camera
  18714. *
  18715. */
  18716. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18717. THREE.Camera.call( this );
  18718. this.fov = fov;
  18719. this.left = -width / 2;
  18720. this.right = width / 2
  18721. this.top = height / 2;
  18722. this.bottom = -height / 2;
  18723. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18724. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18725. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18726. this.zoom = 1;
  18727. this.toPerspective();
  18728. var aspect = width/height;
  18729. };
  18730. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18731. THREE.CombinedCamera.prototype.toPerspective = function () {
  18732. // Switches to the Perspective Camera
  18733. this.near = this.cameraP.near;
  18734. this.far = this.cameraP.far;
  18735. this.cameraP.fov = this.fov / this.zoom ;
  18736. this.cameraP.updateProjectionMatrix();
  18737. this.projectionMatrix = this.cameraP.projectionMatrix;
  18738. this.inPerspectiveMode = true;
  18739. this.inOrthographicMode = false;
  18740. };
  18741. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18742. // Switches to the Orthographic camera estimating viewport from Perspective
  18743. var fov = this.fov;
  18744. var aspect = this.cameraP.aspect;
  18745. var near = this.cameraP.near;
  18746. var far = this.cameraP.far;
  18747. // The size that we set is the mid plane of the viewing frustum
  18748. var hyperfocus = ( near + far ) / 2;
  18749. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18750. var planeHeight = 2 * halfHeight;
  18751. var planeWidth = planeHeight * aspect;
  18752. var halfWidth = planeWidth / 2;
  18753. halfHeight /= this.zoom;
  18754. halfWidth /= this.zoom;
  18755. this.cameraO.left = -halfWidth;
  18756. this.cameraO.right = halfWidth;
  18757. this.cameraO.top = halfHeight;
  18758. this.cameraO.bottom = -halfHeight;
  18759. // this.cameraO.left = -farHalfWidth;
  18760. // this.cameraO.right = farHalfWidth;
  18761. // this.cameraO.top = farHalfHeight;
  18762. // this.cameraO.bottom = -farHalfHeight;
  18763. // this.cameraO.left = this.left / this.zoom;
  18764. // this.cameraO.right = this.right / this.zoom;
  18765. // this.cameraO.top = this.top / this.zoom;
  18766. // this.cameraO.bottom = this.bottom / this.zoom;
  18767. this.cameraO.updateProjectionMatrix();
  18768. this.near = this.cameraO.near;
  18769. this.far = this.cameraO.far;
  18770. this.projectionMatrix = this.cameraO.projectionMatrix;
  18771. this.inPerspectiveMode = false;
  18772. this.inOrthographicMode = true;
  18773. };
  18774. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18775. this.cameraP.aspect = width / height;
  18776. this.left = -width / 2;
  18777. this.right = width / 2
  18778. this.top = height / 2;
  18779. this.bottom = -height / 2;
  18780. };
  18781. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18782. this.fov = fov;
  18783. if ( this.inPerspectiveMode ) {
  18784. this.toPerspective();
  18785. } else {
  18786. this.toOrthographic();
  18787. }
  18788. };
  18789. // For mantaining similar API with PerspectiveCamera
  18790. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18791. if ( this.inPerspectiveMode ) {
  18792. this.toPerspective();
  18793. } else {
  18794. this.toPerspective();
  18795. this.toOrthographic();
  18796. }
  18797. };
  18798. /*
  18799. * Uses Focal Length (in mm) to estimate and set FOV
  18800. * 35mm (fullframe) camera is used if frame size is not specified;
  18801. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18802. */
  18803. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18804. if ( frameHeight === undefined ) frameHeight = 24;
  18805. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18806. this.setFov( fov );
  18807. return fov;
  18808. };
  18809. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18810. this.zoom = zoom;
  18811. if ( this.inPerspectiveMode ) {
  18812. this.toPerspective();
  18813. } else {
  18814. this.toOrthographic();
  18815. }
  18816. };
  18817. THREE.CombinedCamera.prototype.toFrontView = function() {
  18818. this.rotation.x = 0;
  18819. this.rotation.y = 0;
  18820. this.rotation.z = 0;
  18821. // should we be modifing the matrix instead?
  18822. this.rotationAutoUpdate = false;
  18823. };
  18824. THREE.CombinedCamera.prototype.toBackView = function() {
  18825. this.rotation.x = 0;
  18826. this.rotation.y = Math.PI;
  18827. this.rotation.z = 0;
  18828. this.rotationAutoUpdate = false;
  18829. };
  18830. THREE.CombinedCamera.prototype.toLeftView = function() {
  18831. this.rotation.x = 0;
  18832. this.rotation.y = - Math.PI / 2;
  18833. this.rotation.z = 0;
  18834. this.rotationAutoUpdate = false;
  18835. };
  18836. THREE.CombinedCamera.prototype.toRightView = function() {
  18837. this.rotation.x = 0;
  18838. this.rotation.y = Math.PI / 2;
  18839. this.rotation.z = 0;
  18840. this.rotationAutoUpdate = false;
  18841. };
  18842. THREE.CombinedCamera.prototype.toTopView = function() {
  18843. this.rotation.x = - Math.PI / 2;
  18844. this.rotation.y = 0;
  18845. this.rotation.z = 0;
  18846. this.rotationAutoUpdate = false;
  18847. };
  18848. THREE.CombinedCamera.prototype.toBottomView = function() {
  18849. this.rotation.x = Math.PI / 2;
  18850. this.rotation.y = 0;
  18851. this.rotation.z = 0;
  18852. this.rotationAutoUpdate = false;
  18853. };
  18854. /**
  18855. * @author hughes
  18856. */
  18857. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18858. THREE.Geometry.call( this );
  18859. radius = radius || 50;
  18860. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18861. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18862. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18863. var i, uvs = [],
  18864. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18865. this.vertices.push(center);
  18866. uvs.push( centerUV );
  18867. for ( i = 0; i <= segments; i ++ ) {
  18868. var vertex = new THREE.Vector3();
  18869. var segment = thetaStart + i / segments * thetaLength;
  18870. vertex.x = radius * Math.cos( segment );
  18871. vertex.y = radius * Math.sin( segment );
  18872. this.vertices.push( vertex );
  18873. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18874. }
  18875. var n = new THREE.Vector3( 0, 0, 1 );
  18876. for ( i = 1; i <= segments; i ++ ) {
  18877. var v1 = i;
  18878. var v2 = i + 1 ;
  18879. var v3 = 0;
  18880. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18881. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18882. }
  18883. this.computeCentroids();
  18884. this.computeFaceNormals();
  18885. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18886. };
  18887. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18888. /**
  18889. * @author mrdoob / http://mrdoob.com/
  18890. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18891. */
  18892. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18893. THREE.Geometry.call( this );
  18894. var scope = this;
  18895. this.width = width;
  18896. this.height = height;
  18897. this.depth = depth;
  18898. this.widthSegments = widthSegments || 1;
  18899. this.heightSegments = heightSegments || 1;
  18900. this.depthSegments = depthSegments || 1;
  18901. var width_half = this.width / 2;
  18902. var height_half = this.height / 2;
  18903. var depth_half = this.depth / 2;
  18904. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18905. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18906. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18907. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18908. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18909. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18910. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18911. var w, ix, iy,
  18912. gridX = scope.widthSegments,
  18913. gridY = scope.heightSegments,
  18914. width_half = width / 2,
  18915. height_half = height / 2,
  18916. offset = scope.vertices.length;
  18917. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18918. w = 'z';
  18919. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18920. w = 'y';
  18921. gridY = scope.depthSegments;
  18922. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18923. w = 'x';
  18924. gridX = scope.depthSegments;
  18925. }
  18926. var gridX1 = gridX + 1,
  18927. gridY1 = gridY + 1,
  18928. segment_width = width / gridX,
  18929. segment_height = height / gridY,
  18930. normal = new THREE.Vector3();
  18931. normal[ w ] = depth > 0 ? 1 : - 1;
  18932. for ( iy = 0; iy < gridY1; iy ++ ) {
  18933. for ( ix = 0; ix < gridX1; ix ++ ) {
  18934. var vector = new THREE.Vector3();
  18935. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18936. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18937. vector[ w ] = depth;
  18938. scope.vertices.push( vector );
  18939. }
  18940. }
  18941. for ( iy = 0; iy < gridY; iy++ ) {
  18942. for ( ix = 0; ix < gridX; ix++ ) {
  18943. var a = ix + gridX1 * iy;
  18944. var b = ix + gridX1 * ( iy + 1 );
  18945. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18946. var d = ( ix + 1 ) + gridX1 * iy;
  18947. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18948. face.normal.copy( normal );
  18949. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18950. face.materialIndex = materialIndex;
  18951. scope.faces.push( face );
  18952. scope.faceVertexUvs[ 0 ].push( [
  18953. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18954. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18955. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18956. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18957. ] );
  18958. }
  18959. }
  18960. }
  18961. this.computeCentroids();
  18962. this.mergeVertices();
  18963. };
  18964. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18965. /**
  18966. * @author mrdoob / http://mrdoob.com/
  18967. */
  18968. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18969. THREE.Geometry.call( this );
  18970. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18971. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18972. this.height = height = height !== undefined ? height : 100;
  18973. this.radialSegments = radialSegments = radialSegments || 8;
  18974. this.heightSegments = heightSegments = heightSegments || 1;
  18975. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18976. var heightHalf = height / 2;
  18977. var x, y, vertices = [], uvs = [];
  18978. for ( y = 0; y <= heightSegments; y ++ ) {
  18979. var verticesRow = [];
  18980. var uvsRow = [];
  18981. var v = y / heightSegments;
  18982. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18983. for ( x = 0; x <= radialSegments; x ++ ) {
  18984. var u = x / radialSegments;
  18985. var vertex = new THREE.Vector3();
  18986. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18987. vertex.y = - v * height + heightHalf;
  18988. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18989. this.vertices.push( vertex );
  18990. verticesRow.push( this.vertices.length - 1 );
  18991. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18992. }
  18993. vertices.push( verticesRow );
  18994. uvs.push( uvsRow );
  18995. }
  18996. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18997. var na, nb;
  18998. for ( x = 0; x < radialSegments; x ++ ) {
  18999. if ( radiusTop !== 0 ) {
  19000. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19001. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19002. } else {
  19003. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19004. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19005. }
  19006. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19007. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19008. for ( y = 0; y < heightSegments; y ++ ) {
  19009. var v1 = vertices[ y ][ x ];
  19010. var v2 = vertices[ y + 1 ][ x ];
  19011. var v3 = vertices[ y + 1 ][ x + 1 ];
  19012. var v4 = vertices[ y ][ x + 1 ];
  19013. var n1 = na.clone();
  19014. var n2 = na.clone();
  19015. var n3 = nb.clone();
  19016. var n4 = nb.clone();
  19017. var uv1 = uvs[ y ][ x ].clone();
  19018. var uv2 = uvs[ y + 1 ][ x ].clone();
  19019. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19020. var uv4 = uvs[ y ][ x + 1 ].clone();
  19021. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19022. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19023. }
  19024. }
  19025. // top cap
  19026. if ( openEnded === false && radiusTop > 0 ) {
  19027. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19028. for ( x = 0; x < radialSegments; x ++ ) {
  19029. var v1 = vertices[ 0 ][ x ];
  19030. var v2 = vertices[ 0 ][ x + 1 ];
  19031. var v3 = this.vertices.length - 1;
  19032. var n1 = new THREE.Vector3( 0, 1, 0 );
  19033. var n2 = new THREE.Vector3( 0, 1, 0 );
  19034. var n3 = new THREE.Vector3( 0, 1, 0 );
  19035. var uv1 = uvs[ 0 ][ x ].clone();
  19036. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19037. var uv3 = new THREE.Vector2( uv2.u, 0 );
  19038. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19039. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19040. }
  19041. }
  19042. // bottom cap
  19043. if ( openEnded === false && radiusBottom > 0 ) {
  19044. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19045. for ( x = 0; x < radialSegments; x ++ ) {
  19046. var v1 = vertices[ y ][ x + 1 ];
  19047. var v2 = vertices[ y ][ x ];
  19048. var v3 = this.vertices.length - 1;
  19049. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19050. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19051. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19052. var uv1 = uvs[ y ][ x + 1 ].clone();
  19053. var uv2 = uvs[ y ][ x ].clone();
  19054. var uv3 = new THREE.Vector2( uv2.u, 1 );
  19055. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19056. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19057. }
  19058. }
  19059. this.computeCentroids();
  19060. this.computeFaceNormals();
  19061. }
  19062. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19063. /**
  19064. * @author zz85 / http://www.lab4games.net/zz85/blog
  19065. *
  19066. * Creates extruded geometry from a path shape.
  19067. *
  19068. * parameters = {
  19069. *
  19070. * size: <float>, // size of the text
  19071. * height: <float>, // thickness to extrude text
  19072. * curveSegments: <int>, // number of points on the curves
  19073. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19074. * amount: <int>, // Amount
  19075. *
  19076. * bevelEnabled: <bool>, // turn on bevel
  19077. * bevelThickness: <float>, // how deep into text bevel goes
  19078. * bevelSize: <float>, // how far from text outline is bevel
  19079. * bevelSegments: <int>, // number of bevel layers
  19080. *
  19081. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19082. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19083. *
  19084. * material: <int> // material index for front and back faces
  19085. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19086. * uvGenerator: <Object> // object that provides UV generator functions
  19087. *
  19088. * }
  19089. **/
  19090. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19091. if ( typeof( shapes ) === "undefined" ) {
  19092. shapes = [];
  19093. return;
  19094. }
  19095. THREE.Geometry.call( this );
  19096. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19097. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19098. this.addShapeList( shapes, options );
  19099. this.computeCentroids();
  19100. this.computeFaceNormals();
  19101. // can't really use automatic vertex normals
  19102. // as then front and back sides get smoothed too
  19103. // should do separate smoothing just for sides
  19104. //this.computeVertexNormals();
  19105. //console.log( "took", ( Date.now() - startTime ) );
  19106. };
  19107. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19108. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19109. var sl = shapes.length;
  19110. for ( var s = 0; s < sl; s ++ ) {
  19111. var shape = shapes[ s ];
  19112. this.addShape( shape, options );
  19113. }
  19114. };
  19115. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19116. var amount = options.amount !== undefined ? options.amount : 100;
  19117. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19118. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19119. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19120. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19121. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19122. var steps = options.steps !== undefined ? options.steps : 1;
  19123. var extrudePath = options.extrudePath;
  19124. var extrudePts, extrudeByPath = false;
  19125. var material = options.material;
  19126. var extrudeMaterial = options.extrudeMaterial;
  19127. // Use default WorldUVGenerator if no UV generators are specified.
  19128. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19129. var shapebb = this.shapebb;
  19130. //shapebb = shape.getBoundingBox();
  19131. var splineTube, binormal, normal, position2;
  19132. if ( extrudePath ) {
  19133. extrudePts = extrudePath.getSpacedPoints( steps );
  19134. extrudeByPath = true;
  19135. bevelEnabled = false; // bevels not supported for path extrusion
  19136. // SETUP TNB variables
  19137. // Reuse TNB from TubeGeomtry for now.
  19138. // TODO1 - have a .isClosed in spline?
  19139. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19140. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19141. binormal = new THREE.Vector3();
  19142. normal = new THREE.Vector3();
  19143. position2 = new THREE.Vector3();
  19144. }
  19145. // Safeguards if bevels are not enabled
  19146. if ( ! bevelEnabled ) {
  19147. bevelSegments = 0;
  19148. bevelThickness = 0;
  19149. bevelSize = 0;
  19150. }
  19151. // Variables initalization
  19152. var ahole, h, hl; // looping of holes
  19153. var scope = this;
  19154. var bevelPoints = [];
  19155. var shapesOffset = this.vertices.length;
  19156. var shapePoints = shape.extractPoints( curveSegments );
  19157. var vertices = shapePoints.shape;
  19158. var holes = shapePoints.holes;
  19159. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19160. if ( reverse ) {
  19161. vertices = vertices.reverse();
  19162. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19163. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19164. ahole = holes[ h ];
  19165. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19166. holes[ h ] = ahole.reverse();
  19167. }
  19168. }
  19169. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19170. }
  19171. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19172. /* Vertices */
  19173. var contour = vertices; // vertices has all points but contour has only points of circumference
  19174. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19175. ahole = holes[ h ];
  19176. vertices = vertices.concat( ahole );
  19177. }
  19178. function scalePt2 ( pt, vec, size ) {
  19179. if ( !vec ) console.log( "die" );
  19180. return vec.clone().multiplyScalar( size ).add( pt );
  19181. }
  19182. var b, bs, t, z,
  19183. vert, vlen = vertices.length,
  19184. face, flen = faces.length,
  19185. cont, clen = contour.length;
  19186. // Find directions for point movement
  19187. var RAD_TO_DEGREES = 180 / Math.PI;
  19188. function getBevelVec( pt_i, pt_j, pt_k ) {
  19189. // Algorithm 2
  19190. return getBevelVec2( pt_i, pt_j, pt_k );
  19191. }
  19192. function getBevelVec1( pt_i, pt_j, pt_k ) {
  19193. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  19194. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  19195. if ( anglea > angleb ) {
  19196. angleb += Math.PI * 2;
  19197. }
  19198. var anglec = ( anglea + angleb ) / 2;
  19199. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  19200. var x = - Math.cos( anglec );
  19201. var y = - Math.sin( anglec );
  19202. var vec = new THREE.Vector2( x, y ); //.normalize();
  19203. return vec;
  19204. }
  19205. function getBevelVec2( pt_i, pt_j, pt_k ) {
  19206. var a = THREE.ExtrudeGeometry.__v1,
  19207. b = THREE.ExtrudeGeometry.__v2,
  19208. v_hat = THREE.ExtrudeGeometry.__v3,
  19209. w_hat = THREE.ExtrudeGeometry.__v4,
  19210. p = THREE.ExtrudeGeometry.__v5,
  19211. q = THREE.ExtrudeGeometry.__v6,
  19212. v, w,
  19213. v_dot_w_hat, q_sub_p_dot_w_hat,
  19214. s, intersection;
  19215. // good reading for line-line intersection
  19216. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  19217. // define a as vector j->i
  19218. // define b as vectot k->i
  19219. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  19220. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  19221. // get unit vectors
  19222. v = a.normalize();
  19223. w = b.normalize();
  19224. // normals from pt i
  19225. v_hat.set( -v.y, v.x );
  19226. w_hat.set( w.y, -w.x );
  19227. // pts from i
  19228. p.copy( pt_i ).add( v_hat );
  19229. q.copy( pt_i ).add( w_hat );
  19230. if ( p.equals( q ) ) {
  19231. //console.log("Warning: lines are straight");
  19232. return w_hat.clone();
  19233. }
  19234. // Points from j, k. helps prevents points cross overover most of the time
  19235. p.copy( pt_j ).add( v_hat );
  19236. q.copy( pt_k ).add( w_hat );
  19237. v_dot_w_hat = v.dot( w_hat );
  19238. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  19239. // We should not reach these conditions
  19240. if ( v_dot_w_hat === 0 ) {
  19241. console.log( "Either infinite or no solutions!" );
  19242. if ( q_sub_p_dot_w_hat === 0 ) {
  19243. console.log( "Its finite solutions." );
  19244. } else {
  19245. console.log( "Too bad, no solutions." );
  19246. }
  19247. }
  19248. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19249. if ( s < 0 ) {
  19250. // in case of emergecy, revert to algorithm 1.
  19251. return getBevelVec1( pt_i, pt_j, pt_k );
  19252. }
  19253. intersection = v.multiplyScalar( s ).add( p );
  19254. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19255. }
  19256. var contourMovements = [];
  19257. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19258. if ( j === il ) j = 0;
  19259. if ( k === il ) k = 0;
  19260. // (j)---(i)---(k)
  19261. // console.log('i,j,k', i, j , k)
  19262. var pt_i = contour[ i ];
  19263. var pt_j = contour[ j ];
  19264. var pt_k = contour[ k ];
  19265. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19266. }
  19267. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19268. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19269. ahole = holes[ h ];
  19270. oneHoleMovements = [];
  19271. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19272. if ( j === il ) j = 0;
  19273. if ( k === il ) k = 0;
  19274. // (j)---(i)---(k)
  19275. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19276. }
  19277. holesMovements.push( oneHoleMovements );
  19278. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19279. }
  19280. // Loop bevelSegments, 1 for the front, 1 for the back
  19281. for ( b = 0; b < bevelSegments; b ++ ) {
  19282. //for ( b = bevelSegments; b > 0; b -- ) {
  19283. t = b / bevelSegments;
  19284. z = bevelThickness * ( 1 - t );
  19285. //z = bevelThickness * t;
  19286. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19287. //bs = bevelSize * t ; // linear
  19288. // contract shape
  19289. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19290. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19291. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19292. v( vert.x, vert.y, - z );
  19293. }
  19294. // expand holes
  19295. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19296. ahole = holes[ h ];
  19297. oneHoleMovements = holesMovements[ h ];
  19298. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19299. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19300. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19301. v( vert.x, vert.y, -z );
  19302. }
  19303. }
  19304. }
  19305. bs = bevelSize;
  19306. // Back facing vertices
  19307. for ( i = 0; i < vlen; i ++ ) {
  19308. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19309. if ( !extrudeByPath ) {
  19310. v( vert.x, vert.y, 0 );
  19311. } else {
  19312. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19313. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19314. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19315. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19316. v( position2.x, position2.y, position2.z );
  19317. }
  19318. }
  19319. // Add stepped vertices...
  19320. // Including front facing vertices
  19321. var s;
  19322. for ( s = 1; s <= steps; s ++ ) {
  19323. for ( i = 0; i < vlen; i ++ ) {
  19324. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19325. if ( !extrudeByPath ) {
  19326. v( vert.x, vert.y, amount / steps * s );
  19327. } else {
  19328. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19329. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19330. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19331. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19332. v( position2.x, position2.y, position2.z );
  19333. }
  19334. }
  19335. }
  19336. // Add bevel segments planes
  19337. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19338. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19339. t = b / bevelSegments;
  19340. z = bevelThickness * ( 1 - t );
  19341. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19342. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19343. // contract shape
  19344. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19345. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19346. v( vert.x, vert.y, amount + z );
  19347. }
  19348. // expand holes
  19349. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19350. ahole = holes[ h ];
  19351. oneHoleMovements = holesMovements[ h ];
  19352. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19353. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19354. if ( !extrudeByPath ) {
  19355. v( vert.x, vert.y, amount + z );
  19356. } else {
  19357. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19358. }
  19359. }
  19360. }
  19361. }
  19362. /* Faces */
  19363. // Top and bottom faces
  19364. buildLidFaces();
  19365. // Sides faces
  19366. buildSideFaces();
  19367. ///// Internal functions
  19368. function buildLidFaces() {
  19369. if ( bevelEnabled ) {
  19370. var layer = 0 ; // steps + 1
  19371. var offset = vlen * layer;
  19372. // Bottom faces
  19373. for ( i = 0; i < flen; i ++ ) {
  19374. face = faces[ i ];
  19375. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19376. }
  19377. layer = steps + bevelSegments * 2;
  19378. offset = vlen * layer;
  19379. // Top faces
  19380. for ( i = 0; i < flen; i ++ ) {
  19381. face = faces[ i ];
  19382. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19383. }
  19384. } else {
  19385. // Bottom faces
  19386. for ( i = 0; i < flen; i++ ) {
  19387. face = faces[ i ];
  19388. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19389. }
  19390. // Top faces
  19391. for ( i = 0; i < flen; i ++ ) {
  19392. face = faces[ i ];
  19393. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19394. }
  19395. }
  19396. }
  19397. // Create faces for the z-sides of the shape
  19398. function buildSideFaces() {
  19399. var layeroffset = 0;
  19400. sidewalls( contour, layeroffset );
  19401. layeroffset += contour.length;
  19402. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19403. ahole = holes[ h ];
  19404. sidewalls( ahole, layeroffset );
  19405. //, true
  19406. layeroffset += ahole.length;
  19407. }
  19408. }
  19409. function sidewalls( contour, layeroffset ) {
  19410. var j, k;
  19411. i = contour.length;
  19412. while ( --i >= 0 ) {
  19413. j = i;
  19414. k = i - 1;
  19415. if ( k < 0 ) k = contour.length - 1;
  19416. //console.log('b', i,j, i-1, k,vertices.length);
  19417. var s = 0, sl = steps + bevelSegments * 2;
  19418. for ( s = 0; s < sl; s ++ ) {
  19419. var slen1 = vlen * s;
  19420. var slen2 = vlen * ( s + 1 );
  19421. var a = layeroffset + j + slen1,
  19422. b = layeroffset + k + slen1,
  19423. c = layeroffset + k + slen2,
  19424. d = layeroffset + j + slen2;
  19425. f4( a, b, c, d, contour, s, sl, j, k );
  19426. }
  19427. }
  19428. }
  19429. function v( x, y, z ) {
  19430. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19431. }
  19432. function f3( a, b, c, isBottom ) {
  19433. a += shapesOffset;
  19434. b += shapesOffset;
  19435. c += shapesOffset;
  19436. // normal, color, material
  19437. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19438. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19439. scope.faceVertexUvs[ 0 ].push( uvs );
  19440. }
  19441. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19442. a += shapesOffset;
  19443. b += shapesOffset;
  19444. c += shapesOffset;
  19445. d += shapesOffset;
  19446. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19447. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19448. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19449. scope.faceVertexUvs[ 0 ].push( uvs );
  19450. }
  19451. };
  19452. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19453. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19454. var ax = geometry.vertices[ indexA ].x,
  19455. ay = geometry.vertices[ indexA ].y,
  19456. bx = geometry.vertices[ indexB ].x,
  19457. by = geometry.vertices[ indexB ].y,
  19458. cx = geometry.vertices[ indexC ].x,
  19459. cy = geometry.vertices[ indexC ].y;
  19460. return [
  19461. new THREE.Vector2( ax, ay ),
  19462. new THREE.Vector2( bx, by ),
  19463. new THREE.Vector2( cx, cy )
  19464. ];
  19465. },
  19466. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19467. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19468. },
  19469. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19470. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19471. contourIndex1, contourIndex2 ) {
  19472. var ax = geometry.vertices[ indexA ].x,
  19473. ay = geometry.vertices[ indexA ].y,
  19474. az = geometry.vertices[ indexA ].z,
  19475. bx = geometry.vertices[ indexB ].x,
  19476. by = geometry.vertices[ indexB ].y,
  19477. bz = geometry.vertices[ indexB ].z,
  19478. cx = geometry.vertices[ indexC ].x,
  19479. cy = geometry.vertices[ indexC ].y,
  19480. cz = geometry.vertices[ indexC ].z,
  19481. dx = geometry.vertices[ indexD ].x,
  19482. dy = geometry.vertices[ indexD ].y,
  19483. dz = geometry.vertices[ indexD ].z;
  19484. if ( Math.abs( ay - by ) < 0.01 ) {
  19485. return [
  19486. new THREE.Vector2( ax, 1 - az ),
  19487. new THREE.Vector2( bx, 1 - bz ),
  19488. new THREE.Vector2( cx, 1 - cz ),
  19489. new THREE.Vector2( dx, 1 - dz )
  19490. ];
  19491. } else {
  19492. return [
  19493. new THREE.Vector2( ay, 1 - az ),
  19494. new THREE.Vector2( by, 1 - bz ),
  19495. new THREE.Vector2( cy, 1 - cz ),
  19496. new THREE.Vector2( dy, 1 - dz )
  19497. ];
  19498. }
  19499. }
  19500. };
  19501. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19502. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19503. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19504. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19505. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19506. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19507. /**
  19508. * @author jonobr1 / http://jonobr1.com
  19509. *
  19510. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19511. * ExtrudeGeometry.
  19512. *
  19513. * parameters = {
  19514. *
  19515. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19516. *
  19517. * material: <int> // material index for front and back faces
  19518. * uvGenerator: <Object> // object that provides UV generator functions
  19519. *
  19520. * }
  19521. **/
  19522. THREE.ShapeGeometry = function ( shapes, options ) {
  19523. THREE.Geometry.call( this );
  19524. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19525. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19526. this.addShapeList( shapes, options );
  19527. this.computeCentroids();
  19528. this.computeFaceNormals();
  19529. };
  19530. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19531. /**
  19532. * Add an array of shapes to THREE.ShapeGeometry.
  19533. */
  19534. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19535. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19536. this.addShape( shapes[ i ], options );
  19537. }
  19538. return this;
  19539. };
  19540. /**
  19541. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19542. */
  19543. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19544. if ( options === undefined ) options = {};
  19545. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19546. var material = options.material;
  19547. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19548. var shapebb = this.shapebb;
  19549. //
  19550. var i, l, hole, s;
  19551. var shapesOffset = this.vertices.length;
  19552. var shapePoints = shape.extractPoints( curveSegments );
  19553. var vertices = shapePoints.shape;
  19554. var holes = shapePoints.holes;
  19555. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19556. if ( reverse ) {
  19557. vertices = vertices.reverse();
  19558. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19559. for ( i = 0, l = holes.length; i < l; i++ ) {
  19560. hole = holes[ i ];
  19561. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19562. holes[ i ] = hole.reverse();
  19563. }
  19564. }
  19565. reverse = false;
  19566. }
  19567. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19568. // Vertices
  19569. var contour = vertices;
  19570. for ( i = 0, l = holes.length; i < l; i++ ) {
  19571. hole = holes[ i ];
  19572. vertices = vertices.concat( hole );
  19573. }
  19574. //
  19575. var vert, vlen = vertices.length;
  19576. var face, flen = faces.length;
  19577. var cont, clen = contour.length;
  19578. for ( i = 0; i < vlen; i++ ) {
  19579. vert = vertices[ i ];
  19580. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19581. }
  19582. for ( i = 0; i < flen; i++ ) {
  19583. face = faces[ i ];
  19584. var a = face[ 0 ] + shapesOffset;
  19585. var b = face[ 1 ] + shapesOffset;
  19586. var c = face[ 2 ] + shapesOffset;
  19587. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19588. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19589. }
  19590. };
  19591. /**
  19592. * @author astrodud / http://astrodud.isgreat.org/
  19593. * @author zz85 / https://github.com/zz85
  19594. * @author bhouston / http://exocortex.com
  19595. */
  19596. // points - to create a closed torus, one must use a set of points
  19597. // like so: [ a, b, c, d, a ], see first is the same as last.
  19598. // segments - the number of circumference segments to create
  19599. // phiStart - the starting radian
  19600. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19601. // 2*pi is a closed lathe, less than 2PI is a portion.
  19602. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19603. THREE.Geometry.call( this );
  19604. segments = segments || 12;
  19605. phiStart = phiStart || 0;
  19606. phiLength = phiLength || 2 * Math.PI;
  19607. var inversePointLength = 1.0 / ( points.length - 1 );
  19608. var inverseSegments = 1.0 / segments;
  19609. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19610. var phi = phiStart + i * inverseSegments * phiLength;
  19611. var c = Math.cos( phi ),
  19612. s = Math.sin( phi );
  19613. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19614. var pt = points[ j ];
  19615. var vertex = new THREE.Vector3();
  19616. vertex.x = c * pt.x - s * pt.y;
  19617. vertex.y = s * pt.x + c * pt.y;
  19618. vertex.z = pt.z;
  19619. this.vertices.push( vertex );
  19620. }
  19621. }
  19622. var np = points.length;
  19623. for ( var i = 0, il = segments; i < il; i ++ ) {
  19624. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19625. var base = j + np * i;
  19626. var a = base;
  19627. var b = base + np;
  19628. var c = base + 1 + np;
  19629. var d = base + 1;
  19630. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19631. var u0 = i * inverseSegments;
  19632. var v0 = j * inversePointLength;
  19633. var u1 = u0 + inverseSegments;
  19634. var v1 = v0 + inversePointLength;
  19635. this.faceVertexUvs[ 0 ].push( [
  19636. new THREE.Vector2( u0, v0 ),
  19637. new THREE.Vector2( u1, v0 ),
  19638. new THREE.Vector2( u1, v1 ),
  19639. new THREE.Vector2( u0, v1 )
  19640. ] );
  19641. }
  19642. }
  19643. this.mergeVertices();
  19644. this.computeCentroids();
  19645. this.computeFaceNormals();
  19646. this.computeVertexNormals();
  19647. };
  19648. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19649. /**
  19650. * @author mrdoob / http://mrdoob.com/
  19651. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19652. */
  19653. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19654. THREE.Geometry.call( this );
  19655. this.width = width;
  19656. this.height = height;
  19657. this.widthSegments = widthSegments || 1;
  19658. this.heightSegments = heightSegments || 1;
  19659. var ix, iz;
  19660. var width_half = width / 2;
  19661. var height_half = height / 2;
  19662. var gridX = this.widthSegments;
  19663. var gridZ = this.heightSegments;
  19664. var gridX1 = gridX + 1;
  19665. var gridZ1 = gridZ + 1;
  19666. var segment_width = this.width / gridX;
  19667. var segment_height = this.height / gridZ;
  19668. var normal = new THREE.Vector3( 0, 0, 1 );
  19669. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19670. for ( ix = 0; ix < gridX1; ix ++ ) {
  19671. var x = ix * segment_width - width_half;
  19672. var y = iz * segment_height - height_half;
  19673. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19674. }
  19675. }
  19676. for ( iz = 0; iz < gridZ; iz ++ ) {
  19677. for ( ix = 0; ix < gridX; ix ++ ) {
  19678. var a = ix + gridX1 * iz;
  19679. var b = ix + gridX1 * ( iz + 1 );
  19680. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19681. var d = ( ix + 1 ) + gridX1 * iz;
  19682. var face = new THREE.Face4( a, b, c, d );
  19683. face.normal.copy( normal );
  19684. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19685. this.faces.push( face );
  19686. this.faceVertexUvs[ 0 ].push( [
  19687. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19688. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19689. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19690. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19691. ] );
  19692. }
  19693. }
  19694. this.computeCentroids();
  19695. };
  19696. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19697. /**
  19698. * @author Kaleb Murphy
  19699. */
  19700. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19701. THREE.Geometry.call( this );
  19702. innerRadius = innerRadius || 0;
  19703. outerRadius = outerRadius || 50;
  19704. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19705. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19706. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19707. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19708. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19709. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19710. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19711. var vertex = new THREE.Vector3();
  19712. var segment = thetaStart + o / thetaSegments * thetaLength;
  19713. vertex.x = radius * Math.cos( segment );
  19714. vertex.y = radius * Math.sin( segment );
  19715. this.vertices.push( vertex );
  19716. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19717. }
  19718. radius += radiusStep;
  19719. }
  19720. var n = new THREE.Vector3( 0, 0, 1 );
  19721. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19722. var thetaSegment = i * thetaSegments;
  19723. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19724. var segment = o + thetaSegment;
  19725. var v1 = segment + i;
  19726. var v2 = segment + thetaSegments + i;
  19727. var v3 = segment + thetaSegments + 1 + i;
  19728. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19729. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19730. v1 = segment + i;
  19731. v2 = segment + thetaSegments + 1 + i;
  19732. v3 = segment + 1 + i;
  19733. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19734. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19735. }
  19736. }
  19737. this.computeCentroids();
  19738. this.computeFaceNormals();
  19739. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19740. };
  19741. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19742. /**
  19743. * @author mrdoob / http://mrdoob.com/
  19744. */
  19745. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19746. THREE.Geometry.call( this );
  19747. this.radius = radius = radius || 50;
  19748. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19749. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19750. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19751. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19752. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19753. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19754. var x, y, vertices = [], uvs = [];
  19755. for ( y = 0; y <= heightSegments; y ++ ) {
  19756. var verticesRow = [];
  19757. var uvsRow = [];
  19758. for ( x = 0; x <= widthSegments; x ++ ) {
  19759. var u = x / widthSegments;
  19760. var v = y / heightSegments;
  19761. var vertex = new THREE.Vector3();
  19762. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19763. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19764. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19765. this.vertices.push( vertex );
  19766. verticesRow.push( this.vertices.length - 1 );
  19767. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19768. }
  19769. vertices.push( verticesRow );
  19770. uvs.push( uvsRow );
  19771. }
  19772. for ( y = 0; y < this.heightSegments; y ++ ) {
  19773. for ( x = 0; x < this.widthSegments; x ++ ) {
  19774. var v1 = vertices[ y ][ x + 1 ];
  19775. var v2 = vertices[ y ][ x ];
  19776. var v3 = vertices[ y + 1 ][ x ];
  19777. var v4 = vertices[ y + 1 ][ x + 1 ];
  19778. var n1 = this.vertices[ v1 ].clone().normalize();
  19779. var n2 = this.vertices[ v2 ].clone().normalize();
  19780. var n3 = this.vertices[ v3 ].clone().normalize();
  19781. var n4 = this.vertices[ v4 ].clone().normalize();
  19782. var uv1 = uvs[ y ][ x + 1 ].clone();
  19783. var uv2 = uvs[ y ][ x ].clone();
  19784. var uv3 = uvs[ y + 1 ][ x ].clone();
  19785. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19786. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19787. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19788. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19789. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19790. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19791. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19792. } else {
  19793. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19794. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19795. }
  19796. }
  19797. }
  19798. this.computeCentroids();
  19799. this.computeFaceNormals();
  19800. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19801. };
  19802. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19803. /**
  19804. * @author zz85 / http://www.lab4games.net/zz85/blog
  19805. * @author alteredq / http://alteredqualia.com/
  19806. *
  19807. * For creating 3D text geometry in three.js
  19808. *
  19809. * Text = 3D Text
  19810. *
  19811. * parameters = {
  19812. * size: <float>, // size of the text
  19813. * height: <float>, // thickness to extrude text
  19814. * curveSegments: <int>, // number of points on the curves
  19815. *
  19816. * font: <string>, // font name
  19817. * weight: <string>, // font weight (normal, bold)
  19818. * style: <string>, // font style (normal, italics)
  19819. *
  19820. * bevelEnabled: <bool>, // turn on bevel
  19821. * bevelThickness: <float>, // how deep into text bevel goes
  19822. * bevelSize: <float>, // how far from text outline is bevel
  19823. * }
  19824. *
  19825. */
  19826. /* Usage Examples
  19827. // TextGeometry wrapper
  19828. var text3d = new TextGeometry( text, options );
  19829. // Complete manner
  19830. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19831. var text3d = new ExtrudeGeometry( textShapes, options );
  19832. */
  19833. THREE.TextGeometry = function ( text, parameters ) {
  19834. parameters = parameters || {};
  19835. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19836. // translate parameters to ExtrudeGeometry API
  19837. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19838. // defaults
  19839. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19840. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19841. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19842. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19843. };
  19844. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19845. /**
  19846. * @author oosmoxiecode
  19847. * @author mrdoob / http://mrdoob.com/
  19848. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19849. */
  19850. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19851. THREE.Geometry.call( this );
  19852. var scope = this;
  19853. this.radius = radius || 100;
  19854. this.tube = tube || 40;
  19855. this.radialSegments = radialSegments || 8;
  19856. this.tubularSegments = tubularSegments || 6;
  19857. this.arc = arc || Math.PI * 2;
  19858. var center = new THREE.Vector3(), uvs = [], normals = [];
  19859. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19860. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19861. var u = i / this.tubularSegments * this.arc;
  19862. var v = j / this.radialSegments * Math.PI * 2;
  19863. center.x = this.radius * Math.cos( u );
  19864. center.y = this.radius * Math.sin( u );
  19865. var vertex = new THREE.Vector3();
  19866. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19867. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19868. vertex.z = this.tube * Math.sin( v );
  19869. this.vertices.push( vertex );
  19870. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19871. normals.push( vertex.clone().sub( center ).normalize() );
  19872. }
  19873. }
  19874. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19875. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19876. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19877. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19878. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19879. var d = ( this.tubularSegments + 1 ) * j + i;
  19880. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19881. face.normal.add( normals[ a ] );
  19882. face.normal.add( normals[ b ] );
  19883. face.normal.add( normals[ c ] );
  19884. face.normal.add( normals[ d ] );
  19885. face.normal.normalize();
  19886. this.faces.push( face );
  19887. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19888. }
  19889. }
  19890. this.computeCentroids();
  19891. };
  19892. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19893. /**
  19894. * @author oosmoxiecode
  19895. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19896. */
  19897. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19898. THREE.Geometry.call( this );
  19899. var scope = this;
  19900. this.radius = radius || 100;
  19901. this.tube = tube || 40;
  19902. this.radialSegments = radialSegments || 64;
  19903. this.tubularSegments = tubularSegments || 8;
  19904. this.p = p || 2;
  19905. this.q = q || 3;
  19906. this.heightScale = heightScale || 1;
  19907. this.grid = new Array( this.radialSegments );
  19908. var tang = new THREE.Vector3();
  19909. var n = new THREE.Vector3();
  19910. var bitan = new THREE.Vector3();
  19911. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19912. this.grid[ i ] = new Array( this.tubularSegments );
  19913. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19914. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  19915. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  19916. tang.subVectors( p2, p1 );
  19917. n.addVectors( p2, p1 );
  19918. bitan.crossVectors( tang, n );
  19919. n.crossVectors( bitan, tang );
  19920. bitan.normalize();
  19921. n.normalize();
  19922. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19923. var v = j / this.tubularSegments * 2 * Math.PI;
  19924. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19925. var cy = this.tube * Math.sin( v );
  19926. var pos = new THREE.Vector3();
  19927. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19928. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19929. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19930. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  19931. }
  19932. }
  19933. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19934. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19935. var ip = ( i + 1 ) % this.radialSegments;
  19936. var jp = ( j + 1 ) % this.tubularSegments;
  19937. var a = this.grid[ i ][ j ];
  19938. var b = this.grid[ ip ][ j ];
  19939. var c = this.grid[ ip ][ jp ];
  19940. var d = this.grid[ i ][ jp ];
  19941. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19942. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19943. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19944. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19945. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19946. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19947. }
  19948. }
  19949. this.computeCentroids();
  19950. this.computeFaceNormals();
  19951. this.computeVertexNormals();
  19952. function getPos( u, in_q, in_p, radius, heightScale ) {
  19953. var cu = Math.cos( u );
  19954. var su = Math.sin( u );
  19955. var quOverP = in_q / in_p * u;
  19956. var cs = Math.cos( quOverP );
  19957. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19958. var ty = radius * ( 2 + cs ) * su * 0.5;
  19959. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19960. return new THREE.Vector3( tx, ty, tz );
  19961. }
  19962. };
  19963. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19964. /**
  19965. * @author WestLangley / https://github.com/WestLangley
  19966. * @author zz85 / https://github.com/zz85
  19967. * @author miningold / https://github.com/miningold
  19968. *
  19969. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19970. *
  19971. * Creates a tube which extrudes along a 3d spline
  19972. *
  19973. * Uses parallel transport frames as described in
  19974. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19975. */
  19976. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  19977. THREE.Geometry.call( this );
  19978. this.path = path;
  19979. this.segments = segments || 64;
  19980. this.radius = radius || 1;
  19981. this.radialSegments = radialSegments || 8;
  19982. this.closed = closed || false;
  19983. this.grid = [];
  19984. var scope = this,
  19985. tangent,
  19986. normal,
  19987. binormal,
  19988. numpoints = this.segments + 1,
  19989. x, y, z,
  19990. tx, ty, tz,
  19991. u, v,
  19992. cx, cy,
  19993. pos, pos2 = new THREE.Vector3(),
  19994. i, j,
  19995. ip, jp,
  19996. a, b, c, d,
  19997. uva, uvb, uvc, uvd;
  19998. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19999. tangents = frames.tangents,
  20000. normals = frames.normals,
  20001. binormals = frames.binormals;
  20002. // proxy internals
  20003. this.tangents = tangents;
  20004. this.normals = normals;
  20005. this.binormals = binormals;
  20006. function vert( x, y, z ) {
  20007. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20008. }
  20009. // consruct the grid
  20010. for ( i = 0; i < numpoints; i++ ) {
  20011. this.grid[ i ] = [];
  20012. u = i / ( numpoints - 1 );
  20013. pos = path.getPointAt( u );
  20014. tangent = tangents[ i ];
  20015. normal = normals[ i ];
  20016. binormal = binormals[ i ];
  20017. for ( j = 0; j < this.radialSegments; j++ ) {
  20018. v = j / this.radialSegments * 2 * Math.PI;
  20019. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20020. cy = this.radius * Math.sin( v );
  20021. pos2.copy( pos );
  20022. pos2.x += cx * normal.x + cy * binormal.x;
  20023. pos2.y += cx * normal.y + cy * binormal.y;
  20024. pos2.z += cx * normal.z + cy * binormal.z;
  20025. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20026. }
  20027. }
  20028. // construct the mesh
  20029. for ( i = 0; i < this.segments; i++ ) {
  20030. for ( j = 0; j < this.radialSegments; j++ ) {
  20031. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20032. jp = (j + 1) % this.radialSegments;
  20033. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20034. b = this.grid[ ip ][ j ];
  20035. c = this.grid[ ip ][ jp ];
  20036. d = this.grid[ i ][ jp ];
  20037. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20038. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20039. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20040. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20041. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20042. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  20043. }
  20044. }
  20045. this.computeCentroids();
  20046. this.computeFaceNormals();
  20047. this.computeVertexNormals();
  20048. };
  20049. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20050. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20051. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20052. var tangent = new THREE.Vector3(),
  20053. normal = new THREE.Vector3(),
  20054. binormal = new THREE.Vector3(),
  20055. tangents = [],
  20056. normals = [],
  20057. binormals = [],
  20058. vec = new THREE.Vector3(),
  20059. mat = new THREE.Matrix4(),
  20060. numpoints = segments + 1,
  20061. theta,
  20062. epsilon = 0.0001,
  20063. smallest,
  20064. tx, ty, tz,
  20065. i, u, v;
  20066. // expose internals
  20067. this.tangents = tangents;
  20068. this.normals = normals;
  20069. this.binormals = binormals;
  20070. // compute the tangent vectors for each segment on the path
  20071. for ( i = 0; i < numpoints; i++ ) {
  20072. u = i / ( numpoints - 1 );
  20073. tangents[ i ] = path.getTangentAt( u );
  20074. tangents[ i ].normalize();
  20075. }
  20076. initialNormal3();
  20077. function initialNormal1(lastBinormal) {
  20078. // fixed start binormal. Has dangers of 0 vectors
  20079. normals[ 0 ] = new THREE.Vector3();
  20080. binormals[ 0 ] = new THREE.Vector3();
  20081. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20082. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20083. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20084. }
  20085. function initialNormal2() {
  20086. // This uses the Frenet-Serret formula for deriving binormal
  20087. var t2 = path.getTangentAt( epsilon );
  20088. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20089. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20090. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20091. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20092. }
  20093. function initialNormal3() {
  20094. // select an initial normal vector perpenicular to the first tangent vector,
  20095. // and in the direction of the smallest tangent xyz component
  20096. normals[ 0 ] = new THREE.Vector3();
  20097. binormals[ 0 ] = new THREE.Vector3();
  20098. smallest = Number.MAX_VALUE;
  20099. tx = Math.abs( tangents[ 0 ].x );
  20100. ty = Math.abs( tangents[ 0 ].y );
  20101. tz = Math.abs( tangents[ 0 ].z );
  20102. if ( tx <= smallest ) {
  20103. smallest = tx;
  20104. normal.set( 1, 0, 0 );
  20105. }
  20106. if ( ty <= smallest ) {
  20107. smallest = ty;
  20108. normal.set( 0, 1, 0 );
  20109. }
  20110. if ( tz <= smallest ) {
  20111. normal.set( 0, 0, 1 );
  20112. }
  20113. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20114. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20115. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20116. }
  20117. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20118. for ( i = 1; i < numpoints; i++ ) {
  20119. normals[ i ] = normals[ i-1 ].clone();
  20120. binormals[ i ] = binormals[ i-1 ].clone();
  20121. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20122. if ( vec.length() > epsilon ) {
  20123. vec.normalize();
  20124. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20125. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20126. }
  20127. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20128. }
  20129. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20130. if ( closed ) {
  20131. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20132. theta /= ( numpoints - 1 );
  20133. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20134. theta = -theta;
  20135. }
  20136. for ( i = 1; i < numpoints; i++ ) {
  20137. // twist a little...
  20138. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20139. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20140. }
  20141. }
  20142. };
  20143. /**
  20144. * @author clockworkgeek / https://github.com/clockworkgeek
  20145. * @author timothypratley / https://github.com/timothypratley
  20146. * @author WestLangley / http://github.com/WestLangley
  20147. */
  20148. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20149. THREE.Geometry.call( this );
  20150. radius = radius || 1;
  20151. detail = detail || 0;
  20152. var that = this;
  20153. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20154. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20155. }
  20156. var midpoints = [], p = this.vertices;
  20157. var f = [];
  20158. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20159. var v1 = p[ faces[ i ][ 0 ] ];
  20160. var v2 = p[ faces[ i ][ 1 ] ];
  20161. var v3 = p[ faces[ i ][ 2 ] ];
  20162. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20163. }
  20164. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20165. subdivide(f[ i ], detail);
  20166. }
  20167. // Handle case when face straddles the seam
  20168. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20169. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20170. var x0 = uvs[ 0 ].x;
  20171. var x1 = uvs[ 1 ].x;
  20172. var x2 = uvs[ 2 ].x;
  20173. var max = Math.max( x0, Math.max( x1, x2 ) );
  20174. var min = Math.min( x0, Math.min( x1, x2 ) );
  20175. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20176. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20177. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20178. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20179. }
  20180. }
  20181. // Apply radius
  20182. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20183. this.vertices[ i ].multiplyScalar( radius );
  20184. }
  20185. // Merge vertices
  20186. this.mergeVertices();
  20187. this.computeCentroids();
  20188. this.computeFaceNormals();
  20189. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20190. // Project vector onto sphere's surface
  20191. function prepare( vector ) {
  20192. var vertex = vector.normalize().clone();
  20193. vertex.index = that.vertices.push( vertex ) - 1;
  20194. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20195. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20196. var v = inclination( vector ) / Math.PI + 0.5;
  20197. vertex.uv = new THREE.Vector2( u, 1 - v );
  20198. return vertex;
  20199. }
  20200. // Approximate a curved face with recursively sub-divided triangles.
  20201. function make( v1, v2, v3 ) {
  20202. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20203. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20204. that.faces.push( face );
  20205. var azi = azimuth( face.centroid );
  20206. that.faceVertexUvs[ 0 ].push( [
  20207. correctUV( v1.uv, v1, azi ),
  20208. correctUV( v2.uv, v2, azi ),
  20209. correctUV( v3.uv, v3, azi )
  20210. ] );
  20211. }
  20212. // Analytically subdivide a face to the required detail level.
  20213. function subdivide(face, detail ) {
  20214. var cols = Math.pow(2, detail);
  20215. var cells = Math.pow(4, detail);
  20216. var a = prepare( that.vertices[ face.a ] );
  20217. var b = prepare( that.vertices[ face.b ] );
  20218. var c = prepare( that.vertices[ face.c ] );
  20219. var v = [];
  20220. // Construct all of the vertices for this subdivision.
  20221. for ( var i = 0 ; i <= cols; i ++ ) {
  20222. v[ i ] = [];
  20223. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20224. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20225. var rows = cols - i;
  20226. for ( var j = 0; j <= rows; j ++) {
  20227. if ( j == 0 && i == cols ) {
  20228. v[ i ][ j ] = aj;
  20229. } else {
  20230. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20231. }
  20232. }
  20233. }
  20234. // Construct all of the faces.
  20235. for ( var i = 0; i < cols ; i ++ ) {
  20236. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20237. var k = Math.floor( j / 2 );
  20238. if ( j % 2 == 0 ) {
  20239. make(
  20240. v[ i ][ k + 1],
  20241. v[ i + 1 ][ k ],
  20242. v[ i ][ k ]
  20243. );
  20244. } else {
  20245. make(
  20246. v[ i ][ k + 1 ],
  20247. v[ i + 1][ k + 1],
  20248. v[ i + 1 ][ k ]
  20249. );
  20250. }
  20251. }
  20252. }
  20253. }
  20254. // Angle around the Y axis, counter-clockwise when looking from above.
  20255. function azimuth( vector ) {
  20256. return Math.atan2( vector.z, -vector.x );
  20257. }
  20258. // Angle above the XZ plane.
  20259. function inclination( vector ) {
  20260. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20261. }
  20262. // Texture fixing helper. Spheres have some odd behaviours.
  20263. function correctUV( uv, vector, azimuth ) {
  20264. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20265. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20266. return uv.clone();
  20267. }
  20268. };
  20269. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20270. /**
  20271. * @author timothypratley / https://github.com/timothypratley
  20272. */
  20273. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20274. this.radius = radius;
  20275. this.detail = detail;
  20276. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20277. var vertices = [
  20278. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20279. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20280. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20281. ];
  20282. var faces = [
  20283. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20284. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20285. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20286. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20287. ];
  20288. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20289. };
  20290. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20291. /**
  20292. * @author timothypratley / https://github.com/timothypratley
  20293. */
  20294. THREE.OctahedronGeometry = function ( radius, detail ) {
  20295. var vertices = [
  20296. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20297. ];
  20298. var faces = [
  20299. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20300. ];
  20301. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20302. };
  20303. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20304. /**
  20305. * @author timothypratley / https://github.com/timothypratley
  20306. */
  20307. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20308. var vertices = [
  20309. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20310. ];
  20311. var faces = [
  20312. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20313. ];
  20314. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20315. };
  20316. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20317. /**
  20318. * @author zz85 / https://github.com/zz85
  20319. * Parametric Surfaces Geometry
  20320. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20321. *
  20322. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  20323. *
  20324. */
  20325. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  20326. THREE.Geometry.call( this );
  20327. var verts = this.vertices;
  20328. var faces = this.faces;
  20329. var uvs = this.faceVertexUvs[ 0 ];
  20330. useTris = (useTris === undefined) ? false : useTris;
  20331. var i, il, j, p;
  20332. var u, v;
  20333. var stackCount = stacks + 1;
  20334. var sliceCount = slices + 1;
  20335. for ( i = 0; i <= stacks; i ++ ) {
  20336. v = i / stacks;
  20337. for ( j = 0; j <= slices; j ++ ) {
  20338. u = j / slices;
  20339. p = func( u, v );
  20340. verts.push( p );
  20341. }
  20342. }
  20343. var a, b, c, d;
  20344. var uva, uvb, uvc, uvd;
  20345. for ( i = 0; i < stacks; i ++ ) {
  20346. for ( j = 0; j < slices; j ++ ) {
  20347. a = i * sliceCount + j;
  20348. b = i * sliceCount + j + 1;
  20349. c = (i + 1) * sliceCount + j;
  20350. d = (i + 1) * sliceCount + j + 1;
  20351. uva = new THREE.Vector2( j / slices, i / stacks );
  20352. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20353. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20354. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20355. if ( useTris ) {
  20356. faces.push( new THREE.Face3( a, b, c ) );
  20357. faces.push( new THREE.Face3( b, d, c ) );
  20358. uvs.push( [ uva, uvb, uvc ] );
  20359. uvs.push( [ uvb, uvd, uvc ] );
  20360. } else {
  20361. faces.push( new THREE.Face4( a, b, d, c ) );
  20362. uvs.push( [ uva, uvb, uvd, uvc ] );
  20363. }
  20364. }
  20365. }
  20366. // console.log(this);
  20367. // magic bullet
  20368. // var diff = this.mergeVertices();
  20369. // console.log('removed ', diff, ' vertices by merging');
  20370. this.computeCentroids();
  20371. this.computeFaceNormals();
  20372. this.computeVertexNormals();
  20373. };
  20374. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20375. /**
  20376. * @author qiao / https://github.com/qiao
  20377. * @fileoverview This is a convex hull generator using the incremental method.
  20378. * The complexity is O(n^2) where n is the number of vertices.
  20379. * O(nlogn) algorithms do exist, but they are much more complicated.
  20380. *
  20381. * Benchmark:
  20382. *
  20383. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20384. *
  20385. * Num Vertices Time(ms)
  20386. *
  20387. * 10 1
  20388. * 20 3
  20389. * 30 19
  20390. * 40 48
  20391. * 50 107
  20392. */
  20393. THREE.ConvexGeometry = function( vertices ) {
  20394. THREE.Geometry.call( this );
  20395. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20396. for ( var i = 3; i < vertices.length; i++ ) {
  20397. addPoint( i );
  20398. }
  20399. function addPoint( vertexId ) {
  20400. var vertex = vertices[ vertexId ].clone();
  20401. var mag = vertex.length();
  20402. vertex.x += mag * randomOffset();
  20403. vertex.y += mag * randomOffset();
  20404. vertex.z += mag * randomOffset();
  20405. var hole = [];
  20406. for ( var f = 0; f < faces.length; ) {
  20407. var face = faces[ f ];
  20408. // for each face, if the vertex can see it,
  20409. // then we try to add the face's edges into the hole.
  20410. if ( visible( face, vertex ) ) {
  20411. for ( var e = 0; e < 3; e++ ) {
  20412. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20413. var boundary = true;
  20414. // remove duplicated edges.
  20415. for ( var h = 0; h < hole.length; h++ ) {
  20416. if ( equalEdge( hole[ h ], edge ) ) {
  20417. hole[ h ] = hole[ hole.length - 1 ];
  20418. hole.pop();
  20419. boundary = false;
  20420. break;
  20421. }
  20422. }
  20423. if ( boundary ) {
  20424. hole.push( edge );
  20425. }
  20426. }
  20427. // remove faces[ f ]
  20428. faces[ f ] = faces[ faces.length - 1 ];
  20429. faces.pop();
  20430. } else { // not visible
  20431. f++;
  20432. }
  20433. }
  20434. // construct the new faces formed by the edges of the hole and the vertex
  20435. for ( var h = 0; h < hole.length; h++ ) {
  20436. faces.push( [
  20437. hole[ h ][ 0 ],
  20438. hole[ h ][ 1 ],
  20439. vertexId
  20440. ] );
  20441. }
  20442. }
  20443. /**
  20444. * Whether the face is visible from the vertex
  20445. */
  20446. function visible( face, vertex ) {
  20447. var va = vertices[ face[ 0 ] ];
  20448. var vb = vertices[ face[ 1 ] ];
  20449. var vc = vertices[ face[ 2 ] ];
  20450. var n = normal( va, vb, vc );
  20451. // distance from face to origin
  20452. var dist = n.dot( va );
  20453. return n.dot( vertex ) >= dist;
  20454. }
  20455. /**
  20456. * Face normal
  20457. */
  20458. function normal( va, vb, vc ) {
  20459. var cb = new THREE.Vector3();
  20460. var ab = new THREE.Vector3();
  20461. cb.subVectors( vc, vb );
  20462. ab.subVectors( va, vb );
  20463. cb.cross( ab );
  20464. cb.normalize();
  20465. return cb;
  20466. }
  20467. /**
  20468. * Detect whether two edges are equal.
  20469. * Note that when constructing the convex hull, two same edges can only
  20470. * be of the negative direction.
  20471. */
  20472. function equalEdge( ea, eb ) {
  20473. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20474. }
  20475. /**
  20476. * Create a random offset between -1e-6 and 1e-6.
  20477. */
  20478. function randomOffset() {
  20479. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20480. }
  20481. /**
  20482. * XXX: Not sure if this is the correct approach. Need someone to review.
  20483. */
  20484. function vertexUv( vertex ) {
  20485. var mag = vertex.length();
  20486. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20487. }
  20488. // Push vertices into `this.vertices`, skipping those inside the hull
  20489. var id = 0;
  20490. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20491. for ( var i = 0; i < faces.length; i++ ) {
  20492. var face = faces[ i ];
  20493. for ( var j = 0; j < 3; j++ ) {
  20494. if ( newId[ face[ j ] ] === undefined ) {
  20495. newId[ face[ j ] ] = id++;
  20496. this.vertices.push( vertices[ face[ j ] ] );
  20497. }
  20498. face[ j ] = newId[ face[ j ] ];
  20499. }
  20500. }
  20501. // Convert faces into instances of THREE.Face3
  20502. for ( var i = 0; i < faces.length; i++ ) {
  20503. this.faces.push( new THREE.Face3(
  20504. faces[ i ][ 0 ],
  20505. faces[ i ][ 1 ],
  20506. faces[ i ][ 2 ]
  20507. ) );
  20508. }
  20509. // Compute UVs
  20510. for ( var i = 0; i < this.faces.length; i++ ) {
  20511. var face = this.faces[ i ];
  20512. this.faceVertexUvs[ 0 ].push( [
  20513. vertexUv( this.vertices[ face.a ] ),
  20514. vertexUv( this.vertices[ face.b ] ),
  20515. vertexUv( this.vertices[ face.c ])
  20516. ] );
  20517. }
  20518. this.computeCentroids();
  20519. this.computeFaceNormals();
  20520. this.computeVertexNormals();
  20521. };
  20522. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20523. /**
  20524. * @author sroucheray / http://sroucheray.org/
  20525. * @author mrdoob / http://mrdoob.com/
  20526. */
  20527. THREE.AxisHelper = function ( size ) {
  20528. size = size || 1;
  20529. var geometry = new THREE.Geometry();
  20530. geometry.vertices.push(
  20531. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20532. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20533. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20534. );
  20535. geometry.colors.push(
  20536. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20537. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20538. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20539. );
  20540. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20541. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20542. };
  20543. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20544. /**
  20545. * @author WestLangley / http://github.com/WestLangley
  20546. * @author zz85 / http://github.com/zz85
  20547. * @author bhouston / http://exocortex.com
  20548. *
  20549. * Creates an arrow for visualizing directions
  20550. *
  20551. * Parameters:
  20552. * dir - Vector3
  20553. * origin - Vector3
  20554. * length - Number
  20555. * hex - color in hex value
  20556. */
  20557. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20558. // dir is assumed to be normalized
  20559. THREE.Object3D.call( this );
  20560. if ( hex === undefined ) hex = 0xffff00;
  20561. if ( length === undefined ) length = 1;
  20562. this.position = origin;
  20563. this.useQuaternion = true;
  20564. var lineGeometry = new THREE.Geometry();
  20565. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20566. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20567. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20568. this.line.matrixAutoUpdate = false;
  20569. this.add( this.line );
  20570. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20571. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20572. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20573. this.cone.matrixAutoUpdate = false;
  20574. this.add( this.cone );
  20575. this.setDirection( dir );
  20576. this.setLength( length );
  20577. };
  20578. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20579. THREE.ArrowHelper.prototype.setDirection = function () {
  20580. var axis = new THREE.Vector3();
  20581. var radians;
  20582. return function ( dir ) {
  20583. // dir is assumed to be normalized
  20584. if ( dir.y > 0.99999 ) {
  20585. this.quaternion.set( 0, 0, 0, 1 );
  20586. } else if ( dir.y < - 0.99999 ) {
  20587. this.quaternion.set( 1, 0, 0, 0 );
  20588. } else {
  20589. axis.set( dir.z, 0, - dir.x ).normalize();
  20590. radians = Math.acos( dir.y );
  20591. this.quaternion.setFromAxisAngle( axis, radians );
  20592. }
  20593. };
  20594. }();
  20595. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20596. this.scale.set( length, length, length );
  20597. };
  20598. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20599. this.line.material.color.setHex( hex );
  20600. this.cone.material.color.setHex( hex );
  20601. };
  20602. /**
  20603. * @author mrdoob / http://mrdoob.com/
  20604. */
  20605. THREE.BoxHelper = function ( object ) {
  20606. // 5____4
  20607. // 1/___0/|
  20608. // | 6__|_7
  20609. // 2/___3/
  20610. var vertices = [
  20611. new THREE.Vector3( 1, 1, 1 ),
  20612. new THREE.Vector3( - 1, 1, 1 ),
  20613. new THREE.Vector3( - 1, - 1, 1 ),
  20614. new THREE.Vector3( 1, - 1, 1 ),
  20615. new THREE.Vector3( 1, 1, - 1 ),
  20616. new THREE.Vector3( - 1, 1, - 1 ),
  20617. new THREE.Vector3( - 1, - 1, - 1 ),
  20618. new THREE.Vector3( 1, - 1, - 1 )
  20619. ];
  20620. this.vertices = vertices;
  20621. // TODO: Wouldn't be nice if Line had .segments?
  20622. var geometry = new THREE.Geometry();
  20623. geometry.vertices.push(
  20624. vertices[ 0 ], vertices[ 1 ],
  20625. vertices[ 1 ], vertices[ 2 ],
  20626. vertices[ 2 ], vertices[ 3 ],
  20627. vertices[ 3 ], vertices[ 0 ],
  20628. vertices[ 4 ], vertices[ 5 ],
  20629. vertices[ 5 ], vertices[ 6 ],
  20630. vertices[ 6 ], vertices[ 7 ],
  20631. vertices[ 7 ], vertices[ 4 ],
  20632. vertices[ 0 ], vertices[ 4 ],
  20633. vertices[ 1 ], vertices[ 5 ],
  20634. vertices[ 2 ], vertices[ 6 ],
  20635. vertices[ 3 ], vertices[ 7 ]
  20636. );
  20637. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20638. if ( object !== undefined ) {
  20639. this.update( object );
  20640. }
  20641. };
  20642. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20643. THREE.BoxHelper.prototype.update = function ( object ) {
  20644. var geometry = object.geometry;
  20645. if ( geometry.boundingBox === null ) {
  20646. geometry.computeBoundingBox();
  20647. }
  20648. var min = geometry.boundingBox.min;
  20649. var max = geometry.boundingBox.max;
  20650. var vertices = this.vertices;
  20651. vertices[ 0 ].set( max.x, max.y, max.z );
  20652. vertices[ 1 ].set( min.x, max.y, max.z );
  20653. vertices[ 2 ].set( min.x, min.y, max.z );
  20654. vertices[ 3 ].set( max.x, min.y, max.z );
  20655. vertices[ 4 ].set( max.x, max.y, min.z );
  20656. vertices[ 5 ].set( min.x, max.y, min.z );
  20657. vertices[ 6 ].set( min.x, min.y, min.z );
  20658. vertices[ 7 ].set( max.x, min.y, min.z );
  20659. this.geometry.computeBoundingSphere();
  20660. this.geometry.verticesNeedUpdate = true;
  20661. this.matrixAutoUpdate = false;
  20662. this.matrixWorld = object.matrixWorld;
  20663. };
  20664. /**
  20665. * @author WestLangley / http://github.com/WestLangley
  20666. */
  20667. // a helper to show the world-axis-aligned bounding box for an object
  20668. THREE.BoundingBoxHelper = function ( object, hex ) {
  20669. var color = hex || 0x888888;
  20670. this.object = object;
  20671. this.box = new THREE.Box3();
  20672. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20673. };
  20674. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20675. THREE.BoundingBoxHelper.prototype.update = function () {
  20676. this.box.setFromObject( this.object );
  20677. this.box.size( this.scale );
  20678. this.box.center( this.position );
  20679. };
  20680. /**
  20681. * @author alteredq / http://alteredqualia.com/
  20682. *
  20683. * - shows frustum, line of sight and up of the camera
  20684. * - suitable for fast updates
  20685. * - based on frustum visualization in lightgl.js shadowmap example
  20686. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20687. */
  20688. THREE.CameraHelper = function ( camera ) {
  20689. THREE.Line.call( this );
  20690. var geometry = new THREE.Geometry();
  20691. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20692. var pointMap = {};
  20693. // colors
  20694. var hexFrustum = 0xffaa00;
  20695. var hexCone = 0xff0000;
  20696. var hexUp = 0x00aaff;
  20697. var hexTarget = 0xffffff;
  20698. var hexCross = 0x333333;
  20699. // near
  20700. addLine( "n1", "n2", hexFrustum );
  20701. addLine( "n2", "n4", hexFrustum );
  20702. addLine( "n4", "n3", hexFrustum );
  20703. addLine( "n3", "n1", hexFrustum );
  20704. // far
  20705. addLine( "f1", "f2", hexFrustum );
  20706. addLine( "f2", "f4", hexFrustum );
  20707. addLine( "f4", "f3", hexFrustum );
  20708. addLine( "f3", "f1", hexFrustum );
  20709. // sides
  20710. addLine( "n1", "f1", hexFrustum );
  20711. addLine( "n2", "f2", hexFrustum );
  20712. addLine( "n3", "f3", hexFrustum );
  20713. addLine( "n4", "f4", hexFrustum );
  20714. // cone
  20715. addLine( "p", "n1", hexCone );
  20716. addLine( "p", "n2", hexCone );
  20717. addLine( "p", "n3", hexCone );
  20718. addLine( "p", "n4", hexCone );
  20719. // up
  20720. addLine( "u1", "u2", hexUp );
  20721. addLine( "u2", "u3", hexUp );
  20722. addLine( "u3", "u1", hexUp );
  20723. // target
  20724. addLine( "c", "t", hexTarget );
  20725. addLine( "p", "c", hexCross );
  20726. // cross
  20727. addLine( "cn1", "cn2", hexCross );
  20728. addLine( "cn3", "cn4", hexCross );
  20729. addLine( "cf1", "cf2", hexCross );
  20730. addLine( "cf3", "cf4", hexCross );
  20731. function addLine( a, b, hex ) {
  20732. addPoint( a, hex );
  20733. addPoint( b, hex );
  20734. }
  20735. function addPoint( id, hex ) {
  20736. geometry.vertices.push( new THREE.Vector3() );
  20737. geometry.colors.push( new THREE.Color( hex ) );
  20738. if ( pointMap[ id ] === undefined ) {
  20739. pointMap[ id ] = [];
  20740. }
  20741. pointMap[ id ].push( geometry.vertices.length - 1 );
  20742. }
  20743. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20744. this.camera = camera;
  20745. this.matrixWorld = camera.matrixWorld;
  20746. this.matrixAutoUpdate = false;
  20747. this.pointMap = pointMap;
  20748. this.update();
  20749. };
  20750. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20751. THREE.CameraHelper.prototype.update = function () {
  20752. var vector = new THREE.Vector3();
  20753. var camera = new THREE.Camera();
  20754. var projector = new THREE.Projector();
  20755. return function () {
  20756. var scope = this;
  20757. var w = 1, h = 1;
  20758. // we need just camera projection matrix
  20759. // world matrix must be identity
  20760. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20761. // center / target
  20762. setPoint( "c", 0, 0, -1 );
  20763. setPoint( "t", 0, 0, 1 );
  20764. // near
  20765. setPoint( "n1", -w, -h, -1 );
  20766. setPoint( "n2", w, -h, -1 );
  20767. setPoint( "n3", -w, h, -1 );
  20768. setPoint( "n4", w, h, -1 );
  20769. // far
  20770. setPoint( "f1", -w, -h, 1 );
  20771. setPoint( "f2", w, -h, 1 );
  20772. setPoint( "f3", -w, h, 1 );
  20773. setPoint( "f4", w, h, 1 );
  20774. // up
  20775. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20776. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20777. setPoint( "u3", 0, h * 2, -1 );
  20778. // cross
  20779. setPoint( "cf1", -w, 0, 1 );
  20780. setPoint( "cf2", w, 0, 1 );
  20781. setPoint( "cf3", 0, -h, 1 );
  20782. setPoint( "cf4", 0, h, 1 );
  20783. setPoint( "cn1", -w, 0, -1 );
  20784. setPoint( "cn2", w, 0, -1 );
  20785. setPoint( "cn3", 0, -h, -1 );
  20786. setPoint( "cn4", 0, h, -1 );
  20787. function setPoint( point, x, y, z ) {
  20788. vector.set( x, y, z );
  20789. projector.unprojectVector( vector, camera );
  20790. var points = scope.pointMap[ point ];
  20791. if ( points !== undefined ) {
  20792. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20793. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20794. }
  20795. }
  20796. }
  20797. this.geometry.verticesNeedUpdate = true;
  20798. };
  20799. }();
  20800. /**
  20801. * @author alteredq / http://alteredqualia.com/
  20802. * @author mrdoob / http://mrdoob.com/
  20803. */
  20804. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20805. THREE.Object3D.call( this );
  20806. this.matrixAutoUpdate = false;
  20807. this.light = light;
  20808. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20809. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20810. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20811. this.lightSphere = new THREE.Mesh( geometry, material );
  20812. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20813. this.lightSphere.matrixAutoUpdate = false;
  20814. this.add( this.lightSphere );
  20815. /*
  20816. this.targetSphere = new THREE.Mesh( geometry, material );
  20817. this.targetSphere.position = this.light.target.position;
  20818. this.add( this.targetSphere );
  20819. */
  20820. geometry = new THREE.Geometry();
  20821. geometry.vertices.push( this.light.position );
  20822. geometry.vertices.push( this.light.target.position );
  20823. geometry.computeLineDistances();
  20824. material = new THREE.LineDashedMaterial( { dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20825. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20826. this.targetLine = new THREE.Line( geometry, material );
  20827. this.add( this.targetLine );
  20828. }
  20829. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20830. THREE.DirectionalLightHelper.prototype.update = function () {
  20831. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20832. this.targetLine.geometry.computeLineDistances();
  20833. this.targetLine.geometry.verticesNeedUpdate = true;
  20834. this.targetLine.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20835. };
  20836. /**
  20837. * @author mrdoob / http://mrdoob.com/
  20838. * @author WestLangley / http://github.com/WestLangley
  20839. */
  20840. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20841. this.object = object;
  20842. this.size = size || 1;
  20843. var color = hex || 0xffff00;
  20844. var width = linewidth || 1;
  20845. var geometry = new THREE.Geometry();
  20846. var faces = this.object.geometry.faces;
  20847. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20848. geometry.vertices.push( new THREE.Vector3() );
  20849. geometry.vertices.push( new THREE.Vector3() );
  20850. }
  20851. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20852. this.matrixAutoUpdate = false;
  20853. this.normalMatrix = new THREE.Matrix3();
  20854. this.update();
  20855. };
  20856. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20857. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20858. var v1 = new THREE.Vector3();
  20859. return function( object ) {
  20860. this.object.updateMatrixWorld( true );
  20861. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20862. var vertices = this.geometry.vertices;
  20863. var faces = this.object.geometry.faces;
  20864. var worldMatrix = this.object.matrixWorld;
  20865. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20866. var face = faces[ i ];
  20867. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20868. var idx = 2 * i;
  20869. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  20870. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20871. }
  20872. this.geometry.verticesNeedUpdate = true;
  20873. return this;
  20874. }
  20875. }());
  20876. /**
  20877. * @author mrdoob / http://mrdoob.com/
  20878. */
  20879. THREE.GridHelper = function ( size, step ) {
  20880. var geometry = new THREE.Geometry();
  20881. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20882. var color1 = new THREE.Color( 0x444444 ), color2 = new THREE.Color( 0x888888 );
  20883. for ( var i = - size; i <= size; i += step ) {
  20884. geometry.vertices.push(
  20885. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20886. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20887. );
  20888. var color = i === 0 ? color1 : color2;
  20889. geometry.colors.push( color, color, color, color );
  20890. }
  20891. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20892. };
  20893. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20894. /**
  20895. * @author alteredq / http://alteredqualia.com/
  20896. * @author mrdoob / http://mrdoob.com/
  20897. */
  20898. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20899. THREE.Object3D.call( this );
  20900. this.light = light;
  20901. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20902. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20903. for ( var i = 0, il = 8; i < il; i ++ ) {
  20904. geometry.faces[ i ].materialIndex = i < 4 ? 0 : 1;
  20905. }
  20906. var materialSky = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20907. materialSky.color.copy( light.color ).multiplyScalar( light.intensity );
  20908. var materialGround = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20909. materialGround.color.copy( light.groundColor ).multiplyScalar( light.intensity );
  20910. this.lightSphere = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ materialSky, materialGround ] ) );
  20911. this.lightSphere.position = light.position;
  20912. this.lightSphere.lookAt( new THREE.Vector3() );
  20913. this.add( this.lightSphere );
  20914. };
  20915. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20916. THREE.HemisphereLightHelper.prototype.update = function () {
  20917. this.lightSphere.lookAt( new THREE.Vector3() );
  20918. this.lightSphere.material.materials[ 0 ].color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20919. this.lightSphere.material.materials[ 1 ].color.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20920. };
  20921. /**
  20922. * @author alteredq / http://alteredqualia.com/
  20923. * @author mrdoob / http://mrdoob.com/
  20924. */
  20925. THREE.PointLightHelper = function ( light, sphereSize ) {
  20926. THREE.Object3D.call( this );
  20927. this.matrixAutoUpdate = false;
  20928. this.light = light;
  20929. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20930. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20931. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20932. this.lightSphere = new THREE.Mesh( geometry, material );
  20933. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20934. this.lightSphere.matrixAutoUpdate = false;
  20935. this.add( this.lightSphere );
  20936. /*
  20937. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20938. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20939. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20940. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20941. var d = light.distance;
  20942. if ( d === 0.0 ) {
  20943. this.lightDistance.visible = false;
  20944. } else {
  20945. this.lightDistance.scale.set( d, d, d );
  20946. }
  20947. this.add( this.lightDistance );
  20948. */
  20949. };
  20950. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20951. THREE.PointLightHelper.prototype.update = function () {
  20952. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20953. /*
  20954. this.lightDistance.material.color.copy( this.color );
  20955. var d = this.light.distance;
  20956. if ( d === 0.0 ) {
  20957. this.lightDistance.visible = false;
  20958. } else {
  20959. this.lightDistance.visible = true;
  20960. this.lightDistance.scale.set( d, d, d );
  20961. }
  20962. */
  20963. };
  20964. /**
  20965. * @author alteredq / http://alteredqualia.com/
  20966. * @author mrdoob / http://mrdoob.com/
  20967. * @author WestLangley / http://github.com/WestLangley
  20968. */
  20969. THREE.SpotLightHelper = function ( light ) {
  20970. // spotlight helper must be a child of the scene
  20971. this.light = light;
  20972. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20973. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20974. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20975. var material = new THREE.MeshBasicMaterial( { wireframe: true, opacity: 0.3, transparent: true } );
  20976. THREE.Mesh.call( this, geometry, material );
  20977. this.update();
  20978. };
  20979. THREE.SpotLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20980. THREE.SpotLightHelper.prototype.update = ( function () {
  20981. var targetPosition = new THREE.Vector3();
  20982. return function() {
  20983. var coneLength = this.light.distance ? this.light.distance : 10000;
  20984. var coneWidth = coneLength * Math.tan( this.light.angle );
  20985. this.scale.set( coneWidth, coneWidth, coneLength );
  20986. this.light.updateMatrixWorld( true );
  20987. this.position.getPositionFromMatrix( this.light.matrixWorld );
  20988. this.light.target.updateMatrixWorld( true );
  20989. targetPosition.getPositionFromMatrix( this.light.target.matrixWorld );
  20990. this.lookAt( targetPosition );
  20991. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20992. }
  20993. }());
  20994. /**
  20995. * @author mrdoob / http://mrdoob.com/
  20996. * @author WestLangley / http://github.com/WestLangley
  20997. */
  20998. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20999. this.object = object;
  21000. this.size = size || 1;
  21001. var color = hex || 0xff0000;
  21002. var width = linewidth || 1;
  21003. var geometry = new THREE.Geometry();
  21004. var vertices = object.geometry.vertices;
  21005. var faces = object.geometry.faces;
  21006. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21007. var face = faces[ i ];
  21008. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21009. geometry.vertices.push( new THREE.Vector3() );
  21010. geometry.vertices.push( new THREE.Vector3() );
  21011. }
  21012. }
  21013. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21014. this.matrixAutoUpdate = false;
  21015. this.normalMatrix = new THREE.Matrix3();
  21016. this.update();
  21017. };
  21018. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21019. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21020. var v1 = new THREE.Vector3();
  21021. return function( object ) {
  21022. var keys = [ 'a', 'b', 'c', 'd' ];
  21023. this.object.updateMatrixWorld( true );
  21024. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21025. var vertices = this.geometry.vertices;
  21026. var verts = this.object.geometry.vertices;
  21027. var faces = this.object.geometry.faces;
  21028. var worldMatrix = this.object.matrixWorld;
  21029. var idx = 0;
  21030. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21031. var face = faces[ i ];
  21032. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21033. var vertexId = face[ keys[ j ] ];
  21034. var vertex = verts[ vertexId ];
  21035. var normal = face.vertexNormals[ j ];
  21036. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21037. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21038. v1.add( vertices[ idx ] );
  21039. idx = idx + 1;
  21040. vertices[ idx ].copy( v1 );
  21041. idx = idx + 1;
  21042. }
  21043. }
  21044. this.geometry.verticesNeedUpdate = true;
  21045. return this;
  21046. }
  21047. }());
  21048. /**
  21049. * @author mrdoob / http://mrdoob.com/
  21050. * @author WestLangley / http://github.com/WestLangley
  21051. */
  21052. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21053. this.object = object;
  21054. this.size = size || 1;
  21055. var color = hex || 0x0000ff;
  21056. var width = linewidth || 1;
  21057. var geometry = new THREE.Geometry();
  21058. var vertices = object.geometry.vertices;
  21059. var faces = object.geometry.faces;
  21060. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21061. var face = faces[ i ];
  21062. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21063. geometry.vertices.push( new THREE.Vector3() );
  21064. geometry.vertices.push( new THREE.Vector3() );
  21065. }
  21066. }
  21067. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21068. this.matrixAutoUpdate = false;
  21069. this.update();
  21070. };
  21071. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21072. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21073. var v1 = new THREE.Vector3();
  21074. return function( object ) {
  21075. var keys = [ 'a', 'b', 'c', 'd' ];
  21076. this.object.updateMatrixWorld( true );
  21077. var vertices = this.geometry.vertices;
  21078. var verts = this.object.geometry.vertices;
  21079. var faces = this.object.geometry.faces;
  21080. var worldMatrix = this.object.matrixWorld;
  21081. var idx = 0;
  21082. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21083. var face = faces[ i ];
  21084. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21085. var vertexId = face[ keys[ j ] ];
  21086. var vertex = verts[ vertexId ];
  21087. var tangent = face.vertexTangents[ j ];
  21088. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21089. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21090. v1.add( vertices[ idx ] );
  21091. idx = idx + 1;
  21092. vertices[ idx ].copy( v1 );
  21093. idx = idx + 1;
  21094. }
  21095. }
  21096. this.geometry.verticesNeedUpdate = true;
  21097. return this;
  21098. }
  21099. }());
  21100. /**
  21101. * @author mrdoob / http://mrdoob.com/
  21102. */
  21103. THREE.WireframeHelper = function ( object ) {
  21104. var edge = [ 0, 0 ], hash = {};
  21105. var sortFunction = function ( a, b ) { return a - b };
  21106. var keys = [ 'a', 'b', 'c', 'd' ];
  21107. var geometry = new THREE.Geometry();
  21108. var vertices = object.geometry.vertices;
  21109. var faces = object.geometry.faces;
  21110. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21111. var face = faces[ i ];
  21112. var length = face instanceof THREE.Face4 ? 4 : 3;
  21113. for ( var j = 0; j < length; j ++ ) {
  21114. edge[ 0 ] = face[ keys[ j ] ];
  21115. edge[ 1 ] = face[ keys[ ( j + 1 ) % length ] ];
  21116. edge.sort( sortFunction );
  21117. var key = edge.toString();
  21118. if ( hash[ key ] === undefined ) {
  21119. geometry.vertices.push( vertices[ edge[ 0 ] ] );
  21120. geometry.vertices.push( vertices[ edge[ 1 ] ] );
  21121. hash[ key ] = true;
  21122. }
  21123. }
  21124. }
  21125. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  21126. this.matrixAutoUpdate = false;
  21127. this.matrixWorld = object.matrixWorld;
  21128. };
  21129. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21130. /**
  21131. * @author alteredq / http://alteredqualia.com/
  21132. */
  21133. THREE.ImmediateRenderObject = function () {
  21134. THREE.Object3D.call( this );
  21135. this.render = function ( renderCallback ) { };
  21136. };
  21137. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21138. /**
  21139. * @author mikael emtinger / http://gomo.se/
  21140. * @author alteredq / http://alteredqualia.com/
  21141. */
  21142. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21143. THREE.Object3D.call( this );
  21144. this.lensFlares = [];
  21145. this.positionScreen = new THREE.Vector3();
  21146. this.customUpdateCallback = undefined;
  21147. if( texture !== undefined ) {
  21148. this.add( texture, size, distance, blending, color );
  21149. }
  21150. };
  21151. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21152. /*
  21153. * Add: adds another flare
  21154. */
  21155. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21156. if( size === undefined ) size = -1;
  21157. if( distance === undefined ) distance = 0;
  21158. if( opacity === undefined ) opacity = 1;
  21159. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21160. if( blending === undefined ) blending = THREE.NormalBlending;
  21161. distance = Math.min( distance, Math.max( 0, distance ) );
  21162. this.lensFlares.push( { texture: texture, // THREE.Texture
  21163. size: size, // size in pixels (-1 = use texture.width)
  21164. distance: distance, // distance (0-1) from light source (0=at light source)
  21165. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21166. scale: 1, // scale
  21167. rotation: 1, // rotation
  21168. opacity: opacity, // opacity
  21169. color: color, // color
  21170. blending: blending } ); // blending
  21171. };
  21172. /*
  21173. * Update lens flares update positions on all flares based on the screen position
  21174. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21175. */
  21176. THREE.LensFlare.prototype.updateLensFlares = function () {
  21177. var f, fl = this.lensFlares.length;
  21178. var flare;
  21179. var vecX = -this.positionScreen.x * 2;
  21180. var vecY = -this.positionScreen.y * 2;
  21181. for( f = 0; f < fl; f ++ ) {
  21182. flare = this.lensFlares[ f ];
  21183. flare.x = this.positionScreen.x + vecX * flare.distance;
  21184. flare.y = this.positionScreen.y + vecY * flare.distance;
  21185. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21186. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21187. }
  21188. };
  21189. /**
  21190. * @author alteredq / http://alteredqualia.com/
  21191. */
  21192. THREE.MorphBlendMesh = function( geometry, material ) {
  21193. THREE.Mesh.call( this, geometry, material );
  21194. this.animationsMap = {};
  21195. this.animationsList = [];
  21196. // prepare default animation
  21197. // (all frames played together in 1 second)
  21198. var numFrames = this.geometry.morphTargets.length;
  21199. var name = "__default";
  21200. var startFrame = 0;
  21201. var endFrame = numFrames - 1;
  21202. var fps = numFrames / 1;
  21203. this.createAnimation( name, startFrame, endFrame, fps );
  21204. this.setAnimationWeight( name, 1 );
  21205. };
  21206. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21207. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21208. var animation = {
  21209. startFrame: start,
  21210. endFrame: end,
  21211. length: end - start + 1,
  21212. fps: fps,
  21213. duration: ( end - start ) / fps,
  21214. lastFrame: 0,
  21215. currentFrame: 0,
  21216. active: false,
  21217. time: 0,
  21218. direction: 1,
  21219. weight: 1,
  21220. directionBackwards: false,
  21221. mirroredLoop: false
  21222. };
  21223. this.animationsMap[ name ] = animation;
  21224. this.animationsList.push( animation );
  21225. };
  21226. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21227. var pattern = /([a-z]+)(\d+)/;
  21228. var firstAnimation, frameRanges = {};
  21229. var geometry = this.geometry;
  21230. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21231. var morph = geometry.morphTargets[ i ];
  21232. var chunks = morph.name.match( pattern );
  21233. if ( chunks && chunks.length > 1 ) {
  21234. var name = chunks[ 1 ];
  21235. var num = chunks[ 2 ];
  21236. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21237. var range = frameRanges[ name ];
  21238. if ( i < range.start ) range.start = i;
  21239. if ( i > range.end ) range.end = i;
  21240. if ( ! firstAnimation ) firstAnimation = name;
  21241. }
  21242. }
  21243. for ( var name in frameRanges ) {
  21244. var range = frameRanges[ name ];
  21245. this.createAnimation( name, range.start, range.end, fps );
  21246. }
  21247. this.firstAnimation = firstAnimation;
  21248. };
  21249. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21250. var animation = this.animationsMap[ name ];
  21251. if ( animation ) {
  21252. animation.direction = 1;
  21253. animation.directionBackwards = false;
  21254. }
  21255. };
  21256. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21257. var animation = this.animationsMap[ name ];
  21258. if ( animation ) {
  21259. animation.direction = -1;
  21260. animation.directionBackwards = true;
  21261. }
  21262. };
  21263. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21264. var animation = this.animationsMap[ name ];
  21265. if ( animation ) {
  21266. animation.fps = fps;
  21267. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21268. }
  21269. };
  21270. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21271. var animation = this.animationsMap[ name ];
  21272. if ( animation ) {
  21273. animation.duration = duration;
  21274. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21275. }
  21276. };
  21277. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21278. var animation = this.animationsMap[ name ];
  21279. if ( animation ) {
  21280. animation.weight = weight;
  21281. }
  21282. };
  21283. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21284. var animation = this.animationsMap[ name ];
  21285. if ( animation ) {
  21286. animation.time = time;
  21287. }
  21288. };
  21289. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21290. var time = 0;
  21291. var animation = this.animationsMap[ name ];
  21292. if ( animation ) {
  21293. time = animation.time;
  21294. }
  21295. return time;
  21296. };
  21297. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21298. var duration = -1;
  21299. var animation = this.animationsMap[ name ];
  21300. if ( animation ) {
  21301. duration = animation.duration;
  21302. }
  21303. return duration;
  21304. };
  21305. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21306. var animation = this.animationsMap[ name ];
  21307. if ( animation ) {
  21308. animation.time = 0;
  21309. animation.active = true;
  21310. } else {
  21311. console.warn( "animation[" + name + "] undefined" );
  21312. }
  21313. };
  21314. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21315. var animation = this.animationsMap[ name ];
  21316. if ( animation ) {
  21317. animation.active = false;
  21318. }
  21319. };
  21320. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21321. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21322. var animation = this.animationsList[ i ];
  21323. if ( ! animation.active ) continue;
  21324. var frameTime = animation.duration / animation.length;
  21325. animation.time += animation.direction * delta;
  21326. if ( animation.mirroredLoop ) {
  21327. if ( animation.time > animation.duration || animation.time < 0 ) {
  21328. animation.direction *= -1;
  21329. if ( animation.time > animation.duration ) {
  21330. animation.time = animation.duration;
  21331. animation.directionBackwards = true;
  21332. }
  21333. if ( animation.time < 0 ) {
  21334. animation.time = 0;
  21335. animation.directionBackwards = false;
  21336. }
  21337. }
  21338. } else {
  21339. animation.time = animation.time % animation.duration;
  21340. if ( animation.time < 0 ) animation.time += animation.duration;
  21341. }
  21342. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21343. var weight = animation.weight;
  21344. if ( keyframe !== animation.currentFrame ) {
  21345. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21346. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21347. this.morphTargetInfluences[ keyframe ] = 0;
  21348. animation.lastFrame = animation.currentFrame;
  21349. animation.currentFrame = keyframe;
  21350. }
  21351. var mix = ( animation.time % frameTime ) / frameTime;
  21352. if ( animation.directionBackwards ) mix = 1 - mix;
  21353. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21354. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21355. }
  21356. };
  21357. /**
  21358. * @author mikael emtinger / http://gomo.se/
  21359. * @author alteredq / http://alteredqualia.com/
  21360. */
  21361. THREE.LensFlarePlugin = function () {
  21362. var _gl, _renderer, _precision, _lensFlare = {};
  21363. this.init = function ( renderer ) {
  21364. _gl = renderer.context;
  21365. _renderer = renderer;
  21366. _precision = renderer.getPrecision();
  21367. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21368. _lensFlare.faces = new Uint16Array( 6 );
  21369. var i = 0;
  21370. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21371. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21372. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21373. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21374. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21375. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21376. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21377. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21378. i = 0;
  21379. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21380. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21381. // buffers
  21382. _lensFlare.vertexBuffer = _gl.createBuffer();
  21383. _lensFlare.elementBuffer = _gl.createBuffer();
  21384. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21385. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21386. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21387. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21388. // textures
  21389. _lensFlare.tempTexture = _gl.createTexture();
  21390. _lensFlare.occlusionTexture = _gl.createTexture();
  21391. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21392. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21393. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21394. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21395. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21396. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21397. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21398. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21399. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21400. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21401. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21402. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21403. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21404. _lensFlare.hasVertexTexture = false;
  21405. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21406. } else {
  21407. _lensFlare.hasVertexTexture = true;
  21408. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21409. }
  21410. _lensFlare.attributes = {};
  21411. _lensFlare.uniforms = {};
  21412. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21413. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21414. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21415. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21416. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21417. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21418. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21419. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21420. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21421. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21422. };
  21423. /*
  21424. * Render lens flares
  21425. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21426. * reads these back and calculates occlusion.
  21427. * Then _lensFlare.update_lensFlares() is called to re-position and
  21428. * update transparency of flares. Then they are rendered.
  21429. *
  21430. */
  21431. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21432. var flares = scene.__webglFlares,
  21433. nFlares = flares.length;
  21434. if ( ! nFlares ) return;
  21435. var tempPosition = new THREE.Vector3();
  21436. var invAspect = viewportHeight / viewportWidth,
  21437. halfViewportWidth = viewportWidth * 0.5,
  21438. halfViewportHeight = viewportHeight * 0.5;
  21439. var size = 16 / viewportHeight,
  21440. scale = new THREE.Vector2( size * invAspect, size );
  21441. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21442. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21443. var uniforms = _lensFlare.uniforms,
  21444. attributes = _lensFlare.attributes;
  21445. // set _lensFlare program and reset blending
  21446. _gl.useProgram( _lensFlare.program );
  21447. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21448. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21449. // loop through all lens flares to update their occlusion and positions
  21450. // setup gl and common used attribs/unforms
  21451. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21452. _gl.uniform1i( uniforms.map, 1 );
  21453. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21454. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21455. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21456. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21457. _gl.disable( _gl.CULL_FACE );
  21458. _gl.depthMask( false );
  21459. var i, j, jl, flare, sprite;
  21460. for ( i = 0; i < nFlares; i ++ ) {
  21461. size = 16 / viewportHeight;
  21462. scale.set( size * invAspect, size );
  21463. // calc object screen position
  21464. flare = flares[ i ];
  21465. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21466. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21467. tempPosition.applyProjection( camera.projectionMatrix );
  21468. // setup arrays for gl programs
  21469. screenPosition.copy( tempPosition )
  21470. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21471. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21472. // screen cull
  21473. if ( _lensFlare.hasVertexTexture || (
  21474. screenPositionPixels.x > 0 &&
  21475. screenPositionPixels.x < viewportWidth &&
  21476. screenPositionPixels.y > 0 &&
  21477. screenPositionPixels.y < viewportHeight ) ) {
  21478. // save current RGB to temp texture
  21479. _gl.activeTexture( _gl.TEXTURE1 );
  21480. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21481. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21482. // render pink quad
  21483. _gl.uniform1i( uniforms.renderType, 0 );
  21484. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21485. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21486. _gl.disable( _gl.BLEND );
  21487. _gl.enable( _gl.DEPTH_TEST );
  21488. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21489. // copy result to occlusionMap
  21490. _gl.activeTexture( _gl.TEXTURE0 );
  21491. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21492. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21493. // restore graphics
  21494. _gl.uniform1i( uniforms.renderType, 1 );
  21495. _gl.disable( _gl.DEPTH_TEST );
  21496. _gl.activeTexture( _gl.TEXTURE1 );
  21497. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21498. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21499. // update object positions
  21500. flare.positionScreen.copy( screenPosition )
  21501. if ( flare.customUpdateCallback ) {
  21502. flare.customUpdateCallback( flare );
  21503. } else {
  21504. flare.updateLensFlares();
  21505. }
  21506. // render flares
  21507. _gl.uniform1i( uniforms.renderType, 2 );
  21508. _gl.enable( _gl.BLEND );
  21509. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21510. sprite = flare.lensFlares[ j ];
  21511. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21512. screenPosition.x = sprite.x;
  21513. screenPosition.y = sprite.y;
  21514. screenPosition.z = sprite.z;
  21515. size = sprite.size * sprite.scale / viewportHeight;
  21516. scale.x = size * invAspect;
  21517. scale.y = size;
  21518. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21519. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21520. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21521. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21522. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21523. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21524. _renderer.setTexture( sprite.texture, 1 );
  21525. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21526. }
  21527. }
  21528. }
  21529. }
  21530. // restore gl
  21531. _gl.enable( _gl.CULL_FACE );
  21532. _gl.enable( _gl.DEPTH_TEST );
  21533. _gl.depthMask( true );
  21534. };
  21535. function createProgram ( shader, precision ) {
  21536. var program = _gl.createProgram();
  21537. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21538. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21539. var prefix = "precision " + precision + " float;\n";
  21540. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21541. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21542. _gl.compileShader( fragmentShader );
  21543. _gl.compileShader( vertexShader );
  21544. _gl.attachShader( program, fragmentShader );
  21545. _gl.attachShader( program, vertexShader );
  21546. _gl.linkProgram( program );
  21547. return program;
  21548. };
  21549. };
  21550. /**
  21551. * @author alteredq / http://alteredqualia.com/
  21552. */
  21553. THREE.ShadowMapPlugin = function () {
  21554. var _gl,
  21555. _renderer,
  21556. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21557. _frustum = new THREE.Frustum(),
  21558. _projScreenMatrix = new THREE.Matrix4(),
  21559. _min = new THREE.Vector3(),
  21560. _max = new THREE.Vector3(),
  21561. _matrixPosition = new THREE.Vector3();
  21562. this.init = function ( renderer ) {
  21563. _gl = renderer.context;
  21564. _renderer = renderer;
  21565. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21566. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21567. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21568. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21569. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21570. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21571. _depthMaterial._shadowPass = true;
  21572. _depthMaterialMorph._shadowPass = true;
  21573. _depthMaterialSkin._shadowPass = true;
  21574. _depthMaterialMorphSkin._shadowPass = true;
  21575. };
  21576. this.render = function ( scene, camera ) {
  21577. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21578. this.update( scene, camera );
  21579. };
  21580. this.update = function ( scene, camera ) {
  21581. var i, il, j, jl, n,
  21582. shadowMap, shadowMatrix, shadowCamera,
  21583. program, buffer, material,
  21584. webglObject, object, light,
  21585. renderList,
  21586. lights = [],
  21587. k = 0,
  21588. fog = null;
  21589. // set GL state for depth map
  21590. _gl.clearColor( 1, 1, 1, 1 );
  21591. _gl.disable( _gl.BLEND );
  21592. _gl.enable( _gl.CULL_FACE );
  21593. _gl.frontFace( _gl.CCW );
  21594. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21595. _gl.cullFace( _gl.FRONT );
  21596. } else {
  21597. _gl.cullFace( _gl.BACK );
  21598. }
  21599. _renderer.setDepthTest( true );
  21600. // preprocess lights
  21601. // - skip lights that are not casting shadows
  21602. // - create virtual lights for cascaded shadow maps
  21603. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21604. light = scene.__lights[ i ];
  21605. if ( ! light.castShadow ) continue;
  21606. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21607. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21608. var virtualLight;
  21609. if ( ! light.shadowCascadeArray[ n ] ) {
  21610. virtualLight = createVirtualLight( light, n );
  21611. virtualLight.originalCamera = camera;
  21612. var gyro = new THREE.Gyroscope();
  21613. gyro.position = light.shadowCascadeOffset;
  21614. gyro.add( virtualLight );
  21615. gyro.add( virtualLight.target );
  21616. camera.add( gyro );
  21617. light.shadowCascadeArray[ n ] = virtualLight;
  21618. console.log( "Created virtualLight", virtualLight );
  21619. } else {
  21620. virtualLight = light.shadowCascadeArray[ n ];
  21621. }
  21622. updateVirtualLight( light, n );
  21623. lights[ k ] = virtualLight;
  21624. k ++;
  21625. }
  21626. } else {
  21627. lights[ k ] = light;
  21628. k ++;
  21629. }
  21630. }
  21631. // render depth map
  21632. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21633. light = lights[ i ];
  21634. if ( ! light.shadowMap ) {
  21635. var shadowFilter = THREE.LinearFilter;
  21636. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21637. shadowFilter = THREE.NearestFilter;
  21638. }
  21639. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21640. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21641. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21642. light.shadowMatrix = new THREE.Matrix4();
  21643. }
  21644. if ( ! light.shadowCamera ) {
  21645. if ( light instanceof THREE.SpotLight ) {
  21646. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21647. } else if ( light instanceof THREE.DirectionalLight ) {
  21648. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21649. } else {
  21650. console.error( "Unsupported light type for shadow" );
  21651. continue;
  21652. }
  21653. scene.add( light.shadowCamera );
  21654. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21655. }
  21656. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21657. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21658. light.shadowCamera.add( light.cameraHelper );
  21659. }
  21660. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21661. updateShadowCamera( camera, light );
  21662. }
  21663. shadowMap = light.shadowMap;
  21664. shadowMatrix = light.shadowMatrix;
  21665. shadowCamera = light.shadowCamera;
  21666. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21667. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21668. shadowCamera.lookAt( _matrixPosition );
  21669. shadowCamera.updateMatrixWorld();
  21670. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21671. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21672. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21673. // compute shadow matrix
  21674. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21675. 0.0, 0.5, 0.0, 0.5,
  21676. 0.0, 0.0, 0.5, 0.5,
  21677. 0.0, 0.0, 0.0, 1.0 );
  21678. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21679. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21680. // update camera matrices and frustum
  21681. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21682. _frustum.setFromMatrix( _projScreenMatrix );
  21683. // render shadow map
  21684. _renderer.setRenderTarget( shadowMap );
  21685. _renderer.clear();
  21686. // set object matrices & frustum culling
  21687. renderList = scene.__webglObjects;
  21688. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21689. webglObject = renderList[ j ];
  21690. object = webglObject.object;
  21691. webglObject.render = false;
  21692. if ( object.visible && object.castShadow ) {
  21693. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21694. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21695. webglObject.render = true;
  21696. }
  21697. }
  21698. }
  21699. // render regular objects
  21700. var objectMaterial, useMorphing, useSkinning;
  21701. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21702. webglObject = renderList[ j ];
  21703. if ( webglObject.render ) {
  21704. object = webglObject.object;
  21705. buffer = webglObject.buffer;
  21706. // culling is overriden globally for all objects
  21707. // while rendering depth map
  21708. // need to deal with MeshFaceMaterial somehow
  21709. // in that case just use the first of material.materials for now
  21710. // (proper solution would require to break objects by materials
  21711. // similarly to regular rendering and then set corresponding
  21712. // depth materials per each chunk instead of just once per object)
  21713. objectMaterial = getObjectMaterial( object );
  21714. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21715. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21716. if ( object.customDepthMaterial ) {
  21717. material = object.customDepthMaterial;
  21718. } else if ( useSkinning ) {
  21719. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21720. } else if ( useMorphing ) {
  21721. material = _depthMaterialMorph;
  21722. } else {
  21723. material = _depthMaterial;
  21724. }
  21725. if ( buffer instanceof THREE.BufferGeometry ) {
  21726. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21727. } else {
  21728. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21729. }
  21730. }
  21731. }
  21732. // set matrices and render immediate objects
  21733. renderList = scene.__webglObjectsImmediate;
  21734. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21735. webglObject = renderList[ j ];
  21736. object = webglObject.object;
  21737. if ( object.visible && object.castShadow ) {
  21738. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21739. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21740. }
  21741. }
  21742. }
  21743. // restore GL state
  21744. var clearColor = _renderer.getClearColor(),
  21745. clearAlpha = _renderer.getClearAlpha();
  21746. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21747. _gl.enable( _gl.BLEND );
  21748. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21749. _gl.cullFace( _gl.BACK );
  21750. }
  21751. };
  21752. function createVirtualLight( light, cascade ) {
  21753. var virtualLight = new THREE.DirectionalLight();
  21754. virtualLight.isVirtual = true;
  21755. virtualLight.onlyShadow = true;
  21756. virtualLight.castShadow = true;
  21757. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21758. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21759. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21760. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21761. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21762. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21763. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21764. virtualLight.shadowDarkness = light.shadowDarkness;
  21765. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21766. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21767. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21768. virtualLight.pointsWorld = [];
  21769. virtualLight.pointsFrustum = [];
  21770. var pointsWorld = virtualLight.pointsWorld,
  21771. pointsFrustum = virtualLight.pointsFrustum;
  21772. for ( var i = 0; i < 8; i ++ ) {
  21773. pointsWorld[ i ] = new THREE.Vector3();
  21774. pointsFrustum[ i ] = new THREE.Vector3();
  21775. }
  21776. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21777. var farZ = light.shadowCascadeFarZ[ cascade ];
  21778. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21779. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21780. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21781. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21782. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21783. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21784. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21785. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21786. return virtualLight;
  21787. }
  21788. // Synchronize virtual light with the original light
  21789. function updateVirtualLight( light, cascade ) {
  21790. var virtualLight = light.shadowCascadeArray[ cascade ];
  21791. virtualLight.position.copy( light.position );
  21792. virtualLight.target.position.copy( light.target.position );
  21793. virtualLight.lookAt( virtualLight.target );
  21794. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21795. virtualLight.shadowDarkness = light.shadowDarkness;
  21796. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21797. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21798. var farZ = light.shadowCascadeFarZ[ cascade ];
  21799. var pointsFrustum = virtualLight.pointsFrustum;
  21800. pointsFrustum[ 0 ].z = nearZ;
  21801. pointsFrustum[ 1 ].z = nearZ;
  21802. pointsFrustum[ 2 ].z = nearZ;
  21803. pointsFrustum[ 3 ].z = nearZ;
  21804. pointsFrustum[ 4 ].z = farZ;
  21805. pointsFrustum[ 5 ].z = farZ;
  21806. pointsFrustum[ 6 ].z = farZ;
  21807. pointsFrustum[ 7 ].z = farZ;
  21808. }
  21809. // Fit shadow camera's ortho frustum to camera frustum
  21810. function updateShadowCamera( camera, light ) {
  21811. var shadowCamera = light.shadowCamera,
  21812. pointsFrustum = light.pointsFrustum,
  21813. pointsWorld = light.pointsWorld;
  21814. _min.set( Infinity, Infinity, Infinity );
  21815. _max.set( -Infinity, -Infinity, -Infinity );
  21816. for ( var i = 0; i < 8; i ++ ) {
  21817. var p = pointsWorld[ i ];
  21818. p.copy( pointsFrustum[ i ] );
  21819. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21820. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21821. if ( p.x < _min.x ) _min.x = p.x;
  21822. if ( p.x > _max.x ) _max.x = p.x;
  21823. if ( p.y < _min.y ) _min.y = p.y;
  21824. if ( p.y > _max.y ) _max.y = p.y;
  21825. if ( p.z < _min.z ) _min.z = p.z;
  21826. if ( p.z > _max.z ) _max.z = p.z;
  21827. }
  21828. shadowCamera.left = _min.x;
  21829. shadowCamera.right = _max.x;
  21830. shadowCamera.top = _max.y;
  21831. shadowCamera.bottom = _min.y;
  21832. // can't really fit near/far
  21833. //shadowCamera.near = _min.z;
  21834. //shadowCamera.far = _max.z;
  21835. shadowCamera.updateProjectionMatrix();
  21836. }
  21837. // For the moment just ignore objects that have multiple materials with different animation methods
  21838. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21839. function getObjectMaterial( object ) {
  21840. return object.material instanceof THREE.MeshFaceMaterial
  21841. ? object.material.materials[ 0 ]
  21842. : object.material;
  21843. };
  21844. };
  21845. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21846. /**
  21847. * @author mikael emtinger / http://gomo.se/
  21848. * @author alteredq / http://alteredqualia.com/
  21849. */
  21850. THREE.SpritePlugin = function () {
  21851. var _gl, _renderer, _precision, _sprite = {};
  21852. this.init = function ( renderer ) {
  21853. _gl = renderer.context;
  21854. _renderer = renderer;
  21855. _precision = renderer.getPrecision();
  21856. _sprite.vertices = new Float32Array( 8 + 8 );
  21857. _sprite.faces = new Uint16Array( 6 );
  21858. var i = 0;
  21859. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21860. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21861. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21862. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21863. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21864. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21865. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21866. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21867. i = 0;
  21868. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21869. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21870. _sprite.vertexBuffer = _gl.createBuffer();
  21871. _sprite.elementBuffer = _gl.createBuffer();
  21872. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21873. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21874. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21875. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21876. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21877. _sprite.attributes = {};
  21878. _sprite.uniforms = {};
  21879. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21880. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21881. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21882. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21883. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21884. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21885. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21886. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21887. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21888. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21889. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21890. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21891. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21892. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21893. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21894. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21895. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21896. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21897. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21898. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21899. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21900. };
  21901. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21902. var sprites = scene.__webglSprites,
  21903. nSprites = sprites.length;
  21904. if ( ! nSprites ) return;
  21905. var attributes = _sprite.attributes,
  21906. uniforms = _sprite.uniforms;
  21907. var invAspect = viewportHeight / viewportWidth;
  21908. var halfViewportWidth = viewportWidth * 0.5,
  21909. halfViewportHeight = viewportHeight * 0.5;
  21910. // setup gl
  21911. _gl.useProgram( _sprite.program );
  21912. _gl.enableVertexAttribArray( attributes.position );
  21913. _gl.enableVertexAttribArray( attributes.uv );
  21914. _gl.disable( _gl.CULL_FACE );
  21915. _gl.enable( _gl.BLEND );
  21916. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21917. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21918. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21919. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21920. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21921. _gl.activeTexture( _gl.TEXTURE0 );
  21922. _gl.uniform1i( uniforms.map, 0 );
  21923. var oldFogType = 0;
  21924. var sceneFogType = 0;
  21925. var fog = scene.fog;
  21926. if ( fog ) {
  21927. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21928. if ( fog instanceof THREE.Fog ) {
  21929. _gl.uniform1f( uniforms.fogNear, fog.near );
  21930. _gl.uniform1f( uniforms.fogFar, fog.far );
  21931. _gl.uniform1i( uniforms.fogType, 1 );
  21932. oldFogType = 1;
  21933. sceneFogType = 1;
  21934. } else if ( fog instanceof THREE.FogExp2 ) {
  21935. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21936. _gl.uniform1i( uniforms.fogType, 2 );
  21937. oldFogType = 2;
  21938. sceneFogType = 2;
  21939. }
  21940. } else {
  21941. _gl.uniform1i( uniforms.fogType, 0 );
  21942. oldFogType = 0;
  21943. sceneFogType = 0;
  21944. }
  21945. // update positions and sort
  21946. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21947. for( i = 0; i < nSprites; i ++ ) {
  21948. sprite = sprites[ i ];
  21949. material = sprite.material;
  21950. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21951. if ( ! material.useScreenCoordinates ) {
  21952. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21953. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21954. } else {
  21955. sprite.z = - sprite.position.z;
  21956. }
  21957. }
  21958. sprites.sort( painterSortStable );
  21959. // render all sprites
  21960. for( i = 0; i < nSprites; i ++ ) {
  21961. sprite = sprites[ i ];
  21962. material = sprite.material;
  21963. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21964. if ( material.map && material.map.image && material.map.image.width ) {
  21965. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21966. if ( material.useScreenCoordinates === true ) {
  21967. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21968. _gl.uniform3f(
  21969. uniforms.screenPosition,
  21970. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21971. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21972. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21973. );
  21974. scale[ 0 ] = _renderer.devicePixelRatio;
  21975. scale[ 1 ] = _renderer.devicePixelRatio;
  21976. } else {
  21977. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21978. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21979. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21980. scale[ 0 ] = 1;
  21981. scale[ 1 ] = 1;
  21982. }
  21983. if ( scene.fog && material.fog ) {
  21984. fogType = sceneFogType;
  21985. } else {
  21986. fogType = 0;
  21987. }
  21988. if ( oldFogType !== fogType ) {
  21989. _gl.uniform1i( uniforms.fogType, fogType );
  21990. oldFogType = fogType;
  21991. }
  21992. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21993. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21994. scale[ 1 ] *= size * sprite.scale.y;
  21995. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21996. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21997. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21998. _gl.uniform1f( uniforms.opacity, material.opacity );
  21999. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22000. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  22001. _gl.uniform2fv( uniforms.scale, scale );
  22002. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22003. _renderer.setDepthTest( material.depthTest );
  22004. _renderer.setDepthWrite( material.depthWrite );
  22005. _renderer.setTexture( material.map, 0 );
  22006. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22007. }
  22008. }
  22009. // restore gl
  22010. _gl.enable( _gl.CULL_FACE );
  22011. };
  22012. function createProgram ( shader, precision ) {
  22013. var program = _gl.createProgram();
  22014. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22015. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22016. var prefix = "precision " + precision + " float;\n";
  22017. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  22018. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  22019. _gl.compileShader( fragmentShader );
  22020. _gl.compileShader( vertexShader );
  22021. _gl.attachShader( program, fragmentShader );
  22022. _gl.attachShader( program, vertexShader );
  22023. _gl.linkProgram( program );
  22024. return program;
  22025. };
  22026. function painterSortStable ( a, b ) {
  22027. if ( a.z !== b.z ) {
  22028. return b.z - a.z;
  22029. } else {
  22030. return b.id - a.id;
  22031. }
  22032. };
  22033. };
  22034. /**
  22035. * @author alteredq / http://alteredqualia.com/
  22036. */
  22037. THREE.DepthPassPlugin = function () {
  22038. this.enabled = false;
  22039. this.renderTarget = null;
  22040. var _gl,
  22041. _renderer,
  22042. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22043. _frustum = new THREE.Frustum(),
  22044. _projScreenMatrix = new THREE.Matrix4();
  22045. this.init = function ( renderer ) {
  22046. _gl = renderer.context;
  22047. _renderer = renderer;
  22048. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22049. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22050. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22051. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22052. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22053. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22054. _depthMaterial._shadowPass = true;
  22055. _depthMaterialMorph._shadowPass = true;
  22056. _depthMaterialSkin._shadowPass = true;
  22057. _depthMaterialMorphSkin._shadowPass = true;
  22058. };
  22059. this.render = function ( scene, camera ) {
  22060. if ( ! this.enabled ) return;
  22061. this.update( scene, camera );
  22062. };
  22063. this.update = function ( scene, camera ) {
  22064. var i, il, j, jl, n,
  22065. program, buffer, material,
  22066. webglObject, object, light,
  22067. renderList,
  22068. fog = null;
  22069. // set GL state for depth map
  22070. _gl.clearColor( 1, 1, 1, 1 );
  22071. _gl.disable( _gl.BLEND );
  22072. _renderer.setDepthTest( true );
  22073. // update scene
  22074. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22075. // update camera matrices and frustum
  22076. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22077. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22078. _frustum.setFromMatrix( _projScreenMatrix );
  22079. // render depth map
  22080. _renderer.setRenderTarget( this.renderTarget );
  22081. _renderer.clear();
  22082. // set object matrices & frustum culling
  22083. renderList = scene.__webglObjects;
  22084. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22085. webglObject = renderList[ j ];
  22086. object = webglObject.object;
  22087. webglObject.render = false;
  22088. if ( object.visible ) {
  22089. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22090. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22091. webglObject.render = true;
  22092. }
  22093. }
  22094. }
  22095. // render regular objects
  22096. var objectMaterial, useMorphing, useSkinning;
  22097. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22098. webglObject = renderList[ j ];
  22099. if ( webglObject.render ) {
  22100. object = webglObject.object;
  22101. buffer = webglObject.buffer;
  22102. // todo: create proper depth material for particles
  22103. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22104. objectMaterial = getObjectMaterial( object );
  22105. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22106. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22107. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22108. if ( object.customDepthMaterial ) {
  22109. material = object.customDepthMaterial;
  22110. } else if ( useSkinning ) {
  22111. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22112. } else if ( useMorphing ) {
  22113. material = _depthMaterialMorph;
  22114. } else {
  22115. material = _depthMaterial;
  22116. }
  22117. if ( buffer instanceof THREE.BufferGeometry ) {
  22118. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22119. } else {
  22120. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22121. }
  22122. }
  22123. }
  22124. // set matrices and render immediate objects
  22125. renderList = scene.__webglObjectsImmediate;
  22126. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22127. webglObject = renderList[ j ];
  22128. object = webglObject.object;
  22129. if ( object.visible ) {
  22130. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22131. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22132. }
  22133. }
  22134. // restore GL state
  22135. var clearColor = _renderer.getClearColor(),
  22136. clearAlpha = _renderer.getClearAlpha();
  22137. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22138. _gl.enable( _gl.BLEND );
  22139. };
  22140. // For the moment just ignore objects that have multiple materials with different animation methods
  22141. // Only the first material will be taken into account for deciding which depth material to use
  22142. function getObjectMaterial( object ) {
  22143. return object.material instanceof THREE.MeshFaceMaterial
  22144. ? object.material.materials[ 0 ]
  22145. : object.material;
  22146. };
  22147. };
  22148. /**
  22149. * @author mikael emtinger / http://gomo.se/
  22150. *
  22151. */
  22152. THREE.ShaderFlares = {
  22153. 'lensFlareVertexTexture': {
  22154. vertexShader: [
  22155. "uniform lowp int renderType;",
  22156. "uniform vec3 screenPosition;",
  22157. "uniform vec2 scale;",
  22158. "uniform float rotation;",
  22159. "uniform sampler2D occlusionMap;",
  22160. "attribute vec2 position;",
  22161. "attribute vec2 uv;",
  22162. "varying vec2 vUV;",
  22163. "varying float vVisibility;",
  22164. "void main() {",
  22165. "vUV = uv;",
  22166. "vec2 pos = position;",
  22167. "if( renderType == 2 ) {",
  22168. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  22169. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  22170. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  22171. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  22172. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  22173. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  22174. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  22175. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  22176. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22177. "vVisibility = ( visibility.r / 9.0 ) *",
  22178. "( 1.0 - visibility.g / 9.0 ) *",
  22179. "( visibility.b / 9.0 ) *",
  22180. "( 1.0 - visibility.a / 9.0 );",
  22181. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22182. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22183. "}",
  22184. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22185. "}"
  22186. ].join( "\n" ),
  22187. fragmentShader: [
  22188. "uniform lowp int renderType;",
  22189. "uniform sampler2D map;",
  22190. "uniform float opacity;",
  22191. "uniform vec3 color;",
  22192. "varying vec2 vUV;",
  22193. "varying float vVisibility;",
  22194. "void main() {",
  22195. // pink square
  22196. "if( renderType == 0 ) {",
  22197. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22198. // restore
  22199. "} else if( renderType == 1 ) {",
  22200. "gl_FragColor = texture2D( map, vUV );",
  22201. // flare
  22202. "} else {",
  22203. "vec4 texture = texture2D( map, vUV );",
  22204. "texture.a *= opacity * vVisibility;",
  22205. "gl_FragColor = texture;",
  22206. "gl_FragColor.rgb *= color;",
  22207. "}",
  22208. "}"
  22209. ].join( "\n" )
  22210. },
  22211. 'lensFlare': {
  22212. vertexShader: [
  22213. "uniform lowp int renderType;",
  22214. "uniform vec3 screenPosition;",
  22215. "uniform vec2 scale;",
  22216. "uniform float rotation;",
  22217. "attribute vec2 position;",
  22218. "attribute vec2 uv;",
  22219. "varying vec2 vUV;",
  22220. "void main() {",
  22221. "vUV = uv;",
  22222. "vec2 pos = position;",
  22223. "if( renderType == 2 ) {",
  22224. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22225. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22226. "}",
  22227. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22228. "}"
  22229. ].join( "\n" ),
  22230. fragmentShader: [
  22231. "precision mediump float;",
  22232. "uniform lowp int renderType;",
  22233. "uniform sampler2D map;",
  22234. "uniform sampler2D occlusionMap;",
  22235. "uniform float opacity;",
  22236. "uniform vec3 color;",
  22237. "varying vec2 vUV;",
  22238. "void main() {",
  22239. // pink square
  22240. "if( renderType == 0 ) {",
  22241. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22242. // restore
  22243. "} else if( renderType == 1 ) {",
  22244. "gl_FragColor = texture2D( map, vUV );",
  22245. // flare
  22246. "} else {",
  22247. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  22248. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  22249. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  22250. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22251. "visibility = ( 1.0 - visibility / 4.0 );",
  22252. "vec4 texture = texture2D( map, vUV );",
  22253. "texture.a *= opacity * visibility;",
  22254. "gl_FragColor = texture;",
  22255. "gl_FragColor.rgb *= color;",
  22256. "}",
  22257. "}"
  22258. ].join( "\n" )
  22259. }
  22260. };
  22261. /**
  22262. * @author mikael emtinger / http://gomo.se/
  22263. * @author alteredq / http://alteredqualia.com/
  22264. *
  22265. */
  22266. THREE.ShaderSprite = {
  22267. 'sprite': {
  22268. vertexShader: [
  22269. "uniform int useScreenCoordinates;",
  22270. "uniform int sizeAttenuation;",
  22271. "uniform vec3 screenPosition;",
  22272. "uniform mat4 modelViewMatrix;",
  22273. "uniform mat4 projectionMatrix;",
  22274. "uniform float rotation;",
  22275. "uniform vec2 scale;",
  22276. "uniform vec2 alignment;",
  22277. "uniform vec2 uvOffset;",
  22278. "uniform vec2 uvScale;",
  22279. "attribute vec2 position;",
  22280. "attribute vec2 uv;",
  22281. "varying vec2 vUV;",
  22282. "void main() {",
  22283. "vUV = uvOffset + uv * uvScale;",
  22284. "vec2 alignedPosition = position + alignment;",
  22285. "vec2 rotatedPosition;",
  22286. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  22287. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  22288. "vec4 finalPosition;",
  22289. "if( useScreenCoordinates != 0 ) {",
  22290. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  22291. "} else {",
  22292. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  22293. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  22294. "}",
  22295. "gl_Position = finalPosition;",
  22296. "}"
  22297. ].join( "\n" ),
  22298. fragmentShader: [
  22299. "uniform vec3 color;",
  22300. "uniform sampler2D map;",
  22301. "uniform float opacity;",
  22302. "uniform int fogType;",
  22303. "uniform vec3 fogColor;",
  22304. "uniform float fogDensity;",
  22305. "uniform float fogNear;",
  22306. "uniform float fogFar;",
  22307. "uniform float alphaTest;",
  22308. "varying vec2 vUV;",
  22309. "void main() {",
  22310. "vec4 texture = texture2D( map, vUV );",
  22311. "if ( texture.a < alphaTest ) discard;",
  22312. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22313. "if ( fogType > 0 ) {",
  22314. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  22315. "float fogFactor = 0.0;",
  22316. "if ( fogType == 1 ) {",
  22317. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  22318. "} else {",
  22319. "const float LOG2 = 1.442695;",
  22320. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  22321. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  22322. "}",
  22323. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  22324. "}",
  22325. "}"
  22326. ].join( "\n" )
  22327. }
  22328. };