three.js 795 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '56dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. // Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
  16. // not sure we should have this, or at least not have it here
  17. // http://stackoverflow.com/questions/646628/javascript-startswith
  18. // http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
  19. // http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras
  20. String.prototype.startsWith = String.prototype.startsWith || function ( str ) {
  21. return this.slice( 0, str.length ) === str;
  22. };
  23. String.prototype.endsWith = String.prototype.endsWith || function ( str ) {
  24. var t = String( str );
  25. var index = this.lastIndexOf( t );
  26. return ( -1 < index && index ) === (this.length - t.length);
  27. };
  28. String.prototype.trim = String.prototype.trim || function () {
  29. return this.replace( /^\s+|\s+$/g, '' );
  30. };
  31. // based on http://stackoverflow.com/a/12317051
  32. THREE.extend = function ( target, other ) {
  33. target = target || {};
  34. for (var prop in other) {
  35. if ( typeof other[prop] === 'object' ) {
  36. target[prop] = THREE.extend( target[prop], other[prop] );
  37. } else {
  38. target[prop] = other[prop];
  39. }
  40. }
  41. return target;
  42. };
  43. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  44. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  45. // requestAnimationFrame polyfill by Erik Möller
  46. // fixes from Paul Irish and Tino Zijdel
  47. ( function () {
  48. var lastTime = 0;
  49. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  50. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  51. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  52. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  53. }
  54. if ( window.requestAnimationFrame === undefined ) {
  55. window.requestAnimationFrame = function ( callback, element ) {
  56. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  57. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  58. lastTime = currTime + timeToCall;
  59. return id;
  60. };
  61. }
  62. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  63. }() );
  64. // GL STATE CONSTANTS
  65. THREE.CullFaceNone = 0;
  66. THREE.CullFaceBack = 1;
  67. THREE.CullFaceFront = 2;
  68. THREE.CullFaceFrontBack = 3;
  69. THREE.FrontFaceDirectionCW = 0;
  70. THREE.FrontFaceDirectionCCW = 1;
  71. // SHADOWING TYPES
  72. THREE.BasicShadowMap = 0;
  73. THREE.PCFShadowMap = 1;
  74. THREE.PCFSoftShadowMap = 2;
  75. // MATERIAL CONSTANTS
  76. // side
  77. THREE.FrontSide = 0;
  78. THREE.BackSide = 1;
  79. THREE.DoubleSide = 2;
  80. // shading
  81. THREE.NoShading = 0;
  82. THREE.FlatShading = 1;
  83. THREE.SmoothShading = 2;
  84. // colors
  85. THREE.NoColors = 0;
  86. THREE.FaceColors = 1;
  87. THREE.VertexColors = 2;
  88. // blending modes
  89. THREE.NoBlending = 0;
  90. THREE.NormalBlending = 1;
  91. THREE.AdditiveBlending = 2;
  92. THREE.SubtractiveBlending = 3;
  93. THREE.MultiplyBlending = 4;
  94. THREE.CustomBlending = 5;
  95. // custom blending equations
  96. // (numbers start from 100 not to clash with other
  97. // mappings to OpenGL constants defined in Texture.js)
  98. THREE.AddEquation = 100;
  99. THREE.SubtractEquation = 101;
  100. THREE.ReverseSubtractEquation = 102;
  101. // custom blending destination factors
  102. THREE.ZeroFactor = 200;
  103. THREE.OneFactor = 201;
  104. THREE.SrcColorFactor = 202;
  105. THREE.OneMinusSrcColorFactor = 203;
  106. THREE.SrcAlphaFactor = 204;
  107. THREE.OneMinusSrcAlphaFactor = 205;
  108. THREE.DstAlphaFactor = 206;
  109. THREE.OneMinusDstAlphaFactor = 207;
  110. // custom blending source factors
  111. //THREE.ZeroFactor = 200;
  112. //THREE.OneFactor = 201;
  113. //THREE.SrcAlphaFactor = 204;
  114. //THREE.OneMinusSrcAlphaFactor = 205;
  115. //THREE.DstAlphaFactor = 206;
  116. //THREE.OneMinusDstAlphaFactor = 207;
  117. THREE.DstColorFactor = 208;
  118. THREE.OneMinusDstColorFactor = 209;
  119. THREE.SrcAlphaSaturateFactor = 210;
  120. // TEXTURE CONSTANTS
  121. THREE.MultiplyOperation = 0;
  122. THREE.MixOperation = 1;
  123. THREE.AddOperation = 2;
  124. // Mapping modes
  125. THREE.UVMapping = function () {};
  126. THREE.CubeReflectionMapping = function () {};
  127. THREE.CubeRefractionMapping = function () {};
  128. THREE.SphericalReflectionMapping = function () {};
  129. THREE.SphericalRefractionMapping = function () {};
  130. // Wrapping modes
  131. THREE.RepeatWrapping = 1000;
  132. THREE.ClampToEdgeWrapping = 1001;
  133. THREE.MirroredRepeatWrapping = 1002;
  134. // Filters
  135. THREE.NearestFilter = 1003;
  136. THREE.NearestMipMapNearestFilter = 1004;
  137. THREE.NearestMipMapLinearFilter = 1005;
  138. THREE.LinearFilter = 1006;
  139. THREE.LinearMipMapNearestFilter = 1007;
  140. THREE.LinearMipMapLinearFilter = 1008;
  141. // Data types
  142. THREE.UnsignedByteType = 1009;
  143. THREE.ByteType = 1010;
  144. THREE.ShortType = 1011;
  145. THREE.UnsignedShortType = 1012;
  146. THREE.IntType = 1013;
  147. THREE.UnsignedIntType = 1014;
  148. THREE.FloatType = 1015;
  149. // Pixel types
  150. //THREE.UnsignedByteType = 1009;
  151. THREE.UnsignedShort4444Type = 1016;
  152. THREE.UnsignedShort5551Type = 1017;
  153. THREE.UnsignedShort565Type = 1018;
  154. // Pixel formats
  155. THREE.AlphaFormat = 1019;
  156. THREE.RGBFormat = 1020;
  157. THREE.RGBAFormat = 1021;
  158. THREE.LuminanceFormat = 1022;
  159. THREE.LuminanceAlphaFormat = 1023;
  160. // Compressed texture formats
  161. THREE.RGB_S3TC_DXT1_Format = 2001;
  162. THREE.RGBA_S3TC_DXT1_Format = 2002;
  163. THREE.RGBA_S3TC_DXT3_Format = 2003;
  164. THREE.RGBA_S3TC_DXT5_Format = 2004;
  165. /*
  166. // Potential future PVRTC compressed texture formats
  167. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  168. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  169. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  170. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  171. */
  172. /**
  173. * @author mrdoob / http://mrdoob.com/
  174. */
  175. THREE.Color = function ( value ) {
  176. if ( value !== undefined ) this.set( value );
  177. return this;
  178. };
  179. THREE.extend( THREE.Color.prototype, {
  180. r: 1, g: 1, b: 1,
  181. set: function ( value ) {
  182. switch ( typeof value ) {
  183. case "number":
  184. this.setHex( value );
  185. break;
  186. case "string":
  187. this.setStyle( value );
  188. break;
  189. }
  190. },
  191. setHex: function ( hex ) {
  192. hex = Math.floor( hex );
  193. this.r = ( hex >> 16 & 255 ) / 255;
  194. this.g = ( hex >> 8 & 255 ) / 255;
  195. this.b = ( hex & 255 ) / 255;
  196. return this;
  197. },
  198. setRGB: function ( r, g, b ) {
  199. this.r = r;
  200. this.g = g;
  201. this.b = b;
  202. return this;
  203. },
  204. setHSV: function ( h, s, v ) {
  205. // based on MochiKit implementation by Bob Ippolito
  206. // h,s,v ranges are < 0.0 - 1.0 >
  207. var i, f, p, q, t;
  208. if ( v === 0 ) {
  209. this.r = this.g = this.b = 0;
  210. } else {
  211. i = Math.floor( h * 6 );
  212. f = ( h * 6 ) - i;
  213. p = v * ( 1 - s );
  214. q = v * ( 1 - ( s * f ) );
  215. t = v * ( 1 - ( s * ( 1 - f ) ) );
  216. if ( i === 0 ) {
  217. this.r = v;
  218. this.g = t;
  219. this.b = p;
  220. } else if ( i === 1 ) {
  221. this.r = q;
  222. this.g = v;
  223. this.b = p;
  224. } else if ( i === 2 ) {
  225. this.r = p;
  226. this.g = v;
  227. this.b = t;
  228. } else if ( i === 3 ) {
  229. this.r = p;
  230. this.g = q;
  231. this.b = v;
  232. } else if ( i === 4 ) {
  233. this.r = t;
  234. this.g = p;
  235. this.b = v;
  236. } else if ( i === 5 ) {
  237. this.r = v;
  238. this.g = p;
  239. this.b = q;
  240. }
  241. }
  242. return this;
  243. },
  244. setStyle: function ( style ) {
  245. // rgb(255,0,0)
  246. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  247. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  248. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  249. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  250. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  251. return this;
  252. }
  253. // rgb(100%,0%,0%)
  254. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  255. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  256. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  257. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  258. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  259. return this;
  260. }
  261. // #ff0000
  262. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  263. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  264. this.setHex( parseInt( color[ 1 ], 16 ) );
  265. return this;
  266. }
  267. // #f00
  268. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  269. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  270. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  271. return this;
  272. }
  273. // red
  274. if ( /^(\w+)$/i.test( style ) ) {
  275. this.setHex( THREE.ColorKeywords[ style ] );
  276. return this;
  277. }
  278. },
  279. copy: function ( color ) {
  280. this.r = color.r;
  281. this.g = color.g;
  282. this.b = color.b;
  283. return this;
  284. },
  285. copyGammaToLinear: function ( color ) {
  286. this.r = color.r * color.r;
  287. this.g = color.g * color.g;
  288. this.b = color.b * color.b;
  289. return this;
  290. },
  291. copyLinearToGamma: function ( color ) {
  292. this.r = Math.sqrt( color.r );
  293. this.g = Math.sqrt( color.g );
  294. this.b = Math.sqrt( color.b );
  295. return this;
  296. },
  297. convertGammaToLinear: function () {
  298. var r = this.r, g = this.g, b = this.b;
  299. this.r = r * r;
  300. this.g = g * g;
  301. this.b = b * b;
  302. return this;
  303. },
  304. convertLinearToGamma: function () {
  305. this.r = Math.sqrt( this.r );
  306. this.g = Math.sqrt( this.g );
  307. this.b = Math.sqrt( this.b );
  308. return this;
  309. },
  310. getHex: function () {
  311. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  312. },
  313. getHexString: function () {
  314. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  315. },
  316. getStyle: function () {
  317. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  318. },
  319. getHSV: function ( hsv ) {
  320. // based on MochiKit implementation by Bob Ippolito
  321. // h,s,v ranges are < 0.0 - 1.0 >
  322. var r = this.r;
  323. var g = this.g;
  324. var b = this.b;
  325. var max = Math.max( Math.max( r, g ), b );
  326. var min = Math.min( Math.min( r, g ), b );
  327. var hue;
  328. var saturation;
  329. var value = max;
  330. if ( min === max ) {
  331. hue = 0;
  332. saturation = 0;
  333. } else {
  334. var delta = ( max - min );
  335. saturation = delta / max;
  336. if ( r === max ) {
  337. hue = ( g - b ) / delta;
  338. } else if ( g === max ) {
  339. hue = 2 + ( ( b - r ) / delta );
  340. } else {
  341. hue = 4 + ( ( r - g ) / delta );
  342. }
  343. hue /= 6;
  344. if ( hue < 0 ) {
  345. hue += 1;
  346. }
  347. if ( hue > 1 ) {
  348. hue -= 1;
  349. }
  350. }
  351. if ( hsv === undefined ) {
  352. hsv = { h: 0, s: 0, v: 0 };
  353. }
  354. hsv.h = hue;
  355. hsv.s = saturation;
  356. hsv.v = value;
  357. return hsv;
  358. },
  359. add: function ( color ) {
  360. this.r += color.r;
  361. this.g += color.g;
  362. this.b += color.b;
  363. return this;
  364. },
  365. addColors: function ( color1, color2 ) {
  366. this.r = color1.r + color2.r;
  367. this.g = color1.g + color2.g;
  368. this.b = color1.b + color2.b;
  369. return this;
  370. },
  371. addScalar: function ( s ) {
  372. this.r += s;
  373. this.g += s;
  374. this.b += s;
  375. return this;
  376. },
  377. multiply: function ( color ) {
  378. this.r *= color.r;
  379. this.g *= color.g;
  380. this.b *= color.b;
  381. return this;
  382. },
  383. multiplyScalar: function ( s ) {
  384. this.r *= s;
  385. this.g *= s;
  386. this.b *= s;
  387. return this;
  388. },
  389. lerp: function ( color, alpha ) {
  390. this.r += ( color.r - this.r ) * alpha;
  391. this.g += ( color.g - this.g ) * alpha;
  392. this.b += ( color.b - this.b ) * alpha;
  393. return this;
  394. },
  395. clone: function () {
  396. return new THREE.Color().setRGB( this.r, this.g, this.b );
  397. }
  398. } );
  399. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  400. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  401. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  402. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  403. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  404. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  405. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  406. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  407. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  408. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  409. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  410. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  411. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  412. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  413. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  414. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  415. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  416. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  417. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  418. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  419. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  420. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  421. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  422. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  423. /**
  424. * @author mikael emtinger / http://gomo.se/
  425. * @author alteredq / http://alteredqualia.com/
  426. * @author WestLangley / http://github.com/WestLangley
  427. * @author bhouston / http://exocortex.com
  428. */
  429. THREE.Quaternion = function( x, y, z, w ) {
  430. this.x = x || 0;
  431. this.y = y || 0;
  432. this.z = z || 0;
  433. this.w = ( w !== undefined ) ? w : 1;
  434. };
  435. THREE.extend( THREE.Quaternion.prototype, {
  436. set: function ( x, y, z, w ) {
  437. this.x = x;
  438. this.y = y;
  439. this.z = z;
  440. this.w = w;
  441. return this;
  442. },
  443. copy: function ( q ) {
  444. this.x = q.x;
  445. this.y = q.y;
  446. this.z = q.z;
  447. this.w = q.w;
  448. return this;
  449. },
  450. setFromEuler: function ( v, order ) {
  451. // http://www.mathworks.com/matlabcentral/fileexchange/
  452. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  453. // content/SpinCalc.m
  454. var c1 = Math.cos( v.x / 2 );
  455. var c2 = Math.cos( v.y / 2 );
  456. var c3 = Math.cos( v.z / 2 );
  457. var s1 = Math.sin( v.x / 2 );
  458. var s2 = Math.sin( v.y / 2 );
  459. var s3 = Math.sin( v.z / 2 );
  460. if ( order === undefined || order === 'XYZ' ) {
  461. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  462. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  463. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  464. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  465. } else if ( order === 'YXZ' ) {
  466. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  467. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  468. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  469. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  470. } else if ( order === 'ZXY' ) {
  471. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  472. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  473. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  474. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  475. } else if ( order === 'ZYX' ) {
  476. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  477. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  478. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  479. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  480. } else if ( order === 'YZX' ) {
  481. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  482. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  483. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  484. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  485. } else if ( order === 'XZY' ) {
  486. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  487. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  488. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  489. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  490. }
  491. return this;
  492. },
  493. setFromAxisAngle: function ( axis, angle ) {
  494. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  495. // axis have to be normalized
  496. var halfAngle = angle / 2,
  497. s = Math.sin( halfAngle );
  498. this.x = axis.x * s;
  499. this.y = axis.y * s;
  500. this.z = axis.z * s;
  501. this.w = Math.cos( halfAngle );
  502. return this;
  503. },
  504. setFromRotationMatrix: function ( m ) {
  505. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  506. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  507. var te = m.elements,
  508. m11 = te[0], m12 = te[4], m13 = te[8],
  509. m21 = te[1], m22 = te[5], m23 = te[9],
  510. m31 = te[2], m32 = te[6], m33 = te[10],
  511. trace = m11 + m22 + m33,
  512. s;
  513. if ( trace > 0 ) {
  514. s = 0.5 / Math.sqrt( trace + 1.0 );
  515. this.w = 0.25 / s;
  516. this.x = ( m32 - m23 ) * s;
  517. this.y = ( m13 - m31 ) * s;
  518. this.z = ( m21 - m12 ) * s;
  519. } else if ( m11 > m22 && m11 > m33 ) {
  520. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  521. this.w = (m32 - m23 ) / s;
  522. this.x = 0.25 * s;
  523. this.y = (m12 + m21 ) / s;
  524. this.z = (m13 + m31 ) / s;
  525. } else if ( m22 > m33 ) {
  526. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  527. this.w = (m13 - m31 ) / s;
  528. this.x = (m12 + m21 ) / s;
  529. this.y = 0.25 * s;
  530. this.z = (m23 + m32 ) / s;
  531. } else {
  532. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  533. this.w = ( m21 - m12 ) / s;
  534. this.x = ( m13 + m31 ) / s;
  535. this.y = ( m23 + m32 ) / s;
  536. this.z = 0.25 * s;
  537. }
  538. return this;
  539. },
  540. inverse: function () {
  541. this.conjugate().normalize();
  542. return this;
  543. },
  544. conjugate: function () {
  545. this.x *= -1;
  546. this.y *= -1;
  547. this.z *= -1;
  548. return this;
  549. },
  550. lengthSq: function () {
  551. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  552. },
  553. length: function () {
  554. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  555. },
  556. normalize: function () {
  557. var l = this.length();
  558. if ( l === 0 ) {
  559. this.x = 0;
  560. this.y = 0;
  561. this.z = 0;
  562. this.w = 1;
  563. } else {
  564. l = 1 / l;
  565. this.x = this.x * l;
  566. this.y = this.y * l;
  567. this.z = this.z * l;
  568. this.w = this.w * l;
  569. }
  570. return this;
  571. },
  572. multiply: function ( q, p ) {
  573. if ( p !== undefined ) {
  574. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  575. return this.multiplyQuaternions( q, p );
  576. }
  577. return this.multiplyQuaternions( this, q );
  578. },
  579. multiplyQuaternions: function ( a, b ) {
  580. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  581. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  582. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  583. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  584. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  585. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  586. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  587. return this;
  588. },
  589. multiplyVector3: function ( vector ) {
  590. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  591. return vector.applyQuaternion( this );
  592. },
  593. slerp: function ( qb, t ) {
  594. var x = this.x, y = this.y, z = this.z, w = this.w;
  595. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  596. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  597. if ( cosHalfTheta < 0 ) {
  598. this.w = -qb.w;
  599. this.x = -qb.x;
  600. this.y = -qb.y;
  601. this.z = -qb.z;
  602. cosHalfTheta = -cosHalfTheta;
  603. } else {
  604. this.copy( qb );
  605. }
  606. if ( cosHalfTheta >= 1.0 ) {
  607. this.w = w;
  608. this.x = x;
  609. this.y = y;
  610. this.z = z;
  611. return this;
  612. }
  613. var halfTheta = Math.acos( cosHalfTheta );
  614. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  615. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  616. this.w = 0.5 * ( w + this.w );
  617. this.x = 0.5 * ( x + this.x );
  618. this.y = 0.5 * ( y + this.y );
  619. this.z = 0.5 * ( z + this.z );
  620. return this;
  621. }
  622. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  623. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  624. this.w = ( w * ratioA + this.w * ratioB );
  625. this.x = ( x * ratioA + this.x * ratioB );
  626. this.y = ( y * ratioA + this.y * ratioB );
  627. this.z = ( z * ratioA + this.z * ratioB );
  628. return this;
  629. },
  630. equals: function ( v ) {
  631. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  632. },
  633. clone: function () {
  634. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  635. }
  636. } );
  637. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  638. return qm.copy( qa ).slerp( qb, t );
  639. }
  640. /**
  641. * @author mrdoob / http://mrdoob.com/
  642. * @author philogb / http://blog.thejit.org/
  643. * @author egraether / http://egraether.com/
  644. * @author zz85 / http://www.lab4games.net/zz85/blog
  645. */
  646. THREE.Vector2 = function ( x, y ) {
  647. this.x = x || 0;
  648. this.y = y || 0;
  649. };
  650. THREE.extend( THREE.Vector2.prototype, {
  651. set: function ( x, y ) {
  652. this.x = x;
  653. this.y = y;
  654. return this;
  655. },
  656. setX: function ( x ) {
  657. this.x = x;
  658. return this;
  659. },
  660. setY: function ( y ) {
  661. this.y = y;
  662. return this;
  663. },
  664. setComponent: function ( index, value ) {
  665. switch ( index ) {
  666. case 0: this.x = value; break;
  667. case 1: this.y = value; break;
  668. default: throw new Error( "index is out of range: " + index );
  669. }
  670. },
  671. getComponent: function ( index ) {
  672. switch ( index ) {
  673. case 0: return this.x;
  674. case 1: return this.y;
  675. default: throw new Error( "index is out of range: " + index );
  676. }
  677. },
  678. copy: function ( v ) {
  679. this.x = v.x;
  680. this.y = v.y;
  681. return this;
  682. },
  683. add: function ( v, w ) {
  684. if ( w !== undefined ) {
  685. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  686. return this.addVectors( v, w );
  687. }
  688. this.x += v.x;
  689. this.y += v.y;
  690. return this;
  691. },
  692. addVectors: function ( a, b ) {
  693. this.x = a.x + b.x;
  694. this.y = a.y + b.y;
  695. return this;
  696. },
  697. addScalar: function ( s ) {
  698. this.x += s;
  699. this.y += s;
  700. return this;
  701. },
  702. sub: function ( v, w ) {
  703. if ( w !== undefined ) {
  704. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  705. return this.subVectors( v, w );
  706. }
  707. this.x -= v.x;
  708. this.y -= v.y;
  709. return this;
  710. },
  711. subVectors: function ( a, b ) {
  712. this.x = a.x - b.x;
  713. this.y = a.y - b.y;
  714. return this;
  715. },
  716. multiplyScalar: function ( s ) {
  717. this.x *= s;
  718. this.y *= s;
  719. return this;
  720. },
  721. divideScalar: function ( s ) {
  722. if ( s !== 0 ) {
  723. this.x /= s;
  724. this.y /= s;
  725. } else {
  726. this.set( 0, 0 );
  727. }
  728. return this;
  729. },
  730. min: function ( v ) {
  731. if ( this.x > v.x ) {
  732. this.x = v.x;
  733. }
  734. if ( this.y > v.y ) {
  735. this.y = v.y;
  736. }
  737. return this;
  738. },
  739. max: function ( v ) {
  740. if ( this.x < v.x ) {
  741. this.x = v.x;
  742. }
  743. if ( this.y < v.y ) {
  744. this.y = v.y;
  745. }
  746. return this;
  747. },
  748. clamp: function ( min, max ) {
  749. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  750. if ( this.x < min.x ) {
  751. this.x = min.x;
  752. } else if ( this.x > max.x ) {
  753. this.x = max.x;
  754. }
  755. if ( this.y < min.y ) {
  756. this.y = min.y;
  757. } else if ( this.y > max.y ) {
  758. this.y = max.y;
  759. }
  760. return this;
  761. },
  762. negate: function() {
  763. return this.multiplyScalar( - 1 );
  764. },
  765. dot: function ( v ) {
  766. return this.x * v.x + this.y * v.y;
  767. },
  768. lengthSq: function () {
  769. return this.x * this.x + this.y * this.y;
  770. },
  771. length: function () {
  772. return Math.sqrt( this.x * this.x + this.y * this.y );
  773. },
  774. normalize: function () {
  775. return this.divideScalar( this.length() );
  776. },
  777. distanceTo: function ( v ) {
  778. return Math.sqrt( this.distanceToSquared( v ) );
  779. },
  780. distanceToSquared: function ( v ) {
  781. var dx = this.x - v.x, dy = this.y - v.y;
  782. return dx * dx + dy * dy;
  783. },
  784. setLength: function ( l ) {
  785. var oldLength = this.length();
  786. if ( oldLength !== 0 && l !== oldLength ) {
  787. this.multiplyScalar( l / oldLength );
  788. }
  789. return this;
  790. },
  791. lerp: function ( v, alpha ) {
  792. this.x += ( v.x - this.x ) * alpha;
  793. this.y += ( v.y - this.y ) * alpha;
  794. return this;
  795. },
  796. equals: function( v ) {
  797. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  798. },
  799. clone: function () {
  800. return new THREE.Vector2( this.x, this.y );
  801. }
  802. } );
  803. /**
  804. * @author mrdoob / http://mrdoob.com/
  805. * @author *kile / http://kile.stravaganza.org/
  806. * @author philogb / http://blog.thejit.org/
  807. * @author mikael emtinger / http://gomo.se/
  808. * @author egraether / http://egraether.com/
  809. * @author WestLangley / http://github.com/WestLangley
  810. */
  811. THREE.Vector3 = function ( x, y, z ) {
  812. this.x = x || 0;
  813. this.y = y || 0;
  814. this.z = z || 0;
  815. };
  816. THREE.extend( THREE.Vector3.prototype, {
  817. set: function ( x, y, z ) {
  818. this.x = x;
  819. this.y = y;
  820. this.z = z;
  821. return this;
  822. },
  823. setX: function ( x ) {
  824. this.x = x;
  825. return this;
  826. },
  827. setY: function ( y ) {
  828. this.y = y;
  829. return this;
  830. },
  831. setZ: function ( z ) {
  832. this.z = z;
  833. return this;
  834. },
  835. setComponent: function ( index, value ) {
  836. switch ( index ) {
  837. case 0: this.x = value; break;
  838. case 1: this.y = value; break;
  839. case 2: this.z = value; break;
  840. default: throw new Error( "index is out of range: " + index );
  841. }
  842. },
  843. getComponent: function ( index ) {
  844. switch ( index ) {
  845. case 0: return this.x;
  846. case 1: return this.y;
  847. case 2: return this.z;
  848. default: throw new Error( "index is out of range: " + index );
  849. }
  850. },
  851. copy: function ( v ) {
  852. this.x = v.x;
  853. this.y = v.y;
  854. this.z = v.z;
  855. return this;
  856. },
  857. add: function ( v, w ) {
  858. if ( w !== undefined ) {
  859. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  860. return this.addVectors( v, w );
  861. }
  862. this.x += v.x;
  863. this.y += v.y;
  864. this.z += v.z;
  865. return this;
  866. },
  867. addScalar: function ( s ) {
  868. this.x += s;
  869. this.y += s;
  870. this.z += s;
  871. return this;
  872. },
  873. addVectors: function ( a, b ) {
  874. this.x = a.x + b.x;
  875. this.y = a.y + b.y;
  876. this.z = a.z + b.z;
  877. return this;
  878. },
  879. sub: function ( v, w ) {
  880. if ( w !== undefined ) {
  881. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  882. return this.subVectors( v, w );
  883. }
  884. this.x -= v.x;
  885. this.y -= v.y;
  886. this.z -= v.z;
  887. return this;
  888. },
  889. subVectors: function ( a, b ) {
  890. this.x = a.x - b.x;
  891. this.y = a.y - b.y;
  892. this.z = a.z - b.z;
  893. return this;
  894. },
  895. multiply: function ( v, w ) {
  896. if ( w !== undefined ) {
  897. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  898. return this.multiplyVectors( v, w );
  899. }
  900. this.x *= v.x;
  901. this.y *= v.y;
  902. this.z *= v.z;
  903. return this;
  904. },
  905. multiplyScalar: function ( s ) {
  906. this.x *= s;
  907. this.y *= s;
  908. this.z *= s;
  909. return this;
  910. },
  911. multiplyVectors: function ( a, b ) {
  912. this.x = a.x * b.x;
  913. this.y = a.y * b.y;
  914. this.z = a.z * b.z;
  915. return this;
  916. },
  917. applyMatrix3: function ( m ) {
  918. var x = this.x;
  919. var y = this.y;
  920. var z = this.z;
  921. var e = m.elements;
  922. this.x = e[0] * x + e[3] * y + e[6] * z;
  923. this.y = e[1] * x + e[4] * y + e[7] * z;
  924. this.z = e[2] * x + e[5] * y + e[8] * z;
  925. return this;
  926. },
  927. applyMatrix4: function ( m ) {
  928. // input: THREE.Matrix4 affine matrix
  929. var x = this.x, y = this.y, z = this.z;
  930. var e = m.elements;
  931. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  932. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  933. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  934. return this;
  935. },
  936. applyProjection: function ( m ) {
  937. // input: THREE.Matrix4 projection matrix
  938. var x = this.x, y = this.y, z = this.z;
  939. var e = m.elements;
  940. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  941. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  942. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  943. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  944. return this;
  945. },
  946. applyQuaternion: function ( q ) {
  947. var x = this.x;
  948. var y = this.y;
  949. var z = this.z;
  950. var qx = q.x;
  951. var qy = q.y;
  952. var qz = q.z;
  953. var qw = q.w;
  954. // calculate quat * vector
  955. var ix = qw * x + qy * z - qz * y;
  956. var iy = qw * y + qz * x - qx * z;
  957. var iz = qw * z + qx * y - qy * x;
  958. var iw = -qx * x - qy * y - qz * z;
  959. // calculate result * inverse quat
  960. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  961. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  962. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  963. return this;
  964. },
  965. applyEuler: function() {
  966. var q1 = new THREE.Quaternion();
  967. return function ( v, eulerOrder ) {
  968. var quaternion = q1.setFromEuler( v, eulerOrder );
  969. this.applyQuaternion( quaternion );
  970. return this;
  971. };
  972. }(),
  973. applyAxisAngle: function() {
  974. var q1 = new THREE.Quaternion();
  975. return function ( axis, angle ) {
  976. var quaternion = q1.setFromAxisAngle( axis, angle );
  977. this.applyQuaternion( quaternion );
  978. return this;
  979. };
  980. }(),
  981. transformDirection: function ( m ) {
  982. // input: THREE.Matrix4 affine matrix
  983. // vector interpreted as a direction
  984. var x = this.x, y = this.y, z = this.z;
  985. var e = m.elements;
  986. this.x = e[0] * x + e[4] * y + e[8] * z;
  987. this.y = e[1] * x + e[5] * y + e[9] * z;
  988. this.z = e[2] * x + e[6] * y + e[10] * z;
  989. this.normalize();
  990. return this;
  991. },
  992. divide: function ( v ) {
  993. this.x /= v.x;
  994. this.y /= v.y;
  995. this.z /= v.z;
  996. return this;
  997. },
  998. divideScalar: function ( s ) {
  999. if ( s !== 0 ) {
  1000. this.x /= s;
  1001. this.y /= s;
  1002. this.z /= s;
  1003. } else {
  1004. this.x = 0;
  1005. this.y = 0;
  1006. this.z = 0;
  1007. }
  1008. return this;
  1009. },
  1010. min: function ( v ) {
  1011. if ( this.x > v.x ) {
  1012. this.x = v.x;
  1013. }
  1014. if ( this.y > v.y ) {
  1015. this.y = v.y;
  1016. }
  1017. if ( this.z > v.z ) {
  1018. this.z = v.z;
  1019. }
  1020. return this;
  1021. },
  1022. max: function ( v ) {
  1023. if ( this.x < v.x ) {
  1024. this.x = v.x;
  1025. }
  1026. if ( this.y < v.y ) {
  1027. this.y = v.y;
  1028. }
  1029. if ( this.z < v.z ) {
  1030. this.z = v.z;
  1031. }
  1032. return this;
  1033. },
  1034. clamp: function ( min, max ) {
  1035. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1036. if ( this.x < min.x ) {
  1037. this.x = min.x;
  1038. } else if ( this.x > max.x ) {
  1039. this.x = max.x;
  1040. }
  1041. if ( this.y < min.y ) {
  1042. this.y = min.y;
  1043. } else if ( this.y > max.y ) {
  1044. this.y = max.y;
  1045. }
  1046. if ( this.z < min.z ) {
  1047. this.z = min.z;
  1048. } else if ( this.z > max.z ) {
  1049. this.z = max.z;
  1050. }
  1051. return this;
  1052. },
  1053. negate: function() {
  1054. return this.multiplyScalar( - 1 );
  1055. },
  1056. dot: function ( v ) {
  1057. return this.x * v.x + this.y * v.y + this.z * v.z;
  1058. },
  1059. lengthSq: function () {
  1060. return this.x * this.x + this.y * this.y + this.z * this.z;
  1061. },
  1062. length: function () {
  1063. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1064. },
  1065. lengthManhattan: function () {
  1066. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1067. },
  1068. normalize: function () {
  1069. return this.divideScalar( this.length() );
  1070. },
  1071. setLength: function ( l ) {
  1072. var oldLength = this.length();
  1073. if ( oldLength !== 0 && l !== oldLength ) {
  1074. this.multiplyScalar( l / oldLength );
  1075. }
  1076. return this;
  1077. },
  1078. lerp: function ( v, alpha ) {
  1079. this.x += ( v.x - this.x ) * alpha;
  1080. this.y += ( v.y - this.y ) * alpha;
  1081. this.z += ( v.z - this.z ) * alpha;
  1082. return this;
  1083. },
  1084. cross: function ( v, w ) {
  1085. if ( w !== undefined ) {
  1086. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1087. return this.crossVectors( v, w );
  1088. }
  1089. var x = this.x, y = this.y, z = this.z;
  1090. this.x = y * v.z - z * v.y;
  1091. this.y = z * v.x - x * v.z;
  1092. this.z = x * v.y - y * v.x;
  1093. return this;
  1094. },
  1095. crossVectors: function ( a, b ) {
  1096. this.x = a.y * b.z - a.z * b.y;
  1097. this.y = a.z * b.x - a.x * b.z;
  1098. this.z = a.x * b.y - a.y * b.x;
  1099. return this;
  1100. },
  1101. angleTo: function ( v ) {
  1102. return Math.acos( this.dot( v ) / this.length() / v.length() );
  1103. },
  1104. distanceTo: function ( v ) {
  1105. return Math.sqrt( this.distanceToSquared( v ) );
  1106. },
  1107. distanceToSquared: function ( v ) {
  1108. var dx = this.x - v.x;
  1109. var dy = this.y - v.y;
  1110. var dz = this.z - v.z;
  1111. return dx * dx + dy * dy + dz * dz;
  1112. },
  1113. getPositionFromMatrix: function ( m ) {
  1114. this.x = m.elements[12];
  1115. this.y = m.elements[13];
  1116. this.z = m.elements[14];
  1117. return this;
  1118. },
  1119. setEulerFromRotationMatrix: function ( m, order ) {
  1120. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1121. // clamp, to handle numerical problems
  1122. function clamp( x ) {
  1123. return Math.min( Math.max( x, -1 ), 1 );
  1124. }
  1125. var te = m.elements;
  1126. var m11 = te[0], m12 = te[4], m13 = te[8];
  1127. var m21 = te[1], m22 = te[5], m23 = te[9];
  1128. var m31 = te[2], m32 = te[6], m33 = te[10];
  1129. if ( order === undefined || order === 'XYZ' ) {
  1130. this.y = Math.asin( clamp( m13 ) );
  1131. if ( Math.abs( m13 ) < 0.99999 ) {
  1132. this.x = Math.atan2( - m23, m33 );
  1133. this.z = Math.atan2( - m12, m11 );
  1134. } else {
  1135. this.x = Math.atan2( m32, m22 );
  1136. this.z = 0;
  1137. }
  1138. } else if ( order === 'YXZ' ) {
  1139. this.x = Math.asin( - clamp( m23 ) );
  1140. if ( Math.abs( m23 ) < 0.99999 ) {
  1141. this.y = Math.atan2( m13, m33 );
  1142. this.z = Math.atan2( m21, m22 );
  1143. } else {
  1144. this.y = Math.atan2( - m31, m11 );
  1145. this.z = 0;
  1146. }
  1147. } else if ( order === 'ZXY' ) {
  1148. this.x = Math.asin( clamp( m32 ) );
  1149. if ( Math.abs( m32 ) < 0.99999 ) {
  1150. this.y = Math.atan2( - m31, m33 );
  1151. this.z = Math.atan2( - m12, m22 );
  1152. } else {
  1153. this.y = 0;
  1154. this.z = Math.atan2( m21, m11 );
  1155. }
  1156. } else if ( order === 'ZYX' ) {
  1157. this.y = Math.asin( - clamp( m31 ) );
  1158. if ( Math.abs( m31 ) < 0.99999 ) {
  1159. this.x = Math.atan2( m32, m33 );
  1160. this.z = Math.atan2( m21, m11 );
  1161. } else {
  1162. this.x = 0;
  1163. this.z = Math.atan2( - m12, m22 );
  1164. }
  1165. } else if ( order === 'YZX' ) {
  1166. this.z = Math.asin( clamp( m21 ) );
  1167. if ( Math.abs( m21 ) < 0.99999 ) {
  1168. this.x = Math.atan2( - m23, m22 );
  1169. this.y = Math.atan2( - m31, m11 );
  1170. } else {
  1171. this.x = 0;
  1172. this.y = Math.atan2( m13, m33 );
  1173. }
  1174. } else if ( order === 'XZY' ) {
  1175. this.z = Math.asin( - clamp( m12 ) );
  1176. if ( Math.abs( m12 ) < 0.99999 ) {
  1177. this.x = Math.atan2( m32, m22 );
  1178. this.y = Math.atan2( m13, m11 );
  1179. } else {
  1180. this.x = Math.atan2( - m23, m33 );
  1181. this.y = 0;
  1182. }
  1183. }
  1184. return this;
  1185. },
  1186. setEulerFromQuaternion: function ( q, order ) {
  1187. // q is assumed to be normalized
  1188. // clamp, to handle numerical problems
  1189. function clamp( x ) {
  1190. return Math.min( Math.max( x, -1 ), 1 );
  1191. }
  1192. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1193. var sqx = q.x * q.x;
  1194. var sqy = q.y * q.y;
  1195. var sqz = q.z * q.z;
  1196. var sqw = q.w * q.w;
  1197. if ( order === undefined || order === 'XYZ' ) {
  1198. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1199. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1200. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1201. } else if ( order === 'YXZ' ) {
  1202. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1203. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1204. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1205. } else if ( order === 'ZXY' ) {
  1206. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1207. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1208. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1209. } else if ( order === 'ZYX' ) {
  1210. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1211. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1212. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1213. } else if ( order === 'YZX' ) {
  1214. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1215. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1216. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1217. } else if ( order === 'XZY' ) {
  1218. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1219. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1220. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1221. }
  1222. return this;
  1223. },
  1224. getScaleFromMatrix: function ( m ) {
  1225. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1226. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1227. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1228. this.x = sx;
  1229. this.y = sy;
  1230. this.z = sz;
  1231. return this;
  1232. },
  1233. equals: function ( v ) {
  1234. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1235. },
  1236. clone: function () {
  1237. return new THREE.Vector3( this.x, this.y, this.z );
  1238. }
  1239. } );
  1240. /**
  1241. * @author supereggbert / http://www.paulbrunt.co.uk/
  1242. * @author philogb / http://blog.thejit.org/
  1243. * @author mikael emtinger / http://gomo.se/
  1244. * @author egraether / http://egraether.com/
  1245. * @author WestLangley / http://github.com/WestLangley
  1246. */
  1247. THREE.Vector4 = function ( x, y, z, w ) {
  1248. this.x = x || 0;
  1249. this.y = y || 0;
  1250. this.z = z || 0;
  1251. this.w = ( w !== undefined ) ? w : 1;
  1252. };
  1253. THREE.extend( THREE.Vector4.prototype, {
  1254. set: function ( x, y, z, w ) {
  1255. this.x = x;
  1256. this.y = y;
  1257. this.z = z;
  1258. this.w = w;
  1259. return this;
  1260. },
  1261. setX: function ( x ) {
  1262. this.x = x;
  1263. return this;
  1264. },
  1265. setY: function ( y ) {
  1266. this.y = y;
  1267. return this;
  1268. },
  1269. setZ: function ( z ) {
  1270. this.z = z;
  1271. return this;
  1272. },
  1273. setW: function ( w ) {
  1274. this.w = w;
  1275. return this;
  1276. },
  1277. setComponent: function ( index, value ) {
  1278. switch ( index ) {
  1279. case 0: this.x = value; break;
  1280. case 1: this.y = value; break;
  1281. case 2: this.z = value; break;
  1282. case 3: this.w = value; break;
  1283. default: throw new Error( "index is out of range: " + index );
  1284. }
  1285. },
  1286. getComponent: function ( index ) {
  1287. switch ( index ) {
  1288. case 0: return this.x;
  1289. case 1: return this.y;
  1290. case 2: return this.z;
  1291. case 3: return this.w;
  1292. default: throw new Error( "index is out of range: " + index );
  1293. }
  1294. },
  1295. copy: function ( v ) {
  1296. this.x = v.x;
  1297. this.y = v.y;
  1298. this.z = v.z;
  1299. this.w = ( v.w !== undefined ) ? v.w : 1;
  1300. return this;
  1301. },
  1302. add: function ( v, w ) {
  1303. if ( w !== undefined ) {
  1304. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1305. return this.addVectors( v, w );
  1306. }
  1307. this.x += v.x;
  1308. this.y += v.y;
  1309. this.z += v.z;
  1310. this.w += v.w;
  1311. return this;
  1312. },
  1313. addScalar: function ( s ) {
  1314. this.x += s;
  1315. this.y += s;
  1316. this.z += s;
  1317. this.w += s;
  1318. return this;
  1319. },
  1320. addVectors: function ( a, b ) {
  1321. this.x = a.x + b.x;
  1322. this.y = a.y + b.y;
  1323. this.z = a.z + b.z;
  1324. this.w = a.w + b.w;
  1325. return this;
  1326. },
  1327. sub: function ( v, w ) {
  1328. if ( w !== undefined ) {
  1329. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1330. return this.subVectors( v, w );
  1331. }
  1332. this.x -= v.x;
  1333. this.y -= v.y;
  1334. this.z -= v.z;
  1335. this.w -= v.w;
  1336. return this;
  1337. },
  1338. subVectors: function ( a, b ) {
  1339. this.x = a.x - b.x;
  1340. this.y = a.y - b.y;
  1341. this.z = a.z - b.z;
  1342. this.w = a.w - b.w;
  1343. return this;
  1344. },
  1345. multiplyScalar: function ( s ) {
  1346. this.x *= s;
  1347. this.y *= s;
  1348. this.z *= s;
  1349. this.w *= s;
  1350. return this;
  1351. },
  1352. applyMatrix4: function ( m ) {
  1353. var x = this.x;
  1354. var y = this.y;
  1355. var z = this.z;
  1356. var w = this.w;
  1357. var e = m.elements;
  1358. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1359. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1360. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1361. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1362. return this;
  1363. },
  1364. divideScalar: function ( s ) {
  1365. if ( s !== 0 ) {
  1366. this.x /= s;
  1367. this.y /= s;
  1368. this.z /= s;
  1369. this.w /= s;
  1370. } else {
  1371. this.x = 0;
  1372. this.y = 0;
  1373. this.z = 0;
  1374. this.w = 1;
  1375. }
  1376. return this;
  1377. },
  1378. min: function ( v ) {
  1379. if ( this.x > v.x ) {
  1380. this.x = v.x;
  1381. }
  1382. if ( this.y > v.y ) {
  1383. this.y = v.y;
  1384. }
  1385. if ( this.z > v.z ) {
  1386. this.z = v.z;
  1387. }
  1388. if ( this.w > v.w ) {
  1389. this.w = v.w;
  1390. }
  1391. return this;
  1392. },
  1393. max: function ( v ) {
  1394. if ( this.x < v.x ) {
  1395. this.x = v.x;
  1396. }
  1397. if ( this.y < v.y ) {
  1398. this.y = v.y;
  1399. }
  1400. if ( this.z < v.z ) {
  1401. this.z = v.z;
  1402. }
  1403. if ( this.w < v.w ) {
  1404. this.w = v.w;
  1405. }
  1406. return this;
  1407. },
  1408. clamp: function ( min, max ) {
  1409. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1410. if ( this.x < min.x ) {
  1411. this.x = min.x;
  1412. } else if ( this.x > max.x ) {
  1413. this.x = max.x;
  1414. }
  1415. if ( this.y < min.y ) {
  1416. this.y = min.y;
  1417. } else if ( this.y > max.y ) {
  1418. this.y = max.y;
  1419. }
  1420. if ( this.z < min.z ) {
  1421. this.z = min.z;
  1422. } else if ( this.z > max.z ) {
  1423. this.z = max.z;
  1424. }
  1425. if ( this.w < min.w ) {
  1426. this.w = min.w;
  1427. } else if ( this.w > max.w ) {
  1428. this.w = max.w;
  1429. }
  1430. return this;
  1431. },
  1432. negate: function() {
  1433. return this.multiplyScalar( -1 );
  1434. },
  1435. dot: function ( v ) {
  1436. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1437. },
  1438. lengthSq: function () {
  1439. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1440. },
  1441. length: function () {
  1442. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1443. },
  1444. lengthManhattan: function () {
  1445. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1446. },
  1447. normalize: function () {
  1448. return this.divideScalar( this.length() );
  1449. },
  1450. setLength: function ( l ) {
  1451. var oldLength = this.length();
  1452. if ( oldLength !== 0 && l !== oldLength ) {
  1453. this.multiplyScalar( l / oldLength );
  1454. }
  1455. return this;
  1456. },
  1457. lerp: function ( v, alpha ) {
  1458. this.x += ( v.x - this.x ) * alpha;
  1459. this.y += ( v.y - this.y ) * alpha;
  1460. this.z += ( v.z - this.z ) * alpha;
  1461. this.w += ( v.w - this.w ) * alpha;
  1462. return this;
  1463. },
  1464. equals: function ( v ) {
  1465. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1466. },
  1467. clone: function () {
  1468. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1469. },
  1470. setAxisAngleFromQuaternion: function ( q ) {
  1471. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1472. // q is assumed to be normalized
  1473. this.w = 2 * Math.acos( q.w );
  1474. var s = Math.sqrt( 1 - q.w * q.w );
  1475. if ( s < 0.0001 ) {
  1476. this.x = 1;
  1477. this.y = 0;
  1478. this.z = 0;
  1479. } else {
  1480. this.x = q.x / s;
  1481. this.y = q.y / s;
  1482. this.z = q.z / s;
  1483. }
  1484. return this;
  1485. },
  1486. setAxisAngleFromRotationMatrix: function ( m ) {
  1487. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1488. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1489. var angle, x, y, z, // variables for result
  1490. epsilon = 0.01, // margin to allow for rounding errors
  1491. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1492. te = m.elements,
  1493. m11 = te[0], m12 = te[4], m13 = te[8],
  1494. m21 = te[1], m22 = te[5], m23 = te[9],
  1495. m31 = te[2], m32 = te[6], m33 = te[10];
  1496. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1497. && ( Math.abs( m13 - m31 ) < epsilon )
  1498. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1499. // singularity found
  1500. // first check for identity matrix which must have +1 for all terms
  1501. // in leading diagonal and zero in other terms
  1502. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1503. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1504. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1505. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1506. // this singularity is identity matrix so angle = 0
  1507. this.set( 1, 0, 0, 0 );
  1508. return this; // zero angle, arbitrary axis
  1509. }
  1510. // otherwise this singularity is angle = 180
  1511. angle = Math.PI;
  1512. var xx = ( m11 + 1 ) / 2;
  1513. var yy = ( m22 + 1 ) / 2;
  1514. var zz = ( m33 + 1 ) / 2;
  1515. var xy = ( m12 + m21 ) / 4;
  1516. var xz = ( m13 + m31 ) / 4;
  1517. var yz = ( m23 + m32 ) / 4;
  1518. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1519. if ( xx < epsilon ) {
  1520. x = 0;
  1521. y = 0.707106781;
  1522. z = 0.707106781;
  1523. } else {
  1524. x = Math.sqrt( xx );
  1525. y = xy / x;
  1526. z = xz / x;
  1527. }
  1528. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1529. if ( yy < epsilon ) {
  1530. x = 0.707106781;
  1531. y = 0;
  1532. z = 0.707106781;
  1533. } else {
  1534. y = Math.sqrt( yy );
  1535. x = xy / y;
  1536. z = yz / y;
  1537. }
  1538. } else { // m33 is the largest diagonal term so base result on this
  1539. if ( zz < epsilon ) {
  1540. x = 0.707106781;
  1541. y = 0.707106781;
  1542. z = 0;
  1543. } else {
  1544. z = Math.sqrt( zz );
  1545. x = xz / z;
  1546. y = yz / z;
  1547. }
  1548. }
  1549. this.set( x, y, z, angle );
  1550. return this; // return 180 deg rotation
  1551. }
  1552. // as we have reached here there are no singularities so we can handle normally
  1553. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1554. + ( m13 - m31 ) * ( m13 - m31 )
  1555. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1556. if ( Math.abs( s ) < 0.001 ) s = 1;
  1557. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1558. // caught by singularity test above, but I've left it in just in case
  1559. this.x = ( m32 - m23 ) / s;
  1560. this.y = ( m13 - m31 ) / s;
  1561. this.z = ( m21 - m12 ) / s;
  1562. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1563. return this;
  1564. }
  1565. } );
  1566. /**
  1567. * @author bhouston / http://exocortex.com
  1568. */
  1569. THREE.Box2 = function ( min, max ) {
  1570. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1571. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1572. };
  1573. THREE.extend( THREE.Box2.prototype, {
  1574. set: function ( min, max ) {
  1575. this.min.copy( min );
  1576. this.max.copy( max );
  1577. return this;
  1578. },
  1579. setFromPoints: function ( points ) {
  1580. if ( points.length > 0 ) {
  1581. var point = points[ 0 ];
  1582. this.min.copy( point );
  1583. this.max.copy( point );
  1584. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1585. point = points[ i ];
  1586. if ( point.x < this.min.x ) {
  1587. this.min.x = point.x;
  1588. } else if ( point.x > this.max.x ) {
  1589. this.max.x = point.x;
  1590. }
  1591. if ( point.y < this.min.y ) {
  1592. this.min.y = point.y;
  1593. } else if ( point.y > this.max.y ) {
  1594. this.max.y = point.y;
  1595. }
  1596. }
  1597. } else {
  1598. this.makeEmpty();
  1599. }
  1600. return this;
  1601. },
  1602. setFromCenterAndSize: function() {
  1603. var v1 = new THREE.Vector2();
  1604. return function ( center, size ) {
  1605. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1606. this.min.copy( center ).sub( halfSize );
  1607. this.max.copy( center ).add( halfSize );
  1608. return this;
  1609. };
  1610. }(),
  1611. copy: function ( box ) {
  1612. this.min.copy( box.min );
  1613. this.max.copy( box.max );
  1614. return this;
  1615. },
  1616. makeEmpty: function () {
  1617. this.min.x = this.min.y = Infinity;
  1618. this.max.x = this.max.y = -Infinity;
  1619. return this;
  1620. },
  1621. empty: function () {
  1622. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1623. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1624. },
  1625. center: function ( optionalTarget ) {
  1626. var result = optionalTarget || new THREE.Vector2();
  1627. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1628. },
  1629. size: function ( optionalTarget ) {
  1630. var result = optionalTarget || new THREE.Vector2();
  1631. return result.subVectors( this.max, this.min );
  1632. },
  1633. expandByPoint: function ( point ) {
  1634. this.min.min( point );
  1635. this.max.max( point );
  1636. return this;
  1637. },
  1638. expandByVector: function ( vector ) {
  1639. this.min.sub( vector );
  1640. this.max.add( vector );
  1641. return this;
  1642. },
  1643. expandByScalar: function ( scalar ) {
  1644. this.min.addScalar( -scalar );
  1645. this.max.addScalar( scalar );
  1646. return this;
  1647. },
  1648. containsPoint: function ( point ) {
  1649. if ( point.x < this.min.x || point.x > this.max.x ||
  1650. point.y < this.min.y || point.y > this.max.y ) {
  1651. return false;
  1652. }
  1653. return true;
  1654. },
  1655. containsBox: function ( box ) {
  1656. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1657. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1658. return true;
  1659. }
  1660. return false;
  1661. },
  1662. getParameter: function ( point ) {
  1663. // This can potentially have a divide by zero if the box
  1664. // has a size dimension of 0.
  1665. return new THREE.Vector2(
  1666. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1667. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1668. );
  1669. },
  1670. isIntersectionBox: function ( box ) {
  1671. // using 6 splitting planes to rule out intersections.
  1672. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1673. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1674. return false;
  1675. }
  1676. return true;
  1677. },
  1678. clampPoint: function ( point, optionalTarget ) {
  1679. var result = optionalTarget || new THREE.Vector2();
  1680. return result.copy( point ).clamp( this.min, this.max );
  1681. },
  1682. distanceToPoint: function() {
  1683. var v1 = new THREE.Vector2();
  1684. return function ( point ) {
  1685. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1686. return clampedPoint.sub( point ).length();
  1687. };
  1688. }(),
  1689. intersect: function ( box ) {
  1690. this.min.max( box.min );
  1691. this.max.min( box.max );
  1692. return this;
  1693. },
  1694. union: function ( box ) {
  1695. this.min.min( box.min );
  1696. this.max.max( box.max );
  1697. return this;
  1698. },
  1699. translate: function ( offset ) {
  1700. this.min.add( offset );
  1701. this.max.add( offset );
  1702. return this;
  1703. },
  1704. equals: function ( box ) {
  1705. return box.min.equals( this.min ) && box.max.equals( this.max );
  1706. },
  1707. clone: function () {
  1708. return new THREE.Box2().copy( this );
  1709. }
  1710. } );
  1711. /**
  1712. * @author bhouston / http://exocortex.com
  1713. */
  1714. THREE.Box3 = function ( min, max ) {
  1715. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1716. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1717. };
  1718. THREE.extend( THREE.Box3.prototype, {
  1719. set: function ( min, max ) {
  1720. this.min.copy( min );
  1721. this.max.copy( max );
  1722. return this;
  1723. },
  1724. setFromPoints: function ( points ) {
  1725. if ( points.length > 0 ) {
  1726. var point = points[ 0 ];
  1727. this.min.copy( point );
  1728. this.max.copy( point );
  1729. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1730. point = points[ i ];
  1731. if ( point.x < this.min.x ) {
  1732. this.min.x = point.x;
  1733. } else if ( point.x > this.max.x ) {
  1734. this.max.x = point.x;
  1735. }
  1736. if ( point.y < this.min.y ) {
  1737. this.min.y = point.y;
  1738. } else if ( point.y > this.max.y ) {
  1739. this.max.y = point.y;
  1740. }
  1741. if ( point.z < this.min.z ) {
  1742. this.min.z = point.z;
  1743. } else if ( point.z > this.max.z ) {
  1744. this.max.z = point.z;
  1745. }
  1746. }
  1747. } else {
  1748. this.makeEmpty();
  1749. }
  1750. return this;
  1751. },
  1752. setFromCenterAndSize: function() {
  1753. var v1 = new THREE.Vector3();
  1754. return function ( center, size ) {
  1755. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1756. this.min.copy( center ).sub( halfSize );
  1757. this.max.copy( center ).add( halfSize );
  1758. return this;
  1759. };
  1760. }(),
  1761. copy: function ( box ) {
  1762. this.min.copy( box.min );
  1763. this.max.copy( box.max );
  1764. return this;
  1765. },
  1766. makeEmpty: function () {
  1767. this.min.x = this.min.y = this.min.z = Infinity;
  1768. this.max.x = this.max.y = this.max.z = -Infinity;
  1769. return this;
  1770. },
  1771. empty: function () {
  1772. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1773. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1774. },
  1775. center: function ( optionalTarget ) {
  1776. var result = optionalTarget || new THREE.Vector3();
  1777. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1778. },
  1779. size: function ( optionalTarget ) {
  1780. var result = optionalTarget || new THREE.Vector3();
  1781. return result.subVectors( this.max, this.min );
  1782. },
  1783. expandByPoint: function ( point ) {
  1784. this.min.min( point );
  1785. this.max.max( point );
  1786. return this;
  1787. },
  1788. expandByVector: function ( vector ) {
  1789. this.min.sub( vector );
  1790. this.max.add( vector );
  1791. return this;
  1792. },
  1793. expandByScalar: function ( scalar ) {
  1794. this.min.addScalar( -scalar );
  1795. this.max.addScalar( scalar );
  1796. return this;
  1797. },
  1798. containsPoint: function ( point ) {
  1799. if ( point.x < this.min.x || point.x > this.max.x ||
  1800. point.y < this.min.y || point.y > this.max.y ||
  1801. point.z < this.min.z || point.z > this.max.z ) {
  1802. return false;
  1803. }
  1804. return true;
  1805. },
  1806. containsBox: function ( box ) {
  1807. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1808. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1809. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1810. return true;
  1811. }
  1812. return false;
  1813. },
  1814. getParameter: function ( point ) {
  1815. // This can potentially have a divide by zero if the box
  1816. // has a size dimension of 0.
  1817. return new THREE.Vector3(
  1818. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1819. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1820. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1821. );
  1822. },
  1823. isIntersectionBox: function ( box ) {
  1824. // using 6 splitting planes to rule out intersections.
  1825. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1826. box.max.y < this.min.y || box.min.y > this.max.y ||
  1827. box.max.z < this.min.z || box.min.z > this.max.z ) {
  1828. return false;
  1829. }
  1830. return true;
  1831. },
  1832. clampPoint: function ( point, optionalTarget ) {
  1833. var result = optionalTarget || new THREE.Vector3();
  1834. return result.copy( point ).clamp( this.min, this.max );
  1835. },
  1836. distanceToPoint: function() {
  1837. var v1 = new THREE.Vector3();
  1838. return function ( point ) {
  1839. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1840. return clampedPoint.sub( point ).length();
  1841. };
  1842. }(),
  1843. getBoundingSphere: function() {
  1844. var v1 = new THREE.Vector3();
  1845. return function ( optionalTarget ) {
  1846. var result = optionalTarget || new THREE.Sphere();
  1847. result.center = this.center();
  1848. result.radius = this.size( v1 ).length() * 0.5;
  1849. return result;
  1850. };
  1851. }(),
  1852. intersect: function ( box ) {
  1853. this.min.max( box.min );
  1854. this.max.min( box.max );
  1855. return this;
  1856. },
  1857. union: function ( box ) {
  1858. this.min.min( box.min );
  1859. this.max.max( box.max );
  1860. return this;
  1861. },
  1862. transform: function() {
  1863. var points = [
  1864. new THREE.Vector3(),
  1865. new THREE.Vector3(),
  1866. new THREE.Vector3(),
  1867. new THREE.Vector3(),
  1868. new THREE.Vector3(),
  1869. new THREE.Vector3(),
  1870. new THREE.Vector3(),
  1871. new THREE.Vector3()
  1872. ];
  1873. return function ( matrix ) {
  1874. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1875. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  1876. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  1877. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  1878. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  1879. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  1880. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  1881. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  1882. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  1883. this.makeEmpty();
  1884. this.setFromPoints( points );
  1885. return this;
  1886. };
  1887. }(),
  1888. translate: function ( offset ) {
  1889. this.min.add( offset );
  1890. this.max.add( offset );
  1891. return this;
  1892. },
  1893. equals: function ( box ) {
  1894. return box.min.equals( this.min ) && box.max.equals( this.max );
  1895. },
  1896. clone: function () {
  1897. return new THREE.Box3().copy( this );
  1898. }
  1899. } );
  1900. /**
  1901. * @author alteredq / http://alteredqualia.com/
  1902. * @author WestLangley / http://github.com/WestLangley
  1903. * @author bhouston / http://exocortex.com
  1904. */
  1905. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1906. this.elements = new Float32Array(9);
  1907. this.set(
  1908. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  1909. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  1910. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  1911. );
  1912. };
  1913. THREE.extend( THREE.Matrix3.prototype, {
  1914. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1915. var te = this.elements;
  1916. te[0] = n11; te[3] = n12; te[6] = n13;
  1917. te[1] = n21; te[4] = n22; te[7] = n23;
  1918. te[2] = n31; te[5] = n32; te[8] = n33;
  1919. return this;
  1920. },
  1921. identity: function () {
  1922. this.set(
  1923. 1, 0, 0,
  1924. 0, 1, 0,
  1925. 0, 0, 1
  1926. );
  1927. return this;
  1928. },
  1929. copy: function ( m ) {
  1930. var me = m.elements;
  1931. this.set(
  1932. me[0], me[3], me[6],
  1933. me[1], me[4], me[7],
  1934. me[2], me[5], me[8]
  1935. );
  1936. return this;
  1937. },
  1938. multiplyVector3: function ( vector ) {
  1939. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  1940. return vector.applyMatrix3( this );
  1941. },
  1942. multiplyVector3Array: function() {
  1943. var v1 = new THREE.Vector3();
  1944. return function ( a ) {
  1945. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1946. v1.x = a[ i ];
  1947. v1.y = a[ i + 1 ];
  1948. v1.z = a[ i + 2 ];
  1949. v1.applyMatrix3(this);
  1950. a[ i ] = v1.x;
  1951. a[ i + 1 ] = v1.y;
  1952. a[ i + 2 ] = v1.z;
  1953. }
  1954. return a;
  1955. };
  1956. }(),
  1957. multiplyScalar: function ( s ) {
  1958. var te = this.elements;
  1959. te[0] *= s; te[3] *= s; te[6] *= s;
  1960. te[1] *= s; te[4] *= s; te[7] *= s;
  1961. te[2] *= s; te[5] *= s; te[8] *= s;
  1962. return this;
  1963. },
  1964. determinant: function () {
  1965. var te = this.elements;
  1966. var a = te[0], b = te[1], c = te[2],
  1967. d = te[3], e = te[4], f = te[5],
  1968. g = te[6], h = te[7], i = te[8];
  1969. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  1970. },
  1971. getInverse: function ( matrix, throwOnInvertible ) {
  1972. // input: THREE.Matrix4
  1973. // ( based on http://code.google.com/p/webgl-mjs/ )
  1974. var me = matrix.elements;
  1975. var te = this.elements;
  1976. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  1977. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  1978. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  1979. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  1980. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  1981. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  1982. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  1983. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  1984. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  1985. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  1986. // no inverse
  1987. if ( det === 0 ) {
  1988. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  1989. if ( throwOnInvertible || false ) {
  1990. throw new Error( msg );
  1991. } else {
  1992. console.warn( msg );
  1993. }
  1994. this.identity();
  1995. return this;
  1996. }
  1997. this.multiplyScalar( 1.0 / det );
  1998. return this;
  1999. },
  2000. transpose: function () {
  2001. var tmp, m = this.elements;
  2002. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2003. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2004. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2005. return this;
  2006. },
  2007. getNormalMatrix: function ( m ) {
  2008. // input: THREE.Matrix4
  2009. this.getInverse( m ).transpose();
  2010. return this;
  2011. },
  2012. transposeIntoArray: function ( r ) {
  2013. var m = this.elements;
  2014. r[ 0 ] = m[ 0 ];
  2015. r[ 1 ] = m[ 3 ];
  2016. r[ 2 ] = m[ 6 ];
  2017. r[ 3 ] = m[ 1 ];
  2018. r[ 4 ] = m[ 4 ];
  2019. r[ 5 ] = m[ 7 ];
  2020. r[ 6 ] = m[ 2 ];
  2021. r[ 7 ] = m[ 5 ];
  2022. r[ 8 ] = m[ 8 ];
  2023. return this;
  2024. },
  2025. clone: function () {
  2026. var te = this.elements;
  2027. return new THREE.Matrix3(
  2028. te[0], te[3], te[6],
  2029. te[1], te[4], te[7],
  2030. te[2], te[5], te[8]
  2031. );
  2032. }
  2033. } );
  2034. /**
  2035. * @author mrdoob / http://mrdoob.com/
  2036. * @author supereggbert / http://www.paulbrunt.co.uk/
  2037. * @author philogb / http://blog.thejit.org/
  2038. * @author jordi_ros / http://plattsoft.com
  2039. * @author D1plo1d / http://github.com/D1plo1d
  2040. * @author alteredq / http://alteredqualia.com/
  2041. * @author mikael emtinger / http://gomo.se/
  2042. * @author timknip / http://www.floorplanner.com/
  2043. * @author bhouston / http://exocortex.com
  2044. */
  2045. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2046. var te = this.elements = new Float32Array( 16 );
  2047. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2048. // we should not support semi specification of Matrix4, it is just weird.
  2049. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2050. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2051. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2052. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2053. };
  2054. THREE.extend( THREE.Matrix4.prototype, {
  2055. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2056. var te = this.elements;
  2057. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2058. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2059. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2060. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2061. return this;
  2062. },
  2063. identity: function () {
  2064. this.set(
  2065. 1, 0, 0, 0,
  2066. 0, 1, 0, 0,
  2067. 0, 0, 1, 0,
  2068. 0, 0, 0, 1
  2069. );
  2070. return this;
  2071. },
  2072. copy: function ( m ) {
  2073. var me = m.elements;
  2074. this.set(
  2075. me[0], me[4], me[8], me[12],
  2076. me[1], me[5], me[9], me[13],
  2077. me[2], me[6], me[10], me[14],
  2078. me[3], me[7], me[11], me[15]
  2079. );
  2080. return this;
  2081. },
  2082. setRotationFromEuler: function ( v, order ) {
  2083. var te = this.elements;
  2084. var x = v.x, y = v.y, z = v.z;
  2085. var a = Math.cos( x ), b = Math.sin( x );
  2086. var c = Math.cos( y ), d = Math.sin( y );
  2087. var e = Math.cos( z ), f = Math.sin( z );
  2088. if ( order === undefined || order === 'XYZ' ) {
  2089. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2090. te[0] = c * e;
  2091. te[4] = - c * f;
  2092. te[8] = d;
  2093. te[1] = af + be * d;
  2094. te[5] = ae - bf * d;
  2095. te[9] = - b * c;
  2096. te[2] = bf - ae * d;
  2097. te[6] = be + af * d;
  2098. te[10] = a * c;
  2099. } else if ( order === 'YXZ' ) {
  2100. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2101. te[0] = ce + df * b;
  2102. te[4] = de * b - cf;
  2103. te[8] = a * d;
  2104. te[1] = a * f;
  2105. te[5] = a * e;
  2106. te[9] = - b;
  2107. te[2] = cf * b - de;
  2108. te[6] = df + ce * b;
  2109. te[10] = a * c;
  2110. } else if ( order === 'ZXY' ) {
  2111. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2112. te[0] = ce - df * b;
  2113. te[4] = - a * f;
  2114. te[8] = de + cf * b;
  2115. te[1] = cf + de * b;
  2116. te[5] = a * e;
  2117. te[9] = df - ce * b;
  2118. te[2] = - a * d;
  2119. te[6] = b;
  2120. te[10] = a * c;
  2121. } else if ( order === 'ZYX' ) {
  2122. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2123. te[0] = c * e;
  2124. te[4] = be * d - af;
  2125. te[8] = ae * d + bf;
  2126. te[1] = c * f;
  2127. te[5] = bf * d + ae;
  2128. te[9] = af * d - be;
  2129. te[2] = - d;
  2130. te[6] = b * c;
  2131. te[10] = a * c;
  2132. } else if ( order === 'YZX' ) {
  2133. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2134. te[0] = c * e;
  2135. te[4] = bd - ac * f;
  2136. te[8] = bc * f + ad;
  2137. te[1] = f;
  2138. te[5] = a * e;
  2139. te[9] = - b * e;
  2140. te[2] = - d * e;
  2141. te[6] = ad * f + bc;
  2142. te[10] = ac - bd * f;
  2143. } else if ( order === 'XZY' ) {
  2144. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2145. te[0] = c * e;
  2146. te[4] = - f;
  2147. te[8] = d * e;
  2148. te[1] = ac * f + bd;
  2149. te[5] = a * e;
  2150. te[9] = ad * f - bc;
  2151. te[2] = bc * f - ad;
  2152. te[6] = b * e;
  2153. te[10] = bd * f + ac;
  2154. }
  2155. return this;
  2156. },
  2157. setRotationFromQuaternion: function ( q ) {
  2158. var te = this.elements;
  2159. var x = q.x, y = q.y, z = q.z, w = q.w;
  2160. var x2 = x + x, y2 = y + y, z2 = z + z;
  2161. var xx = x * x2, xy = x * y2, xz = x * z2;
  2162. var yy = y * y2, yz = y * z2, zz = z * z2;
  2163. var wx = w * x2, wy = w * y2, wz = w * z2;
  2164. te[0] = 1 - ( yy + zz );
  2165. te[4] = xy - wz;
  2166. te[8] = xz + wy;
  2167. te[1] = xy + wz;
  2168. te[5] = 1 - ( xx + zz );
  2169. te[9] = yz - wx;
  2170. te[2] = xz - wy;
  2171. te[6] = yz + wx;
  2172. te[10] = 1 - ( xx + yy );
  2173. return this;
  2174. },
  2175. lookAt: function() {
  2176. var x = new THREE.Vector3();
  2177. var y = new THREE.Vector3();
  2178. var z = new THREE.Vector3();
  2179. return function ( eye, target, up ) {
  2180. var te = this.elements;
  2181. z.subVectors( eye, target ).normalize();
  2182. if ( z.length() === 0 ) {
  2183. z.z = 1;
  2184. }
  2185. x.crossVectors( up, z ).normalize();
  2186. if ( x.length() === 0 ) {
  2187. z.x += 0.0001;
  2188. x.crossVectors( up, z ).normalize();
  2189. }
  2190. y.crossVectors( z, x );
  2191. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2192. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2193. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2194. return this;
  2195. };
  2196. }(),
  2197. multiply: function ( m, n ) {
  2198. if ( n !== undefined ) {
  2199. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2200. return this.multiplyMatrices( m, n );
  2201. }
  2202. return this.multiplyMatrices( this, m );
  2203. },
  2204. multiplyMatrices: function ( a, b ) {
  2205. var ae = a.elements;
  2206. var be = b.elements;
  2207. var te = this.elements;
  2208. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2209. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2210. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2211. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2212. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2213. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2214. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2215. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2216. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2217. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2218. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2219. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2220. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2221. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2222. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2223. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2224. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2225. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2226. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2227. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2228. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2229. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2230. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2231. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2232. return this;
  2233. },
  2234. multiplyToArray: function ( a, b, r ) {
  2235. var te = this.elements;
  2236. this.multiplyMatrices( a, b );
  2237. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2238. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2239. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2240. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2241. return this;
  2242. },
  2243. multiplyScalar: function ( s ) {
  2244. var te = this.elements;
  2245. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2246. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2247. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2248. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2249. return this;
  2250. },
  2251. multiplyVector3: function ( vector ) {
  2252. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2253. return vector.applyProjection( this );
  2254. },
  2255. multiplyVector4: function ( vector ) {
  2256. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2257. return vector.applyMatrix4( this );
  2258. },
  2259. multiplyVector3Array: function() {
  2260. var v1 = new THREE.Vector3();
  2261. return function ( a ) {
  2262. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2263. v1.x = a[ i ];
  2264. v1.y = a[ i + 1 ];
  2265. v1.z = a[ i + 2 ];
  2266. v1.applyProjection( this );
  2267. a[ i ] = v1.x;
  2268. a[ i + 1 ] = v1.y;
  2269. a[ i + 2 ] = v1.z;
  2270. }
  2271. return a;
  2272. };
  2273. }(),
  2274. rotateAxis: function ( v ) {
  2275. var te = this.elements;
  2276. var vx = v.x, vy = v.y, vz = v.z;
  2277. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  2278. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  2279. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  2280. v.normalize();
  2281. return v;
  2282. },
  2283. crossVector: function ( a ) {
  2284. var te = this.elements;
  2285. var v = new THREE.Vector4();
  2286. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  2287. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  2288. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  2289. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  2290. return v;
  2291. },
  2292. determinant: function () {
  2293. var te = this.elements;
  2294. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2295. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2296. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2297. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2298. //TODO: make this more efficient
  2299. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2300. return (
  2301. n41 * (
  2302. +n14 * n23 * n32
  2303. -n13 * n24 * n32
  2304. -n14 * n22 * n33
  2305. +n12 * n24 * n33
  2306. +n13 * n22 * n34
  2307. -n12 * n23 * n34
  2308. ) +
  2309. n42 * (
  2310. +n11 * n23 * n34
  2311. -n11 * n24 * n33
  2312. +n14 * n21 * n33
  2313. -n13 * n21 * n34
  2314. +n13 * n24 * n31
  2315. -n14 * n23 * n31
  2316. ) +
  2317. n43 * (
  2318. +n11 * n24 * n32
  2319. -n11 * n22 * n34
  2320. -n14 * n21 * n32
  2321. +n12 * n21 * n34
  2322. +n14 * n22 * n31
  2323. -n12 * n24 * n31
  2324. ) +
  2325. n44 * (
  2326. -n13 * n22 * n31
  2327. -n11 * n23 * n32
  2328. +n11 * n22 * n33
  2329. +n13 * n21 * n32
  2330. -n12 * n21 * n33
  2331. +n12 * n23 * n31
  2332. )
  2333. );
  2334. },
  2335. transpose: function () {
  2336. var te = this.elements;
  2337. var tmp;
  2338. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2339. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2340. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2341. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2342. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2343. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2344. return this;
  2345. },
  2346. flattenToArray: function ( flat ) {
  2347. var te = this.elements;
  2348. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2349. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2350. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2351. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2352. return flat;
  2353. },
  2354. flattenToArrayOffset: function( flat, offset ) {
  2355. var te = this.elements;
  2356. flat[ offset ] = te[0];
  2357. flat[ offset + 1 ] = te[1];
  2358. flat[ offset + 2 ] = te[2];
  2359. flat[ offset + 3 ] = te[3];
  2360. flat[ offset + 4 ] = te[4];
  2361. flat[ offset + 5 ] = te[5];
  2362. flat[ offset + 6 ] = te[6];
  2363. flat[ offset + 7 ] = te[7];
  2364. flat[ offset + 8 ] = te[8];
  2365. flat[ offset + 9 ] = te[9];
  2366. flat[ offset + 10 ] = te[10];
  2367. flat[ offset + 11 ] = te[11];
  2368. flat[ offset + 12 ] = te[12];
  2369. flat[ offset + 13 ] = te[13];
  2370. flat[ offset + 14 ] = te[14];
  2371. flat[ offset + 15 ] = te[15];
  2372. return flat;
  2373. },
  2374. getPosition: function() {
  2375. var v1 = new THREE.Vector3();
  2376. return function () {
  2377. var te = this.elements;
  2378. return v1.set( te[12], te[13], te[14] );
  2379. };
  2380. }(),
  2381. setPosition: function ( v ) {
  2382. var te = this.elements;
  2383. te[12] = v.x;
  2384. te[13] = v.y;
  2385. te[14] = v.z;
  2386. return this;
  2387. },
  2388. getColumnX: function() {
  2389. var v1 = new THREE.Vector3();
  2390. return function () {
  2391. var te = this.elements;
  2392. return v1.set( te[0], te[1], te[2] );
  2393. };
  2394. }(),
  2395. getColumnY: function() {
  2396. var v1 = new THREE.Vector3();
  2397. return function () {
  2398. var te = this.elements;
  2399. return v1.set( te[4], te[5], te[6] );
  2400. };
  2401. }(),
  2402. getColumnZ: function() {
  2403. var v1 = new THREE.Vector3();
  2404. return function() {
  2405. var te = this.elements;
  2406. return v1.set( te[8], te[9], te[10] );
  2407. };
  2408. }(),
  2409. getInverse: function ( m, throwOnInvertible ) {
  2410. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2411. var te = this.elements;
  2412. var me = m.elements;
  2413. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2414. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2415. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2416. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2417. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2418. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2419. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2420. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2421. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2422. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2423. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2424. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2425. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2426. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2427. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2428. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2429. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2430. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2431. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2432. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2433. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2434. if ( det == 0 ) {
  2435. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2436. if ( throwOnInvertible || false ) {
  2437. throw new Error( msg );
  2438. } else {
  2439. console.warn( msg );
  2440. }
  2441. this.identity();
  2442. return this;
  2443. }
  2444. this.multiplyScalar( 1 / det );
  2445. return this;
  2446. },
  2447. compose: function() {
  2448. var mRotation = new THREE.Matrix4(),
  2449. mScale = new THREE.Matrix4();
  2450. return function ( translation, rotation, scale ) {
  2451. var te = this.elements;
  2452. mRotation.identity();
  2453. mRotation.setRotationFromQuaternion( rotation );
  2454. mScale.makeScale( scale.x, scale.y, scale.z );
  2455. this.multiplyMatrices( mRotation, mScale );
  2456. te[12] = translation.x;
  2457. te[13] = translation.y;
  2458. te[14] = translation.z;
  2459. return this;
  2460. };
  2461. }(),
  2462. decompose: function() {
  2463. var x = new THREE.Vector3(),
  2464. y = new THREE.Vector3(),
  2465. z = new THREE.Vector3(),
  2466. matrix = new THREE.Matrix4();
  2467. return function ( translation, rotation, scale ) {
  2468. var te = this.elements;
  2469. // grab the axis vectors
  2470. x.set( te[0], te[1], te[2] );
  2471. y.set( te[4], te[5], te[6] );
  2472. z.set( te[8], te[9], te[10] );
  2473. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  2474. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  2475. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2476. scale.x = x.length();
  2477. scale.y = y.length();
  2478. scale.z = z.length();
  2479. translation.x = te[12];
  2480. translation.y = te[13];
  2481. translation.z = te[14];
  2482. // scale the rotation part
  2483. matrix.copy( this );
  2484. matrix.elements[0] /= scale.x;
  2485. matrix.elements[1] /= scale.x;
  2486. matrix.elements[2] /= scale.x;
  2487. matrix.elements[4] /= scale.y;
  2488. matrix.elements[5] /= scale.y;
  2489. matrix.elements[6] /= scale.y;
  2490. matrix.elements[8] /= scale.z;
  2491. matrix.elements[9] /= scale.z;
  2492. matrix.elements[10] /= scale.z;
  2493. rotation.setFromRotationMatrix( matrix );
  2494. return [ translation, rotation, scale ];
  2495. };
  2496. }(),
  2497. extractPosition: function ( m ) {
  2498. var te = this.elements;
  2499. var me = m.elements;
  2500. te[12] = me[12];
  2501. te[13] = me[13];
  2502. te[14] = me[14];
  2503. return this;
  2504. },
  2505. extractRotation: function() {
  2506. var v1 = new THREE.Vector3();
  2507. return function ( m ) {
  2508. var te = this.elements;
  2509. var me = m.elements;
  2510. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2511. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2512. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2513. te[0] = me[0] * scaleX;
  2514. te[1] = me[1] * scaleX;
  2515. te[2] = me[2] * scaleX;
  2516. te[4] = me[4] * scaleY;
  2517. te[5] = me[5] * scaleY;
  2518. te[6] = me[6] * scaleY;
  2519. te[8] = me[8] * scaleZ;
  2520. te[9] = me[9] * scaleZ;
  2521. te[10] = me[10] * scaleZ;
  2522. return this;
  2523. };
  2524. }(),
  2525. translate: function ( v ) {
  2526. var te = this.elements;
  2527. var x = v.x, y = v.y, z = v.z;
  2528. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  2529. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  2530. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  2531. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  2532. return this;
  2533. },
  2534. rotateX: function ( angle ) {
  2535. var te = this.elements;
  2536. var m12 = te[4];
  2537. var m22 = te[5];
  2538. var m32 = te[6];
  2539. var m42 = te[7];
  2540. var m13 = te[8];
  2541. var m23 = te[9];
  2542. var m33 = te[10];
  2543. var m43 = te[11];
  2544. var c = Math.cos( angle );
  2545. var s = Math.sin( angle );
  2546. te[4] = c * m12 + s * m13;
  2547. te[5] = c * m22 + s * m23;
  2548. te[6] = c * m32 + s * m33;
  2549. te[7] = c * m42 + s * m43;
  2550. te[8] = c * m13 - s * m12;
  2551. te[9] = c * m23 - s * m22;
  2552. te[10] = c * m33 - s * m32;
  2553. te[11] = c * m43 - s * m42;
  2554. return this;
  2555. },
  2556. rotateY: function ( angle ) {
  2557. var te = this.elements;
  2558. var m11 = te[0];
  2559. var m21 = te[1];
  2560. var m31 = te[2];
  2561. var m41 = te[3];
  2562. var m13 = te[8];
  2563. var m23 = te[9];
  2564. var m33 = te[10];
  2565. var m43 = te[11];
  2566. var c = Math.cos( angle );
  2567. var s = Math.sin( angle );
  2568. te[0] = c * m11 - s * m13;
  2569. te[1] = c * m21 - s * m23;
  2570. te[2] = c * m31 - s * m33;
  2571. te[3] = c * m41 - s * m43;
  2572. te[8] = c * m13 + s * m11;
  2573. te[9] = c * m23 + s * m21;
  2574. te[10] = c * m33 + s * m31;
  2575. te[11] = c * m43 + s * m41;
  2576. return this;
  2577. },
  2578. rotateZ: function ( angle ) {
  2579. var te = this.elements;
  2580. var m11 = te[0];
  2581. var m21 = te[1];
  2582. var m31 = te[2];
  2583. var m41 = te[3];
  2584. var m12 = te[4];
  2585. var m22 = te[5];
  2586. var m32 = te[6];
  2587. var m42 = te[7];
  2588. var c = Math.cos( angle );
  2589. var s = Math.sin( angle );
  2590. te[0] = c * m11 + s * m12;
  2591. te[1] = c * m21 + s * m22;
  2592. te[2] = c * m31 + s * m32;
  2593. te[3] = c * m41 + s * m42;
  2594. te[4] = c * m12 - s * m11;
  2595. te[5] = c * m22 - s * m21;
  2596. te[6] = c * m32 - s * m31;
  2597. te[7] = c * m42 - s * m41;
  2598. return this;
  2599. },
  2600. rotateByAxis: function ( axis, angle ) {
  2601. var te = this.elements;
  2602. // optimize by checking axis
  2603. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2604. return this.rotateX( angle );
  2605. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2606. return this.rotateY( angle );
  2607. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2608. return this.rotateZ( angle );
  2609. }
  2610. var x = axis.x, y = axis.y, z = axis.z;
  2611. var n = Math.sqrt(x * x + y * y + z * z);
  2612. x /= n;
  2613. y /= n;
  2614. z /= n;
  2615. var xx = x * x, yy = y * y, zz = z * z;
  2616. var c = Math.cos( angle );
  2617. var s = Math.sin( angle );
  2618. var oneMinusCosine = 1 - c;
  2619. var xy = x * y * oneMinusCosine;
  2620. var xz = x * z * oneMinusCosine;
  2621. var yz = y * z * oneMinusCosine;
  2622. var xs = x * s;
  2623. var ys = y * s;
  2624. var zs = z * s;
  2625. var r11 = xx + (1 - xx) * c;
  2626. var r21 = xy + zs;
  2627. var r31 = xz - ys;
  2628. var r12 = xy - zs;
  2629. var r22 = yy + (1 - yy) * c;
  2630. var r32 = yz + xs;
  2631. var r13 = xz + ys;
  2632. var r23 = yz - xs;
  2633. var r33 = zz + (1 - zz) * c;
  2634. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2635. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2636. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2637. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  2638. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2639. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2640. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2641. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2642. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2643. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2644. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2645. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2646. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2647. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2648. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2649. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2650. return this;
  2651. },
  2652. scale: function ( v ) {
  2653. var te = this.elements;
  2654. var x = v.x, y = v.y, z = v.z;
  2655. te[0] *= x; te[4] *= y; te[8] *= z;
  2656. te[1] *= x; te[5] *= y; te[9] *= z;
  2657. te[2] *= x; te[6] *= y; te[10] *= z;
  2658. te[3] *= x; te[7] *= y; te[11] *= z;
  2659. return this;
  2660. },
  2661. getMaxScaleOnAxis: function () {
  2662. var te = this.elements;
  2663. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2664. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2665. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2666. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2667. },
  2668. makeTranslation: function ( x, y, z ) {
  2669. this.set(
  2670. 1, 0, 0, x,
  2671. 0, 1, 0, y,
  2672. 0, 0, 1, z,
  2673. 0, 0, 0, 1
  2674. );
  2675. return this;
  2676. },
  2677. makeRotationX: function ( theta ) {
  2678. var c = Math.cos( theta ), s = Math.sin( theta );
  2679. this.set(
  2680. 1, 0, 0, 0,
  2681. 0, c, -s, 0,
  2682. 0, s, c, 0,
  2683. 0, 0, 0, 1
  2684. );
  2685. return this;
  2686. },
  2687. makeRotationY: function ( theta ) {
  2688. var c = Math.cos( theta ), s = Math.sin( theta );
  2689. this.set(
  2690. c, 0, s, 0,
  2691. 0, 1, 0, 0,
  2692. -s, 0, c, 0,
  2693. 0, 0, 0, 1
  2694. );
  2695. return this;
  2696. },
  2697. makeRotationZ: function ( theta ) {
  2698. var c = Math.cos( theta ), s = Math.sin( theta );
  2699. this.set(
  2700. c, -s, 0, 0,
  2701. s, c, 0, 0,
  2702. 0, 0, 1, 0,
  2703. 0, 0, 0, 1
  2704. );
  2705. return this;
  2706. },
  2707. makeRotationAxis: function ( axis, angle ) {
  2708. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2709. var c = Math.cos( angle );
  2710. var s = Math.sin( angle );
  2711. var t = 1 - c;
  2712. var x = axis.x, y = axis.y, z = axis.z;
  2713. var tx = t * x, ty = t * y;
  2714. this.set(
  2715. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2716. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2717. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2718. 0, 0, 0, 1
  2719. );
  2720. return this;
  2721. },
  2722. makeScale: function ( x, y, z ) {
  2723. this.set(
  2724. x, 0, 0, 0,
  2725. 0, y, 0, 0,
  2726. 0, 0, z, 0,
  2727. 0, 0, 0, 1
  2728. );
  2729. return this;
  2730. },
  2731. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2732. var te = this.elements;
  2733. var x = 2 * near / ( right - left );
  2734. var y = 2 * near / ( top - bottom );
  2735. var a = ( right + left ) / ( right - left );
  2736. var b = ( top + bottom ) / ( top - bottom );
  2737. var c = - ( far + near ) / ( far - near );
  2738. var d = - 2 * far * near / ( far - near );
  2739. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2740. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2741. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2742. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2743. return this;
  2744. },
  2745. makePerspective: function ( fov, aspect, near, far ) {
  2746. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2747. var ymin = - ymax;
  2748. var xmin = ymin * aspect;
  2749. var xmax = ymax * aspect;
  2750. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2751. },
  2752. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2753. var te = this.elements;
  2754. var w = right - left;
  2755. var h = top - bottom;
  2756. var p = far - near;
  2757. var x = ( right + left ) / w;
  2758. var y = ( top + bottom ) / h;
  2759. var z = ( far + near ) / p;
  2760. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2761. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2762. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2763. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2764. return this;
  2765. },
  2766. clone: function () {
  2767. var te = this.elements;
  2768. return new THREE.Matrix4(
  2769. te[0], te[4], te[8], te[12],
  2770. te[1], te[5], te[9], te[13],
  2771. te[2], te[6], te[10], te[14],
  2772. te[3], te[7], te[11], te[15]
  2773. );
  2774. }
  2775. } );
  2776. /**
  2777. * @author bhouston / http://exocortex.com
  2778. */
  2779. THREE.Ray = function ( origin, direction ) {
  2780. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2781. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2782. };
  2783. THREE.extend( THREE.Ray.prototype, {
  2784. set: function ( origin, direction ) {
  2785. this.origin.copy( origin );
  2786. this.direction.copy( direction );
  2787. return this;
  2788. },
  2789. copy: function ( ray ) {
  2790. this.origin.copy( ray.origin );
  2791. this.direction.copy( ray.direction );
  2792. return this;
  2793. },
  2794. at: function( t, optionalTarget ) {
  2795. var result = optionalTarget || new THREE.Vector3();
  2796. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2797. },
  2798. recast: function() {
  2799. var v1 = new THREE.Vector3();
  2800. return function ( t ) {
  2801. this.origin.copy( this.at( t, v1 ) );
  2802. return this;
  2803. };
  2804. }(),
  2805. closestPointToPoint: function ( point, optionalTarget ) {
  2806. var result = optionalTarget || new THREE.Vector3();
  2807. result.subVectors( point, this.origin );
  2808. var directionDistance = result.dot( this.direction );
  2809. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2810. },
  2811. distanceToPoint: function() {
  2812. var v1 = new THREE.Vector3();
  2813. return function ( point ) {
  2814. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  2815. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2816. return v1.distanceTo( point );
  2817. };
  2818. }(),
  2819. isIntersectionSphere: function( sphere ) {
  2820. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2821. },
  2822. isIntersectionPlane: function ( plane ) {
  2823. // check if the line and plane are non-perpendicular, if they
  2824. // eventually they will intersect.
  2825. var denominator = plane.normal.dot( this.direction );
  2826. if ( denominator != 0 ) {
  2827. return true;
  2828. }
  2829. // line is coplanar, return origin
  2830. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2831. return true;
  2832. }
  2833. return false;
  2834. },
  2835. distanceToPlane: function ( plane ) {
  2836. var denominator = plane.normal.dot( this.direction );
  2837. if ( denominator == 0 ) {
  2838. // line is coplanar, return origin
  2839. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2840. return 0;
  2841. }
  2842. // Unsure if this is the correct method to handle this case.
  2843. return undefined;
  2844. }
  2845. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2846. return t;
  2847. },
  2848. intersectPlane: function ( plane, optionalTarget ) {
  2849. var t = this.distanceToPlane( plane );
  2850. if ( t === undefined ) {
  2851. return undefined;
  2852. }
  2853. return this.at( t, optionalTarget );
  2854. },
  2855. transform: function ( matrix4 ) {
  2856. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2857. this.origin.applyMatrix4( matrix4 );
  2858. this.direction.sub( this.origin );
  2859. return this;
  2860. },
  2861. equals: function ( ray ) {
  2862. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2863. },
  2864. clone: function () {
  2865. return new THREE.Ray().copy( this );
  2866. }
  2867. } );
  2868. /**
  2869. * @author bhouston / http://exocortex.com
  2870. * @author mrdoob / http://mrdoob.com/
  2871. */
  2872. THREE.Sphere = function ( center, radius ) {
  2873. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  2874. this.radius = ( radius !== undefined ) ? radius : 0;
  2875. };
  2876. THREE.extend( THREE.Sphere.prototype, {
  2877. set: function ( center, radius ) {
  2878. this.center.copy( center );
  2879. this.radius = radius;
  2880. return this;
  2881. },
  2882. setFromCenterAndPoints: function ( center, points ) {
  2883. var maxRadiusSq = 0;
  2884. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2885. var radiusSq = center.distanceToSquared( points[ i ] );
  2886. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2887. }
  2888. this.center = center;
  2889. this.radius = Math.sqrt( maxRadiusSq );
  2890. return this;
  2891. },
  2892. copy: function ( sphere ) {
  2893. this.center.copy( sphere.center );
  2894. this.radius = sphere.radius;
  2895. return this;
  2896. },
  2897. empty: function () {
  2898. return ( this.radius <= 0 );
  2899. },
  2900. containsPoint: function ( point ) {
  2901. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2902. },
  2903. distanceToPoint: function ( point ) {
  2904. return ( point.distanceTo( this.center ) - this.radius );
  2905. },
  2906. intersectsSphere: function ( sphere ) {
  2907. var radiusSum = this.radius + sphere.radius;
  2908. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2909. },
  2910. clampPoint: function ( point, optionalTarget ) {
  2911. var deltaLengthSq = this.center.distanceToSquared( point );
  2912. var result = optionalTarget || new THREE.Vector3();
  2913. result.copy( point );
  2914. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2915. result.sub( this.center ).normalize();
  2916. result.multiplyScalar( this.radius ).add( this.center );
  2917. }
  2918. return result;
  2919. },
  2920. getBoundingBox: function ( optionalTarget ) {
  2921. var box = optionalTarget || new THREE.Box3();
  2922. box.set( this.center, this.center );
  2923. box.expandByScalar( this.radius );
  2924. return box;
  2925. },
  2926. transform: function ( matrix ) {
  2927. this.center.applyMatrix4( matrix );
  2928. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2929. return this;
  2930. },
  2931. translate: function ( offset ) {
  2932. this.center.add( offset );
  2933. return this;
  2934. },
  2935. equals: function ( sphere ) {
  2936. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2937. },
  2938. clone: function () {
  2939. return new THREE.Sphere().copy( this );
  2940. }
  2941. } );
  2942. /**
  2943. * @author mrdoob / http://mrdoob.com/
  2944. * @author alteredq / http://alteredqualia.com/
  2945. * @author bhouston / http://exocortex.com
  2946. */
  2947. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2948. this.planes = [
  2949. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2950. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2951. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2952. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2953. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2954. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2955. ];
  2956. };
  2957. THREE.extend( THREE.Frustum.prototype, {
  2958. set: function ( p0, p1, p2, p3, p4, p5 ) {
  2959. var planes = this.planes;
  2960. planes[0].copy( p0 );
  2961. planes[1].copy( p1 );
  2962. planes[2].copy( p2 );
  2963. planes[3].copy( p3 );
  2964. planes[4].copy( p4 );
  2965. planes[5].copy( p5 );
  2966. return this;
  2967. },
  2968. copy: function ( frustum ) {
  2969. var planes = this.planes;
  2970. for( var i = 0; i < 6; i ++ ) {
  2971. planes[i].copy( frustum.planes[i] );
  2972. }
  2973. return this;
  2974. },
  2975. setFromMatrix: function ( m ) {
  2976. var planes = this.planes;
  2977. var me = m.elements;
  2978. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2979. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2980. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2981. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2982. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  2983. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  2984. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  2985. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  2986. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  2987. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  2988. return this;
  2989. },
  2990. intersectsObject: function ( object ) {
  2991. // this method is expanded inlined for performance reasons.
  2992. var matrix = object.matrixWorld;
  2993. var planes = this.planes;
  2994. var center = matrix.getPosition();
  2995. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  2996. for ( var i = 0; i < 6; i ++ ) {
  2997. var distance = planes[ i ].distanceToPoint( center );
  2998. if( distance < negRadius ) {
  2999. return false;
  3000. }
  3001. }
  3002. return true;
  3003. },
  3004. intersectsSphere: function ( sphere ) {
  3005. var planes = this.planes;
  3006. var center = sphere.center;
  3007. var negRadius = -sphere.radius;
  3008. for ( var i = 0; i < 6; i ++ ) {
  3009. var distance = planes[ i ].distanceToPoint( center );
  3010. if( distance < negRadius ) {
  3011. return false;
  3012. }
  3013. }
  3014. return true;
  3015. },
  3016. containsPoint: function ( point ) {
  3017. var planes = this.planes;
  3018. for ( var i = 0; i < 6; i ++ ) {
  3019. if( planes[ i ].distanceToPoint( point ) < 0 ) {
  3020. return false;
  3021. }
  3022. }
  3023. return true;
  3024. },
  3025. clone: function () {
  3026. return new THREE.Frustum().copy( this );
  3027. }
  3028. } );/**
  3029. * @author bhouston / http://exocortex.com
  3030. */
  3031. THREE.Plane = function ( normal, constant ) {
  3032. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3033. this.constant = ( constant !== undefined ) ? constant : 0;
  3034. };
  3035. THREE.extend( THREE.Plane.prototype, {
  3036. set: function ( normal, constant ) {
  3037. this.normal.copy( normal );
  3038. this.constant = constant;
  3039. return this;
  3040. },
  3041. setComponents: function ( x, y, z, w ) {
  3042. this.normal.set( x, y, z );
  3043. this.constant = w;
  3044. return this;
  3045. },
  3046. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3047. this.normal.copy( normal );
  3048. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3049. return this;
  3050. },
  3051. setFromCoplanarPoints: function() {
  3052. var v1 = new THREE.Vector3();
  3053. var v2 = new THREE.Vector3();
  3054. return function ( a, b, c ) {
  3055. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3056. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3057. this.setFromNormalAndCoplanarPoint( normal, a );
  3058. return this;
  3059. };
  3060. }(),
  3061. copy: function ( plane ) {
  3062. this.normal.copy( plane.normal );
  3063. this.constant = plane.constant;
  3064. return this;
  3065. },
  3066. normalize: function () {
  3067. // Note: will lead to a divide by zero if the plane is invalid.
  3068. var inverseNormalLength = 1.0 / this.normal.length();
  3069. this.normal.multiplyScalar( inverseNormalLength );
  3070. this.constant *= inverseNormalLength;
  3071. return this;
  3072. },
  3073. negate: function () {
  3074. this.constant *= -1;
  3075. this.normal.negate();
  3076. return this;
  3077. },
  3078. distanceToPoint: function ( point ) {
  3079. return this.normal.dot( point ) + this.constant;
  3080. },
  3081. distanceToSphere: function ( sphere ) {
  3082. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3083. },
  3084. projectPoint: function ( point, optionalTarget ) {
  3085. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3086. },
  3087. orthoPoint: function ( point, optionalTarget ) {
  3088. var perpendicularMagnitude = this.distanceToPoint( point );
  3089. var result = optionalTarget || new THREE.Vector3();
  3090. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3091. },
  3092. isIntersectionLine: function ( startPoint, endPoint ) {
  3093. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3094. var startSign = this.distanceToPoint( startPoint );
  3095. var endSign = this.distanceToPoint( endPoint );
  3096. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3097. },
  3098. intersectLine: function() {
  3099. var v1 = new THREE.Vector3();
  3100. return function ( startPoint, endPoint, optionalTarget ) {
  3101. var result = optionalTarget || new THREE.Vector3();
  3102. var direction = v1.subVectors( endPoint, startPoint );
  3103. var denominator = this.normal.dot( direction );
  3104. if ( denominator == 0 ) {
  3105. // line is coplanar, return origin
  3106. if( this.distanceToPoint( startPoint ) == 0 ) {
  3107. return result.copy( startPoint );
  3108. }
  3109. // Unsure if this is the correct method to handle this case.
  3110. return undefined;
  3111. }
  3112. var t = - ( startPoint.dot( this.normal ) + this.constant ) / denominator;
  3113. if( t < 0 || t > 1 ) {
  3114. return undefined;
  3115. }
  3116. return result.copy( direction ).multiplyScalar( t ).add( startPoint );
  3117. };
  3118. }(),
  3119. coplanarPoint: function ( optionalTarget ) {
  3120. var result = optionalTarget || new THREE.Vector3();
  3121. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3122. },
  3123. transform: function() {
  3124. var v1 = new THREE.Vector3();
  3125. var v2 = new THREE.Vector3();
  3126. return function ( matrix, optionalNormalMatrix ) {
  3127. // compute new normal based on theory here:
  3128. // http://www.songho.ca/opengl/gl_normaltransform.html
  3129. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  3130. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3131. var newCoplanarPoint = this.coplanarPoint( v2 );
  3132. newCoplanarPoint.applyMatrix4( matrix );
  3133. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3134. return this;
  3135. };
  3136. }(),
  3137. translate: function ( offset ) {
  3138. this.constant = this.constant - offset.dot( this.normal );
  3139. return this;
  3140. },
  3141. equals: function ( plane ) {
  3142. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3143. },
  3144. clone: function () {
  3145. return new THREE.Plane().copy( this );
  3146. }
  3147. } );
  3148. /**
  3149. * @author alteredq / http://alteredqualia.com/
  3150. */
  3151. THREE.Math = {
  3152. // Clamp value to range <a, b>
  3153. clamp: function ( x, a, b ) {
  3154. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3155. },
  3156. // Clamp value to range <a, inf)
  3157. clampBottom: function ( x, a ) {
  3158. return x < a ? a : x;
  3159. },
  3160. // Linear mapping from range <a1, a2> to range <b1, b2>
  3161. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3162. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3163. },
  3164. // Random float from <0, 1> with 16 bits of randomness
  3165. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3166. random16: function () {
  3167. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3168. },
  3169. // Random integer from <low, high> interval
  3170. randInt: function ( low, high ) {
  3171. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3172. },
  3173. // Random float from <low, high> interval
  3174. randFloat: function ( low, high ) {
  3175. return low + Math.random() * ( high - low );
  3176. },
  3177. // Random float from <-range/2, range/2> interval
  3178. randFloatSpread: function ( range ) {
  3179. return range * ( 0.5 - Math.random() );
  3180. },
  3181. sign: function ( x ) {
  3182. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3183. },
  3184. degToRad: function() {
  3185. var degreeToRadiansFactor = Math.PI / 180;
  3186. return function ( degrees ) {
  3187. return degrees * degreeToRadiansFactor;
  3188. };
  3189. }(),
  3190. radToDeg: function() {
  3191. var radianToDegreesFactor = 180 / Math.PI;
  3192. return function ( radians ) {
  3193. return radians * radianToDegreesFactor;
  3194. };
  3195. }()
  3196. };
  3197. /**
  3198. * Spline from Tween.js, slightly optimized (and trashed)
  3199. * http://sole.github.com/tween.js/examples/05_spline.html
  3200. *
  3201. * @author mrdoob / http://mrdoob.com/
  3202. * @author alteredq / http://alteredqualia.com/
  3203. */
  3204. THREE.Spline = function ( points ) {
  3205. this.points = points;
  3206. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3207. point, intPoint, weight, w2, w3,
  3208. pa, pb, pc, pd;
  3209. this.initFromArray = function( a ) {
  3210. this.points = [];
  3211. for ( var i = 0; i < a.length; i++ ) {
  3212. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3213. }
  3214. };
  3215. this.getPoint = function ( k ) {
  3216. point = ( this.points.length - 1 ) * k;
  3217. intPoint = Math.floor( point );
  3218. weight = point - intPoint;
  3219. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3220. c[ 1 ] = intPoint;
  3221. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3222. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3223. pa = this.points[ c[ 0 ] ];
  3224. pb = this.points[ c[ 1 ] ];
  3225. pc = this.points[ c[ 2 ] ];
  3226. pd = this.points[ c[ 3 ] ];
  3227. w2 = weight * weight;
  3228. w3 = weight * w2;
  3229. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3230. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3231. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3232. return v3;
  3233. };
  3234. this.getControlPointsArray = function () {
  3235. var i, p, l = this.points.length,
  3236. coords = [];
  3237. for ( i = 0; i < l; i ++ ) {
  3238. p = this.points[ i ];
  3239. coords[ i ] = [ p.x, p.y, p.z ];
  3240. }
  3241. return coords;
  3242. };
  3243. // approximate length by summing linear segments
  3244. this.getLength = function ( nSubDivisions ) {
  3245. var i, index, nSamples, position,
  3246. point = 0, intPoint = 0, oldIntPoint = 0,
  3247. oldPosition = new THREE.Vector3(),
  3248. tmpVec = new THREE.Vector3(),
  3249. chunkLengths = [],
  3250. totalLength = 0;
  3251. // first point has 0 length
  3252. chunkLengths[ 0 ] = 0;
  3253. if ( !nSubDivisions ) nSubDivisions = 100;
  3254. nSamples = this.points.length * nSubDivisions;
  3255. oldPosition.copy( this.points[ 0 ] );
  3256. for ( i = 1; i < nSamples; i ++ ) {
  3257. index = i / nSamples;
  3258. position = this.getPoint( index );
  3259. tmpVec.copy( position );
  3260. totalLength += tmpVec.distanceTo( oldPosition );
  3261. oldPosition.copy( position );
  3262. point = ( this.points.length - 1 ) * index;
  3263. intPoint = Math.floor( point );
  3264. if ( intPoint != oldIntPoint ) {
  3265. chunkLengths[ intPoint ] = totalLength;
  3266. oldIntPoint = intPoint;
  3267. }
  3268. }
  3269. // last point ends with total length
  3270. chunkLengths[ chunkLengths.length ] = totalLength;
  3271. return { chunks: chunkLengths, total: totalLength };
  3272. };
  3273. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3274. var i, j,
  3275. index, indexCurrent, indexNext,
  3276. linearDistance, realDistance,
  3277. sampling, position,
  3278. newpoints = [],
  3279. tmpVec = new THREE.Vector3(),
  3280. sl = this.getLength();
  3281. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3282. for ( i = 1; i < this.points.length; i++ ) {
  3283. //tmpVec.copy( this.points[ i - 1 ] );
  3284. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3285. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3286. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3287. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3288. indexNext = i / ( this.points.length - 1 );
  3289. for ( j = 1; j < sampling - 1; j++ ) {
  3290. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3291. position = this.getPoint( index );
  3292. newpoints.push( tmpVec.copy( position ).clone() );
  3293. }
  3294. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3295. }
  3296. this.points = newpoints;
  3297. };
  3298. // Catmull-Rom
  3299. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3300. var v0 = ( p2 - p0 ) * 0.5,
  3301. v1 = ( p3 - p1 ) * 0.5;
  3302. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3303. };
  3304. };
  3305. /**
  3306. * @author bhouston / http://exocortex.com
  3307. * @author mrdoob / http://mrdoob.com/
  3308. */
  3309. THREE.Triangle = function ( a, b, c ) {
  3310. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3311. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3312. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3313. };
  3314. THREE.Triangle.normal = function() {
  3315. var v0 = new THREE.Vector3();
  3316. return function( a, b, c, optionalTarget ) {
  3317. var result = optionalTarget || new THREE.Vector3();
  3318. result.subVectors( c, b );
  3319. v0.subVectors( a, b );
  3320. result.cross( v0 );
  3321. var resultLengthSq = result.lengthSq();
  3322. if( resultLengthSq > 0 ) {
  3323. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3324. }
  3325. return result.set( 0, 0, 0 );
  3326. };
  3327. }();
  3328. // static/instance method to calculate barycoordinates
  3329. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3330. THREE.Triangle.barycoordFromPoint = function() {
  3331. var v0 = new THREE.Vector3(),
  3332. v1 = new THREE.Vector3(),
  3333. v2 = new THREE.Vector3();
  3334. return function ( point, a, b, c, optionalTarget ) {
  3335. v0.subVectors( c, a );
  3336. v1.subVectors( b, a );
  3337. v2.subVectors( point, a );
  3338. var dot00 = v0.dot( v0 );
  3339. var dot01 = v0.dot( v1 );
  3340. var dot02 = v0.dot( v2 );
  3341. var dot11 = v1.dot( v1 );
  3342. var dot12 = v1.dot( v2 );
  3343. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3344. var result = optionalTarget || new THREE.Vector3();
  3345. // colinear or singular triangle
  3346. if( denom == 0 ) {
  3347. // arbitrary location outside of triangle?
  3348. // not sure if this is the best idea, maybe should be returning undefined
  3349. return result.set( -2, -1, -1 );
  3350. }
  3351. var invDenom = 1 / denom;
  3352. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3353. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3354. // barycoordinates must always sum to 1
  3355. return result.set( 1 - u - v, v, u );
  3356. };
  3357. }();
  3358. THREE.Triangle.containsPoint = function() {
  3359. var v1 = new THREE.Vector3();
  3360. return function ( point, a, b, c ) {
  3361. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3362. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3363. };
  3364. }();
  3365. THREE.extend( THREE.Triangle.prototype, {
  3366. constructor: THREE.Triangle,
  3367. set: function ( a, b, c ) {
  3368. this.a.copy( a );
  3369. this.b.copy( b );
  3370. this.c.copy( c );
  3371. return this;
  3372. },
  3373. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3374. this.a.copy( points[i0] );
  3375. this.b.copy( points[i1] );
  3376. this.c.copy( points[i2] );
  3377. return this;
  3378. },
  3379. copy: function ( triangle ) {
  3380. this.a.copy( triangle.a );
  3381. this.b.copy( triangle.b );
  3382. this.c.copy( triangle.c );
  3383. return this;
  3384. },
  3385. area: function() {
  3386. var v0 = new THREE.Vector3();
  3387. var v1 = new THREE.Vector3();
  3388. return function () {
  3389. v0.subVectors( this.c, this.b );
  3390. v1.subVectors( this.a, this.b );
  3391. return v0.cross( v1 ).length() * 0.5;
  3392. };
  3393. }(),
  3394. midpoint: function ( optionalTarget ) {
  3395. var result = optionalTarget || new THREE.Vector3();
  3396. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3397. },
  3398. normal: function ( optionalTarget ) {
  3399. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3400. },
  3401. plane: function ( optionalTarget ) {
  3402. var result = optionalTarget || new THREE.Plane();
  3403. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3404. },
  3405. barycoordFromPoint: function ( point, optionalTarget ) {
  3406. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3407. },
  3408. containsPoint: function ( point ) {
  3409. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3410. },
  3411. equals: function ( triangle ) {
  3412. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3413. },
  3414. clone: function () {
  3415. return new THREE.Triangle().copy( this );
  3416. }
  3417. } );
  3418. /**
  3419. * @author mrdoob / http://mrdoob.com/
  3420. */
  3421. THREE.Vertex = function ( v ) {
  3422. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3423. return v;
  3424. };
  3425. /**
  3426. * @author mrdoob / http://mrdoob.com/
  3427. */
  3428. THREE.UV = function ( u, v ) {
  3429. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3430. return new THREE.Vector2( u, v );
  3431. };
  3432. /**
  3433. * @author alteredq / http://alteredqualia.com/
  3434. */
  3435. THREE.Clock = function ( autoStart ) {
  3436. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3437. this.startTime = 0;
  3438. this.oldTime = 0;
  3439. this.elapsedTime = 0;
  3440. this.running = false;
  3441. };
  3442. THREE.Clock.prototype.start = function () {
  3443. this.startTime = Date.now();
  3444. this.oldTime = this.startTime;
  3445. this.running = true;
  3446. };
  3447. THREE.Clock.prototype.stop = function () {
  3448. this.getElapsedTime();
  3449. this.running = false;
  3450. };
  3451. THREE.Clock.prototype.getElapsedTime = function () {
  3452. this.getDelta();
  3453. return this.elapsedTime;
  3454. };
  3455. THREE.Clock.prototype.getDelta = function () {
  3456. var diff = 0;
  3457. if ( this.autoStart && ! this.running ) {
  3458. this.start();
  3459. }
  3460. if ( this.running ) {
  3461. var newTime = Date.now();
  3462. diff = 0.001 * ( newTime - this.oldTime );
  3463. this.oldTime = newTime;
  3464. this.elapsedTime += diff;
  3465. }
  3466. return diff;
  3467. };/**
  3468. * https://github.com/mrdoob/eventdispatcher.js/
  3469. */
  3470. THREE.EventDispatcher = function () {
  3471. var listeners = {};
  3472. this.addEventListener = function ( type, listener ) {
  3473. if ( listeners[ type ] === undefined ) {
  3474. listeners[ type ] = [];
  3475. }
  3476. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3477. listeners[ type ].push( listener );
  3478. }
  3479. };
  3480. this.removeEventListener = function ( type, listener ) {
  3481. var index = listeners[ type ].indexOf( listener );
  3482. if ( index !== - 1 ) {
  3483. listeners[ type ].splice( index, 1 );
  3484. }
  3485. };
  3486. this.dispatchEvent = function ( event ) {
  3487. var listenerArray = listeners[ event.type ];
  3488. if ( listenerArray !== undefined ) {
  3489. event.target = this;
  3490. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3491. listenerArray[ i ].call( this, event );
  3492. }
  3493. }
  3494. };
  3495. };
  3496. /**
  3497. * @author mrdoob / http://mrdoob.com/
  3498. * @author bhouston / http://exocortex.com/
  3499. */
  3500. ( function ( THREE ) {
  3501. THREE.Raycaster = function ( origin, direction, near, far ) {
  3502. this.ray = new THREE.Ray( origin, direction );
  3503. // normalized ray.direction required for accurate distance calculations
  3504. if( this.ray.direction.length() > 0 ) {
  3505. this.ray.direction.normalize();
  3506. }
  3507. this.near = near || 0;
  3508. this.far = far || Infinity;
  3509. };
  3510. var sphere = new THREE.Sphere();
  3511. var localRay = new THREE.Ray();
  3512. var facePlane = new THREE.Plane();
  3513. var intersectPoint = new THREE.Vector3();
  3514. var inverseMatrix = new THREE.Matrix4();
  3515. var descSort = function ( a, b ) {
  3516. return a.distance - b.distance;
  3517. };
  3518. var intersectObject = function ( object, raycaster, intersects ) {
  3519. if ( object instanceof THREE.Particle ) {
  3520. var distance = raycaster.ray.distanceToPoint( object.matrixWorld.getPosition() );
  3521. if ( distance > object.scale.x ) {
  3522. return intersects;
  3523. }
  3524. intersects.push( {
  3525. distance: distance,
  3526. point: object.position,
  3527. face: null,
  3528. object: object
  3529. } );
  3530. } else if ( object instanceof THREE.Mesh ) {
  3531. // Checking boundingSphere distance to ray
  3532. sphere.set(
  3533. object.matrixWorld.getPosition(),
  3534. object.geometry.boundingSphere.radius* object.matrixWorld.getMaxScaleOnAxis() );
  3535. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3536. return intersects;
  3537. }
  3538. // Checking faces
  3539. var geometry = object.geometry;
  3540. var vertices = geometry.vertices;
  3541. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3542. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3543. var side = object.material.side;
  3544. var a, b, c, d;
  3545. var precision = raycaster.precision;
  3546. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3547. inverseMatrix.getInverse( object.matrixWorld );
  3548. localRay.copy( raycaster.ray ).transform( inverseMatrix );
  3549. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3550. var face = geometry.faces[ f ];
  3551. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3552. if ( material === undefined ) continue;
  3553. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3554. var planeDistance = localRay.distanceToPlane( facePlane );
  3555. // bail if raycaster and plane are parallel
  3556. if ( Math.abs( planeDistance ) < precision ) continue;
  3557. // if negative distance, then plane is behind raycaster
  3558. if ( planeDistance < 0 ) continue;
  3559. // check if we hit the wrong side of a single sided face
  3560. side = material.side;
  3561. if( side !== THREE.DoubleSide ) {
  3562. var planeSign = localRay.direction.dot( facePlane.normal );
  3563. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3564. }
  3565. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3566. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3567. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3568. if ( face instanceof THREE.Face3 ) {
  3569. a = vertices[ face.a ];
  3570. b = vertices[ face.b ];
  3571. c = vertices[ face.c ];
  3572. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3573. } else if ( face instanceof THREE.Face4 ) {
  3574. a = vertices[ face.a ];
  3575. b = vertices[ face.b ];
  3576. c = vertices[ face.c ];
  3577. d = vertices[ face.d ];
  3578. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3579. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3580. } else {
  3581. // This is added because if we call out of this if/else group when none of the cases
  3582. // match it will add a point to the intersection list erroneously.
  3583. throw Error( "face type not supported" );
  3584. }
  3585. intersects.push( {
  3586. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3587. point: raycaster.ray.at( planeDistance ),
  3588. face: face,
  3589. faceIndex: f,
  3590. object: object
  3591. } );
  3592. }
  3593. }
  3594. };
  3595. var intersectDescendants = function ( object, raycaster, intersects ) {
  3596. var descendants = object.getDescendants();
  3597. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3598. intersectObject( descendants[ i ], raycaster, intersects );
  3599. }
  3600. };
  3601. //
  3602. THREE.Raycaster.prototype.precision = 0.0001;
  3603. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3604. this.ray.set( origin, direction );
  3605. // normalized ray.direction required for accurate distance calculations
  3606. if( this.ray.direction.length() > 0 ) {
  3607. this.ray.direction.normalize();
  3608. }
  3609. };
  3610. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3611. var intersects = [];
  3612. if ( recursive === true ) {
  3613. intersectDescendants( object, this, intersects );
  3614. }
  3615. intersectObject( object, this, intersects );
  3616. intersects.sort( descSort );
  3617. return intersects;
  3618. };
  3619. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3620. var intersects = [];
  3621. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3622. intersectObject( objects[ i ], this, intersects );
  3623. if ( recursive === true ) {
  3624. intersectDescendants( objects[ i ], this, intersects );
  3625. }
  3626. }
  3627. intersects.sort( descSort );
  3628. return intersects;
  3629. };
  3630. }( THREE ) );
  3631. /**
  3632. * @author mrdoob / http://mrdoob.com/
  3633. * @author mikael emtinger / http://gomo.se/
  3634. * @author alteredq / http://alteredqualia.com/
  3635. */
  3636. THREE.Object3D = function () {
  3637. this.id = THREE.Object3DIdCount ++;
  3638. this.name = '';
  3639. this.properties = {};
  3640. this.parent = undefined;
  3641. this.children = [];
  3642. this.up = new THREE.Vector3( 0, 1, 0 );
  3643. this.position = new THREE.Vector3();
  3644. this.rotation = new THREE.Vector3();
  3645. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3646. this.scale = new THREE.Vector3( 1, 1, 1 );
  3647. this.renderDepth = null;
  3648. this.rotationAutoUpdate = true;
  3649. this.matrix = new THREE.Matrix4();
  3650. this.matrixWorld = new THREE.Matrix4();
  3651. this.matrixRotationWorld = new THREE.Matrix4();
  3652. this.matrixAutoUpdate = true;
  3653. this.matrixWorldNeedsUpdate = true;
  3654. this.quaternion = new THREE.Quaternion();
  3655. this.useQuaternion = false;
  3656. this.visible = true;
  3657. this.castShadow = false;
  3658. this.receiveShadow = false;
  3659. this.frustumCulled = true;
  3660. this._vector = new THREE.Vector3();
  3661. };
  3662. THREE.Object3D.prototype = {
  3663. constructor: THREE.Object3D,
  3664. applyMatrix: function ( matrix ) {
  3665. this.matrix.multiplyMatrices( matrix, this.matrix );
  3666. this.scale.getScaleFromMatrix( this.matrix );
  3667. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  3668. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  3669. this.position.getPositionFromMatrix( this.matrix );
  3670. },
  3671. translate: function ( distance, axis ) {
  3672. this.matrix.rotateAxis( axis );
  3673. this.position.add( axis.multiplyScalar( distance ) );
  3674. },
  3675. translateX: function ( distance ) {
  3676. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  3677. },
  3678. translateY: function ( distance ) {
  3679. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  3680. },
  3681. translateZ: function ( distance ) {
  3682. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  3683. },
  3684. localToWorld: function ( vector ) {
  3685. return vector.applyMatrix4( this.matrixWorld );
  3686. },
  3687. worldToLocal: function ( vector ) {
  3688. return vector.applyMatrix4( THREE.Object3D.__m1.getInverse( this.matrixWorld ) );
  3689. },
  3690. lookAt: function ( vector ) {
  3691. // TODO: Add hierarchy support.
  3692. this.matrix.lookAt( vector, this.position, this.up );
  3693. if ( this.rotationAutoUpdate ) {
  3694. if ( this.useQuaternion === false ) {
  3695. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3696. } else {
  3697. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3698. }
  3699. }
  3700. },
  3701. add: function ( object ) {
  3702. if ( object === this ) {
  3703. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3704. return;
  3705. }
  3706. if ( object instanceof THREE.Object3D ) {
  3707. if ( object.parent !== undefined ) {
  3708. object.parent.remove( object );
  3709. }
  3710. object.parent = this;
  3711. this.children.push( object );
  3712. // add to scene
  3713. var scene = this;
  3714. while ( scene.parent !== undefined ) {
  3715. scene = scene.parent;
  3716. }
  3717. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3718. scene.__addObject( object );
  3719. }
  3720. }
  3721. },
  3722. remove: function ( object ) {
  3723. var index = this.children.indexOf( object );
  3724. if ( index !== - 1 ) {
  3725. object.parent = undefined;
  3726. this.children.splice( index, 1 );
  3727. // remove from scene
  3728. var scene = this;
  3729. while ( scene.parent !== undefined ) {
  3730. scene = scene.parent;
  3731. }
  3732. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3733. scene.__removeObject( object );
  3734. }
  3735. }
  3736. },
  3737. traverse: function ( callback ) {
  3738. callback( this );
  3739. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3740. this.children[ i ].traverse( callback );
  3741. }
  3742. },
  3743. getChildByName: function ( name, recursive ) {
  3744. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3745. var child = this.children[ i ];
  3746. if ( child.name === name ) {
  3747. return child;
  3748. }
  3749. if ( recursive === true ) {
  3750. child = child.getChildByName( name, recursive );
  3751. if ( child !== undefined ) {
  3752. return child;
  3753. }
  3754. }
  3755. }
  3756. return undefined;
  3757. },
  3758. getDescendants: function ( array ) {
  3759. if ( array === undefined ) array = [];
  3760. Array.prototype.push.apply( array, this.children );
  3761. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3762. this.children[ i ].getDescendants( array );
  3763. }
  3764. return array;
  3765. },
  3766. updateMatrix: function () {
  3767. this.matrix.setPosition( this.position );
  3768. if ( this.useQuaternion === false ) {
  3769. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3770. } else {
  3771. this.matrix.setRotationFromQuaternion( this.quaternion );
  3772. }
  3773. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3774. this.matrix.scale( this.scale );
  3775. }
  3776. this.matrixWorldNeedsUpdate = true;
  3777. },
  3778. updateMatrixWorld: function ( force ) {
  3779. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3780. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3781. if ( this.parent === undefined ) {
  3782. this.matrixWorld.copy( this.matrix );
  3783. } else {
  3784. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3785. }
  3786. this.matrixWorldNeedsUpdate = false;
  3787. force = true;
  3788. }
  3789. // update children
  3790. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3791. this.children[ i ].updateMatrixWorld( force );
  3792. }
  3793. },
  3794. clone: function ( object ) {
  3795. if ( object === undefined ) object = new THREE.Object3D();
  3796. object.name = this.name;
  3797. object.up.copy( this.up );
  3798. object.position.copy( this.position );
  3799. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3800. object.eulerOrder = this.eulerOrder;
  3801. object.scale.copy( this.scale );
  3802. object.renderDepth = this.renderDepth;
  3803. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3804. object.matrix.copy( this.matrix );
  3805. object.matrixWorld.copy( this.matrixWorld );
  3806. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3807. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3808. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3809. object.quaternion.copy( this.quaternion );
  3810. object.useQuaternion = this.useQuaternion;
  3811. object.visible = this.visible;
  3812. object.castShadow = this.castShadow;
  3813. object.receiveShadow = this.receiveShadow;
  3814. object.frustumCulled = this.frustumCulled;
  3815. for ( var i = 0; i < this.children.length; i ++ ) {
  3816. var child = this.children[ i ];
  3817. object.add( child.clone() );
  3818. }
  3819. return object;
  3820. }
  3821. };
  3822. THREE.Object3D.__m1 = new THREE.Matrix4();
  3823. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3824. THREE.Object3DIdCount = 0;
  3825. /**
  3826. * @author mrdoob / http://mrdoob.com/
  3827. * @author supereggbert / http://www.paulbrunt.co.uk/
  3828. * @author julianwa / https://github.com/julianwa
  3829. */
  3830. THREE.Projector = function () {
  3831. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3832. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3833. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3834. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3835. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3836. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3837. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3838. _vector3 = new THREE.Vector3(),
  3839. _vector4 = new THREE.Vector4(),
  3840. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  3841. _boundingBox = new THREE.Box3(),
  3842. _points3 = new Array( 3 ),
  3843. _points4 = new Array( 4 ),
  3844. _viewMatrix = new THREE.Matrix4(),
  3845. _viewProjectionMatrix = new THREE.Matrix4(),
  3846. _modelMatrix,
  3847. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3848. _normalMatrix = new THREE.Matrix3(),
  3849. _normalViewMatrix = new THREE.Matrix3(),
  3850. _centroid = new THREE.Vector3(),
  3851. _frustum = new THREE.Frustum(),
  3852. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3853. _clippedVertex2PositionScreen = new THREE.Vector4(),
  3854. _face3VertexNormals;
  3855. this.projectVector = function ( vector, camera ) {
  3856. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3857. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3858. return vector.applyProjection( _viewProjectionMatrix );
  3859. };
  3860. this.unprojectVector = function ( vector, camera ) {
  3861. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3862. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3863. return vector.applyProjection( _viewProjectionMatrix );
  3864. };
  3865. this.pickingRay = function ( vector, camera ) {
  3866. // set two vectors with opposing z values
  3867. vector.z = -1.0;
  3868. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3869. this.unprojectVector( vector, camera );
  3870. this.unprojectVector( end, camera );
  3871. // find direction from vector to end
  3872. end.sub( vector ).normalize();
  3873. return new THREE.Raycaster( vector, end );
  3874. };
  3875. var projectGraph = function ( root, sortObjects ) {
  3876. _objectCount = 0;
  3877. _renderData.objects.length = 0;
  3878. _renderData.sprites.length = 0;
  3879. _renderData.lights.length = 0;
  3880. var projectObject = function ( parent ) {
  3881. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3882. var object = parent.children[ c ];
  3883. if ( object.visible === false ) continue;
  3884. if ( object instanceof THREE.Light ) {
  3885. _renderData.lights.push( object );
  3886. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3887. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  3888. _object = getNextObjectInPool();
  3889. _object.object = object;
  3890. if ( object.renderDepth !== null ) {
  3891. _object.z = object.renderDepth;
  3892. } else {
  3893. _vector3.copy( object.matrixWorld.getPosition() );
  3894. _vector3.applyProjection( _viewProjectionMatrix );
  3895. _object.z = _vector3.z;
  3896. }
  3897. _renderData.objects.push( _object );
  3898. }
  3899. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3900. _object = getNextObjectInPool();
  3901. _object.object = object;
  3902. // TODO: Find an elegant and performant solution and remove this dupe code.
  3903. if ( object.renderDepth !== null ) {
  3904. _object.z = object.renderDepth;
  3905. } else {
  3906. _vector3.copy( object.matrixWorld.getPosition() );
  3907. _vector3.applyProjection( _viewProjectionMatrix );
  3908. _object.z = _vector3.z;
  3909. }
  3910. _renderData.sprites.push( _object );
  3911. } else {
  3912. _object = getNextObjectInPool();
  3913. _object.object = object;
  3914. if ( object.renderDepth !== null ) {
  3915. _object.z = object.renderDepth;
  3916. } else {
  3917. _vector3.copy( object.matrixWorld.getPosition() );
  3918. _vector3.applyProjection( _viewProjectionMatrix );
  3919. _object.z = _vector3.z;
  3920. }
  3921. _renderData.objects.push( _object );
  3922. }
  3923. projectObject( object );
  3924. }
  3925. };
  3926. projectObject( root );
  3927. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3928. return _renderData;
  3929. };
  3930. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3931. var visible = false,
  3932. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  3933. geometry, vertices, vertex, vertexPositionScreen,
  3934. faces, face, faceVertexNormals, faceVertexUvs, uvs,
  3935. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  3936. _face3Count = 0;
  3937. _face4Count = 0;
  3938. _lineCount = 0;
  3939. _particleCount = 0;
  3940. _renderData.elements.length = 0;
  3941. scene.updateMatrixWorld();
  3942. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3943. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  3944. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  3945. _normalViewMatrix.getInverse( _viewMatrix );
  3946. _normalViewMatrix.transpose();
  3947. _frustum.setFromMatrix( _viewProjectionMatrix );
  3948. _renderData = projectGraph( scene, sortObjects );
  3949. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3950. object = _renderData.objects[ o ].object;
  3951. _modelMatrix = object.matrixWorld;
  3952. _vertexCount = 0;
  3953. if ( object instanceof THREE.Mesh ) {
  3954. geometry = object.geometry;
  3955. vertices = geometry.vertices;
  3956. faces = geometry.faces;
  3957. faceVertexUvs = geometry.faceVertexUvs;
  3958. _normalMatrix.getInverse( _modelMatrix );
  3959. _normalMatrix.transpose();
  3960. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3961. objectMaterials = isFaceMaterial === true ? object.material : null;
  3962. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  3963. _vertex = getNextVertexInPool();
  3964. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  3965. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  3966. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  3967. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  3968. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  3969. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  3970. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  3971. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  3972. }
  3973. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  3974. face = faces[ f ];
  3975. var material = isFaceMaterial === true
  3976. ? objectMaterials.materials[ face.materialIndex ]
  3977. : object.material;
  3978. if ( material === undefined ) continue;
  3979. var side = material.side;
  3980. if ( face instanceof THREE.Face3 ) {
  3981. v1 = _vertexPool[ face.a ];
  3982. v2 = _vertexPool[ face.b ];
  3983. v3 = _vertexPool[ face.c ];
  3984. _points3[ 0 ] = v1.positionScreen;
  3985. _points3[ 1 ] = v2.positionScreen;
  3986. _points3[ 2 ] = v3.positionScreen;
  3987. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  3988. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  3989. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3990. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  3991. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3992. _face = getNextFace3InPool();
  3993. _face.v1.copy( v1 );
  3994. _face.v2.copy( v2 );
  3995. _face.v3.copy( v3 );
  3996. } else {
  3997. continue;
  3998. }
  3999. } else {
  4000. continue;
  4001. }
  4002. } else if ( face instanceof THREE.Face4 ) {
  4003. v1 = _vertexPool[ face.a ];
  4004. v2 = _vertexPool[ face.b ];
  4005. v3 = _vertexPool[ face.c ];
  4006. v4 = _vertexPool[ face.d ];
  4007. _points4[ 0 ] = v1.positionScreen;
  4008. _points4[ 1 ] = v2.positionScreen;
  4009. _points4[ 2 ] = v3.positionScreen;
  4010. _points4[ 3 ] = v4.positionScreen;
  4011. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4012. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4013. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4014. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4015. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4016. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4017. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4018. _face = getNextFace4InPool();
  4019. _face.v1.copy( v1 );
  4020. _face.v2.copy( v2 );
  4021. _face.v3.copy( v3 );
  4022. _face.v4.copy( v4 );
  4023. } else {
  4024. continue;
  4025. }
  4026. } else {
  4027. continue;
  4028. }
  4029. }
  4030. _face.normalModel.copy( face.normal );
  4031. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4032. _face.normalModel.negate();
  4033. }
  4034. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4035. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4036. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4037. faceVertexNormals = face.vertexNormals;
  4038. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4039. var normalModel = _face.vertexNormalsModel[ n ];
  4040. normalModel.copy( faceVertexNormals[ n ] );
  4041. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4042. normalModel.negate();
  4043. }
  4044. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4045. var normalModelView = _face.vertexNormalsModelView[ n ];
  4046. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4047. }
  4048. _face.vertexNormalsLength = faceVertexNormals.length;
  4049. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4050. uvs = faceVertexUvs[ c ][ f ];
  4051. if ( uvs === undefined ) continue;
  4052. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4053. _face.uvs[ c ][ u ] = uvs[ u ];
  4054. }
  4055. }
  4056. _face.color = face.color;
  4057. _face.material = material;
  4058. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4059. _face.z = _centroid.z;
  4060. _renderData.elements.push( _face );
  4061. }
  4062. } else if ( object instanceof THREE.Line ) {
  4063. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4064. vertices = object.geometry.vertices;
  4065. v1 = getNextVertexInPool();
  4066. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4067. // Handle LineStrip and LinePieces
  4068. var step = object.type === THREE.LinePieces ? 2 : 1;
  4069. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4070. v1 = getNextVertexInPool();
  4071. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4072. if ( ( v + 1 ) % step > 0 ) continue;
  4073. v2 = _vertexPool[ _vertexCount - 2 ];
  4074. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4075. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4076. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4077. // Perform the perspective divide
  4078. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4079. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4080. _line = getNextLineInPool();
  4081. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4082. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4083. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4084. _line.material = object.material;
  4085. _renderData.elements.push( _line );
  4086. }
  4087. }
  4088. }
  4089. }
  4090. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4091. object = _renderData.sprites[ o ].object;
  4092. _modelMatrix = object.matrixWorld;
  4093. if ( object instanceof THREE.Particle ) {
  4094. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4095. _vector4.applyMatrix4( _viewProjectionMatrix );
  4096. _vector4.z /= _vector4.w;
  4097. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4098. _particle = getNextParticleInPool();
  4099. _particle.object = object;
  4100. _particle.x = _vector4.x / _vector4.w;
  4101. _particle.y = _vector4.y / _vector4.w;
  4102. _particle.z = _vector4.z;
  4103. _particle.rotation = object.rotation.z;
  4104. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4105. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4106. _particle.material = object.material;
  4107. _renderData.elements.push( _particle );
  4108. }
  4109. }
  4110. }
  4111. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4112. return _renderData;
  4113. };
  4114. // Pools
  4115. function getNextObjectInPool() {
  4116. if ( _objectCount === _objectPoolLength ) {
  4117. var object = new THREE.RenderableObject();
  4118. _objectPool.push( object );
  4119. _objectPoolLength ++;
  4120. _objectCount ++;
  4121. return object;
  4122. }
  4123. return _objectPool[ _objectCount ++ ];
  4124. }
  4125. function getNextVertexInPool() {
  4126. if ( _vertexCount === _vertexPoolLength ) {
  4127. var vertex = new THREE.RenderableVertex();
  4128. _vertexPool.push( vertex );
  4129. _vertexPoolLength ++;
  4130. _vertexCount ++;
  4131. return vertex;
  4132. }
  4133. return _vertexPool[ _vertexCount ++ ];
  4134. }
  4135. function getNextFace3InPool() {
  4136. if ( _face3Count === _face3PoolLength ) {
  4137. var face = new THREE.RenderableFace3();
  4138. _face3Pool.push( face );
  4139. _face3PoolLength ++;
  4140. _face3Count ++;
  4141. return face;
  4142. }
  4143. return _face3Pool[ _face3Count ++ ];
  4144. }
  4145. function getNextFace4InPool() {
  4146. if ( _face4Count === _face4PoolLength ) {
  4147. var face = new THREE.RenderableFace4();
  4148. _face4Pool.push( face );
  4149. _face4PoolLength ++;
  4150. _face4Count ++;
  4151. return face;
  4152. }
  4153. return _face4Pool[ _face4Count ++ ];
  4154. }
  4155. function getNextLineInPool() {
  4156. if ( _lineCount === _linePoolLength ) {
  4157. var line = new THREE.RenderableLine();
  4158. _linePool.push( line );
  4159. _linePoolLength ++;
  4160. _lineCount ++
  4161. return line;
  4162. }
  4163. return _linePool[ _lineCount ++ ];
  4164. }
  4165. function getNextParticleInPool() {
  4166. if ( _particleCount === _particlePoolLength ) {
  4167. var particle = new THREE.RenderableParticle();
  4168. _particlePool.push( particle );
  4169. _particlePoolLength ++;
  4170. _particleCount ++
  4171. return particle;
  4172. }
  4173. return _particlePool[ _particleCount ++ ];
  4174. }
  4175. //
  4176. function painterSort( a, b ) {
  4177. return b.z - a.z;
  4178. }
  4179. function clipLine( s1, s2 ) {
  4180. var alpha1 = 0, alpha2 = 1,
  4181. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4182. // Z = -1 and Z = +1, respectively.
  4183. bc1near = s1.z + s1.w,
  4184. bc2near = s2.z + s2.w,
  4185. bc1far = - s1.z + s1.w,
  4186. bc2far = - s2.z + s2.w;
  4187. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4188. // Both vertices lie entirely within all clip planes.
  4189. return true;
  4190. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4191. // Both vertices lie entirely outside one of the clip planes.
  4192. return false;
  4193. } else {
  4194. // The line segment spans at least one clip plane.
  4195. if ( bc1near < 0 ) {
  4196. // v1 lies outside the near plane, v2 inside
  4197. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4198. } else if ( bc2near < 0 ) {
  4199. // v2 lies outside the near plane, v1 inside
  4200. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4201. }
  4202. if ( bc1far < 0 ) {
  4203. // v1 lies outside the far plane, v2 inside
  4204. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4205. } else if ( bc2far < 0 ) {
  4206. // v2 lies outside the far plane, v2 inside
  4207. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4208. }
  4209. if ( alpha2 < alpha1 ) {
  4210. // The line segment spans two boundaries, but is outside both of them.
  4211. // (This can't happen when we're only clipping against just near/far but good
  4212. // to leave the check here for future usage if other clip planes are added.)
  4213. return false;
  4214. } else {
  4215. // Update the s1 and s2 vertices to match the clipped line segment.
  4216. s1.lerp( s2, alpha1 );
  4217. s2.lerp( s1, 1 - alpha2 );
  4218. return true;
  4219. }
  4220. }
  4221. }
  4222. };
  4223. /**
  4224. * @author mrdoob / http://mrdoob.com/
  4225. * @author alteredq / http://alteredqualia.com/
  4226. */
  4227. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4228. this.a = a;
  4229. this.b = b;
  4230. this.c = c;
  4231. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4232. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4233. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4234. this.vertexColors = color instanceof Array ? color : [];
  4235. this.vertexTangents = [];
  4236. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4237. this.centroid = new THREE.Vector3();
  4238. };
  4239. THREE.Face3.prototype = {
  4240. constructor: THREE.Face3,
  4241. clone: function () {
  4242. var face = new THREE.Face3( this.a, this.b, this.c );
  4243. face.normal.copy( this.normal );
  4244. face.color.copy( this.color );
  4245. face.centroid.copy( this.centroid );
  4246. face.materialIndex = this.materialIndex;
  4247. var i, il;
  4248. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4249. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4250. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4251. return face;
  4252. }
  4253. };
  4254. /**
  4255. * @author mrdoob / http://mrdoob.com/
  4256. * @author alteredq / http://alteredqualia.com/
  4257. */
  4258. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4259. this.a = a;
  4260. this.b = b;
  4261. this.c = c;
  4262. this.d = d;
  4263. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4264. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4265. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4266. this.vertexColors = color instanceof Array ? color : [];
  4267. this.vertexTangents = [];
  4268. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4269. this.centroid = new THREE.Vector3();
  4270. };
  4271. THREE.Face4.prototype = {
  4272. constructor: THREE.Face4,
  4273. clone: function () {
  4274. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4275. face.normal.copy( this.normal );
  4276. face.color.copy( this.color );
  4277. face.centroid.copy( this.centroid );
  4278. face.materialIndex = this.materialIndex;
  4279. var i, il;
  4280. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4281. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4282. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4283. return face;
  4284. }
  4285. };
  4286. /**
  4287. * @author mrdoob / http://mrdoob.com/
  4288. * @author kile / http://kile.stravaganza.org/
  4289. * @author alteredq / http://alteredqualia.com/
  4290. * @author mikael emtinger / http://gomo.se/
  4291. * @author zz85 / http://www.lab4games.net/zz85/blog
  4292. * @author bhouston / http://exocortex.com
  4293. */
  4294. THREE.Geometry = function () {
  4295. THREE.EventDispatcher.call( this );
  4296. this.id = THREE.GeometryIdCount ++;
  4297. this.name = '';
  4298. this.vertices = [];
  4299. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4300. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4301. this.faces = [];
  4302. this.faceUvs = [[]];
  4303. this.faceVertexUvs = [[]];
  4304. this.morphTargets = [];
  4305. this.morphColors = [];
  4306. this.morphNormals = [];
  4307. this.skinWeights = [];
  4308. this.skinIndices = [];
  4309. this.lineDistances = [];
  4310. this.boundingBox = null;
  4311. this.boundingSphere = null;
  4312. this.hasTangents = false;
  4313. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4314. // update flags
  4315. this.verticesNeedUpdate = false;
  4316. this.elementsNeedUpdate = false;
  4317. this.uvsNeedUpdate = false;
  4318. this.normalsNeedUpdate = false;
  4319. this.tangentsNeedUpdate = false;
  4320. this.colorsNeedUpdate = false;
  4321. this.lineDistancesNeedUpdate = false;
  4322. this.buffersNeedUpdate = false;
  4323. };
  4324. THREE.Geometry.prototype = {
  4325. constructor: THREE.Geometry,
  4326. applyMatrix: function ( matrix ) {
  4327. var normalMatrix = new THREE.Matrix3().getInverse( matrix ).transpose();
  4328. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4329. var vertex = this.vertices[ i ];
  4330. vertex.applyMatrix4( matrix );
  4331. }
  4332. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4333. var face = this.faces[ i ];
  4334. face.normal.applyMatrix3( normalMatrix ).normalize();
  4335. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4336. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4337. }
  4338. face.centroid.applyMatrix4( matrix );
  4339. }
  4340. },
  4341. computeCentroids: function () {
  4342. var f, fl, face;
  4343. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4344. face = this.faces[ f ];
  4345. face.centroid.set( 0, 0, 0 );
  4346. if ( face instanceof THREE.Face3 ) {
  4347. face.centroid.add( this.vertices[ face.a ] );
  4348. face.centroid.add( this.vertices[ face.b ] );
  4349. face.centroid.add( this.vertices[ face.c ] );
  4350. face.centroid.divideScalar( 3 );
  4351. } else if ( face instanceof THREE.Face4 ) {
  4352. face.centroid.add( this.vertices[ face.a ] );
  4353. face.centroid.add( this.vertices[ face.b ] );
  4354. face.centroid.add( this.vertices[ face.c ] );
  4355. face.centroid.add( this.vertices[ face.d ] );
  4356. face.centroid.divideScalar( 4 );
  4357. }
  4358. }
  4359. },
  4360. computeFaceNormals: function () {
  4361. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  4362. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4363. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4364. face = this.faces[ f ];
  4365. vA = this.vertices[ face.a ];
  4366. vB = this.vertices[ face.b ];
  4367. vC = this.vertices[ face.c ];
  4368. cb.subVectors( vC, vB );
  4369. ab.subVectors( vA, vB );
  4370. cb.cross( ab );
  4371. cb.normalize();
  4372. face.normal.copy( cb );
  4373. }
  4374. },
  4375. computeVertexNormals: function ( areaWeighted ) {
  4376. var v, vl, f, fl, face, vertices;
  4377. // create internal buffers for reuse when calling this method repeatedly
  4378. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4379. if ( this.__tmpVertices === undefined ) {
  4380. this.__tmpVertices = new Array( this.vertices.length );
  4381. vertices = this.__tmpVertices;
  4382. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4383. vertices[ v ] = new THREE.Vector3();
  4384. }
  4385. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4386. face = this.faces[ f ];
  4387. if ( face instanceof THREE.Face3 ) {
  4388. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4389. } else if ( face instanceof THREE.Face4 ) {
  4390. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4391. }
  4392. }
  4393. } else {
  4394. vertices = this.__tmpVertices;
  4395. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4396. vertices[ v ].set( 0, 0, 0 );
  4397. }
  4398. }
  4399. if ( areaWeighted ) {
  4400. // vertex normals weighted by triangle areas
  4401. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4402. var vA, vB, vC, vD;
  4403. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4404. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4405. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4406. face = this.faces[ f ];
  4407. if ( face instanceof THREE.Face3 ) {
  4408. vA = this.vertices[ face.a ];
  4409. vB = this.vertices[ face.b ];
  4410. vC = this.vertices[ face.c ];
  4411. cb.subVectors( vC, vB );
  4412. ab.subVectors( vA, vB );
  4413. cb.cross( ab );
  4414. vertices[ face.a ].add( cb );
  4415. vertices[ face.b ].add( cb );
  4416. vertices[ face.c ].add( cb );
  4417. } else if ( face instanceof THREE.Face4 ) {
  4418. vA = this.vertices[ face.a ];
  4419. vB = this.vertices[ face.b ];
  4420. vC = this.vertices[ face.c ];
  4421. vD = this.vertices[ face.d ];
  4422. // abd
  4423. db.subVectors( vD, vB );
  4424. ab.subVectors( vA, vB );
  4425. db.cross( ab );
  4426. vertices[ face.a ].add( db );
  4427. vertices[ face.b ].add( db );
  4428. vertices[ face.d ].add( db );
  4429. // bcd
  4430. dc.subVectors( vD, vC );
  4431. bc.subVectors( vB, vC );
  4432. dc.cross( bc );
  4433. vertices[ face.b ].add( dc );
  4434. vertices[ face.c ].add( dc );
  4435. vertices[ face.d ].add( dc );
  4436. }
  4437. }
  4438. } else {
  4439. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4440. face = this.faces[ f ];
  4441. if ( face instanceof THREE.Face3 ) {
  4442. vertices[ face.a ].add( face.normal );
  4443. vertices[ face.b ].add( face.normal );
  4444. vertices[ face.c ].add( face.normal );
  4445. } else if ( face instanceof THREE.Face4 ) {
  4446. vertices[ face.a ].add( face.normal );
  4447. vertices[ face.b ].add( face.normal );
  4448. vertices[ face.c ].add( face.normal );
  4449. vertices[ face.d ].add( face.normal );
  4450. }
  4451. }
  4452. }
  4453. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4454. vertices[ v ].normalize();
  4455. }
  4456. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4457. face = this.faces[ f ];
  4458. if ( face instanceof THREE.Face3 ) {
  4459. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4460. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4461. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4462. } else if ( face instanceof THREE.Face4 ) {
  4463. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4464. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4465. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4466. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4467. }
  4468. }
  4469. },
  4470. computeMorphNormals: function () {
  4471. var i, il, f, fl, face;
  4472. // save original normals
  4473. // - create temp variables on first access
  4474. // otherwise just copy (for faster repeated calls)
  4475. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4476. face = this.faces[ f ];
  4477. if ( ! face.__originalFaceNormal ) {
  4478. face.__originalFaceNormal = face.normal.clone();
  4479. } else {
  4480. face.__originalFaceNormal.copy( face.normal );
  4481. }
  4482. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4483. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4484. if ( ! face.__originalVertexNormals[ i ] ) {
  4485. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4486. } else {
  4487. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4488. }
  4489. }
  4490. }
  4491. // use temp geometry to compute face and vertex normals for each morph
  4492. var tmpGeo = new THREE.Geometry();
  4493. tmpGeo.faces = this.faces;
  4494. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4495. // create on first access
  4496. if ( ! this.morphNormals[ i ] ) {
  4497. this.morphNormals[ i ] = {};
  4498. this.morphNormals[ i ].faceNormals = [];
  4499. this.morphNormals[ i ].vertexNormals = [];
  4500. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4501. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4502. var faceNormal, vertexNormals;
  4503. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4504. face = this.faces[ f ];
  4505. faceNormal = new THREE.Vector3();
  4506. if ( face instanceof THREE.Face3 ) {
  4507. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4508. } else {
  4509. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4510. }
  4511. dstNormalsFace.push( faceNormal );
  4512. dstNormalsVertex.push( vertexNormals );
  4513. }
  4514. }
  4515. var morphNormals = this.morphNormals[ i ];
  4516. // set vertices to morph target
  4517. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4518. // compute morph normals
  4519. tmpGeo.computeFaceNormals();
  4520. tmpGeo.computeVertexNormals();
  4521. // store morph normals
  4522. var faceNormal, vertexNormals;
  4523. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4524. face = this.faces[ f ];
  4525. faceNormal = morphNormals.faceNormals[ f ];
  4526. vertexNormals = morphNormals.vertexNormals[ f ];
  4527. faceNormal.copy( face.normal );
  4528. if ( face instanceof THREE.Face3 ) {
  4529. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4530. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4531. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4532. } else {
  4533. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4534. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4535. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4536. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4537. }
  4538. }
  4539. }
  4540. // restore original normals
  4541. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4542. face = this.faces[ f ];
  4543. face.normal = face.__originalFaceNormal;
  4544. face.vertexNormals = face.__originalVertexNormals;
  4545. }
  4546. },
  4547. computeTangents: function () {
  4548. // based on http://www.terathon.com/code/tangent.html
  4549. // tangents go to vertices
  4550. var f, fl, v, vl, i, il, vertexIndex,
  4551. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4552. x1, x2, y1, y2, z1, z2,
  4553. s1, s2, t1, t2, r, t, test,
  4554. tan1 = [], tan2 = [],
  4555. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4556. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4557. n = new THREE.Vector3(), w;
  4558. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4559. tan1[ v ] = new THREE.Vector3();
  4560. tan2[ v ] = new THREE.Vector3();
  4561. }
  4562. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4563. vA = context.vertices[ a ];
  4564. vB = context.vertices[ b ];
  4565. vC = context.vertices[ c ];
  4566. uvA = uv[ ua ];
  4567. uvB = uv[ ub ];
  4568. uvC = uv[ uc ];
  4569. x1 = vB.x - vA.x;
  4570. x2 = vC.x - vA.x;
  4571. y1 = vB.y - vA.y;
  4572. y2 = vC.y - vA.y;
  4573. z1 = vB.z - vA.z;
  4574. z2 = vC.z - vA.z;
  4575. s1 = uvB.x - uvA.x;
  4576. s2 = uvC.x - uvA.x;
  4577. t1 = uvB.y - uvA.y;
  4578. t2 = uvC.y - uvA.y;
  4579. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4580. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4581. ( t2 * y1 - t1 * y2 ) * r,
  4582. ( t2 * z1 - t1 * z2 ) * r );
  4583. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4584. ( s1 * y2 - s2 * y1 ) * r,
  4585. ( s1 * z2 - s2 * z1 ) * r );
  4586. tan1[ a ].add( sdir );
  4587. tan1[ b ].add( sdir );
  4588. tan1[ c ].add( sdir );
  4589. tan2[ a ].add( tdir );
  4590. tan2[ b ].add( tdir );
  4591. tan2[ c ].add( tdir );
  4592. }
  4593. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4594. face = this.faces[ f ];
  4595. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4596. if ( face instanceof THREE.Face3 ) {
  4597. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4598. } else if ( face instanceof THREE.Face4 ) {
  4599. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4600. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4601. }
  4602. }
  4603. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4604. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4605. face = this.faces[ f ];
  4606. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4607. n.copy( face.vertexNormals[ i ] );
  4608. vertexIndex = face[ faceIndex[ i ] ];
  4609. t = tan1[ vertexIndex ];
  4610. // Gram-Schmidt orthogonalize
  4611. tmp.copy( t );
  4612. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4613. // Calculate handedness
  4614. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4615. test = tmp2.dot( tan2[ vertexIndex ] );
  4616. w = (test < 0.0) ? -1.0 : 1.0;
  4617. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4618. }
  4619. }
  4620. this.hasTangents = true;
  4621. },
  4622. computeLineDistances: function ( ) {
  4623. var d = 0;
  4624. var vertices = this.vertices;
  4625. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4626. if ( i > 0 ) {
  4627. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4628. }
  4629. this.lineDistances[ i ] = d;
  4630. }
  4631. },
  4632. computeBoundingBox: function () {
  4633. if ( this.boundingBox === null ) {
  4634. this.boundingBox = new THREE.Box3();
  4635. }
  4636. this.boundingBox.setFromPoints( this.vertices );
  4637. },
  4638. computeBoundingSphere: function () {
  4639. if ( this.boundingSphere === null ) {
  4640. this.boundingSphere = new THREE.Sphere();
  4641. }
  4642. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4643. },
  4644. /*
  4645. * Checks for duplicate vertices with hashmap.
  4646. * Duplicated vertices are removed
  4647. * and faces' vertices are updated.
  4648. */
  4649. mergeVertices: function () {
  4650. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4651. var unique = [], changes = [];
  4652. var v, key;
  4653. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4654. var precision = Math.pow( 10, precisionPoints );
  4655. var i,il, face;
  4656. var indices, k, j, jl, u;
  4657. // reset cache of vertices as it now will be changing.
  4658. this.__tmpVertices = undefined;
  4659. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4660. v = this.vertices[ i ];
  4661. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4662. if ( verticesMap[ key ] === undefined ) {
  4663. verticesMap[ key ] = i;
  4664. unique.push( this.vertices[ i ] );
  4665. changes[ i ] = unique.length - 1;
  4666. } else {
  4667. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4668. changes[ i ] = changes[ verticesMap[ key ] ];
  4669. }
  4670. };
  4671. // if faces are completely degenerate after merging vertices, we
  4672. // have to remove them from the geometry.
  4673. var faceIndicesToRemove = [];
  4674. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4675. face = this.faces[ i ];
  4676. if ( face instanceof THREE.Face3 ) {
  4677. face.a = changes[ face.a ];
  4678. face.b = changes[ face.b ];
  4679. face.c = changes[ face.c ];
  4680. indices = [ face.a, face.b, face.c ];
  4681. var dupIndex = -1;
  4682. // if any duplicate vertices are found in a Face3
  4683. // we have to remove the face as nothing can be saved
  4684. for ( var n = 0; n < 3; n ++ ) {
  4685. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4686. dupIndex = n;
  4687. faceIndicesToRemove.push( i );
  4688. break;
  4689. }
  4690. }
  4691. } else if ( face instanceof THREE.Face4 ) {
  4692. face.a = changes[ face.a ];
  4693. face.b = changes[ face.b ];
  4694. face.c = changes[ face.c ];
  4695. face.d = changes[ face.d ];
  4696. // check dups in (a, b, c, d) and convert to -> face3
  4697. indices = [ face.a, face.b, face.c, face.d ];
  4698. var dupIndex = -1;
  4699. for ( var n = 0; n < 4; n ++ ) {
  4700. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4701. // if more than one duplicated vertex is found
  4702. // we can't generate any valid Face3's, thus
  4703. // we need to remove this face complete.
  4704. if ( dupIndex >= 0 ) {
  4705. faceIndicesToRemove.push( i );
  4706. }
  4707. dupIndex = n;
  4708. }
  4709. }
  4710. if ( dupIndex >= 0 ) {
  4711. indices.splice( dupIndex, 1 );
  4712. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4713. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4714. u = this.faceVertexUvs[ j ][ i ];
  4715. if ( u ) {
  4716. u.splice( dupIndex, 1 );
  4717. }
  4718. }
  4719. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4720. newFace.vertexNormals = face.vertexNormals;
  4721. newFace.vertexNormals.splice( dupIndex, 1 );
  4722. }
  4723. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4724. newFace.vertexColors = face.vertexColors;
  4725. newFace.vertexColors.splice( dupIndex, 1 );
  4726. }
  4727. this.faces[ i ] = newFace;
  4728. }
  4729. }
  4730. }
  4731. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4732. this.faces.splice( i, 1 );
  4733. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4734. this.faceVertexUvs[ j ].splice( i, 1 );
  4735. }
  4736. }
  4737. // Use unique set of vertices
  4738. var diff = this.vertices.length - unique.length;
  4739. this.vertices = unique;
  4740. return diff;
  4741. },
  4742. clone: function () {
  4743. var geometry = new THREE.Geometry();
  4744. var vertices = this.vertices;
  4745. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4746. geometry.vertices.push( vertices[ i ].clone() );
  4747. }
  4748. var faces = this.faces;
  4749. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4750. geometry.faces.push( faces[ i ].clone() );
  4751. }
  4752. var uvs = this.faceVertexUvs[ 0 ];
  4753. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4754. var uv = uvs[ i ], uvCopy = [];
  4755. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4756. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4757. }
  4758. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4759. }
  4760. return geometry;
  4761. },
  4762. dispose: function () {
  4763. this.dispatchEvent( { type: 'dispose' } );
  4764. }
  4765. };
  4766. THREE.GeometryIdCount = 0;
  4767. /**
  4768. * @author alteredq / http://alteredqualia.com/
  4769. */
  4770. THREE.BufferGeometry = function () {
  4771. THREE.EventDispatcher.call( this );
  4772. this.id = THREE.GeometryIdCount ++;
  4773. // attributes
  4774. this.attributes = {};
  4775. // attributes typed arrays are kept only if dynamic flag is set
  4776. this.dynamic = false;
  4777. // offsets for chunks when using indexed elements
  4778. this.offsets = [];
  4779. // boundings
  4780. this.boundingBox = null;
  4781. this.boundingSphere = null;
  4782. this.hasTangents = false;
  4783. // for compatibility
  4784. this.morphTargets = [];
  4785. };
  4786. THREE.BufferGeometry.prototype = {
  4787. constructor : THREE.BufferGeometry,
  4788. applyMatrix: function ( matrix ) {
  4789. var positionArray;
  4790. var normalArray;
  4791. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4792. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4793. if ( positionArray !== undefined ) {
  4794. matrix.multiplyVector3Array( positionArray );
  4795. this.verticesNeedUpdate = true;
  4796. }
  4797. if ( normalArray !== undefined ) {
  4798. var normalMatrix = new THREE.Matrix3();
  4799. normalMatrix.getInverse( matrix ).transpose();
  4800. normalMatrix.multiplyVector3Array( normalArray );
  4801. this.normalizeNormals();
  4802. this.normalsNeedUpdate = true;
  4803. }
  4804. },
  4805. computeBoundingBox: function () {
  4806. if ( this.boundingBox === null ) {
  4807. this.boundingBox = new THREE.Box3();
  4808. }
  4809. var positions = this.attributes[ "position" ].array;
  4810. if ( positions ) {
  4811. var bb = this.boundingBox;
  4812. var x, y, z;
  4813. if( positions.length >= 3 ) {
  4814. bb.min.x = bb.max.x = positions[ 0 ];
  4815. bb.min.y = bb.max.y = positions[ 1 ];
  4816. bb.min.z = bb.max.z = positions[ 2 ];
  4817. }
  4818. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4819. x = positions[ i ];
  4820. y = positions[ i + 1 ];
  4821. z = positions[ i + 2 ];
  4822. // bounding box
  4823. if ( x < bb.min.x ) {
  4824. bb.min.x = x;
  4825. } else if ( x > bb.max.x ) {
  4826. bb.max.x = x;
  4827. }
  4828. if ( y < bb.min.y ) {
  4829. bb.min.y = y;
  4830. } else if ( y > bb.max.y ) {
  4831. bb.max.y = y;
  4832. }
  4833. if ( z < bb.min.z ) {
  4834. bb.min.z = z;
  4835. } else if ( z > bb.max.z ) {
  4836. bb.max.z = z;
  4837. }
  4838. }
  4839. }
  4840. if ( positions === undefined || positions.length === 0 ) {
  4841. this.boundingBox.min.set( 0, 0, 0 );
  4842. this.boundingBox.max.set( 0, 0, 0 );
  4843. }
  4844. },
  4845. computeBoundingSphere: function () {
  4846. if ( this.boundingSphere === null ) {
  4847. this.boundingSphere = new THREE.Sphere();
  4848. }
  4849. var positions = this.attributes[ "position" ].array;
  4850. if ( positions ) {
  4851. var radiusSq, maxRadiusSq = 0;
  4852. var x, y, z;
  4853. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4854. x = positions[ i ];
  4855. y = positions[ i + 1 ];
  4856. z = positions[ i + 2 ];
  4857. radiusSq = x * x + y * y + z * z;
  4858. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4859. }
  4860. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4861. }
  4862. },
  4863. computeVertexNormals: function () {
  4864. if ( this.attributes[ "position" ] ) {
  4865. var i, il;
  4866. var j, jl;
  4867. var nVertexElements = this.attributes[ "position" ].array.length;
  4868. if ( this.attributes[ "normal" ] === undefined ) {
  4869. this.attributes[ "normal" ] = {
  4870. itemSize: 3,
  4871. array: new Float32Array( nVertexElements ),
  4872. numItems: nVertexElements
  4873. };
  4874. } else {
  4875. // reset existing normals to zero
  4876. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4877. this.attributes[ "normal" ].array[ i ] = 0;
  4878. }
  4879. }
  4880. var positions = this.attributes[ "position" ].array;
  4881. var normals = this.attributes[ "normal" ].array;
  4882. var vA, vB, vC, x, y, z,
  4883. pA = new THREE.Vector3(),
  4884. pB = new THREE.Vector3(),
  4885. pC = new THREE.Vector3(),
  4886. cb = new THREE.Vector3(),
  4887. ab = new THREE.Vector3();
  4888. // indexed elements
  4889. if ( this.attributes[ "index" ] ) {
  4890. var indices = this.attributes[ "index" ].array;
  4891. var offsets = this.offsets;
  4892. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4893. var start = offsets[ j ].start;
  4894. var count = offsets[ j ].count;
  4895. var index = offsets[ j ].index;
  4896. for ( i = start, il = start + count; i < il; i += 3 ) {
  4897. vA = index + indices[ i ];
  4898. vB = index + indices[ i + 1 ];
  4899. vC = index + indices[ i + 2 ];
  4900. x = positions[ vA * 3 ];
  4901. y = positions[ vA * 3 + 1 ];
  4902. z = positions[ vA * 3 + 2 ];
  4903. pA.set( x, y, z );
  4904. x = positions[ vB * 3 ];
  4905. y = positions[ vB * 3 + 1 ];
  4906. z = positions[ vB * 3 + 2 ];
  4907. pB.set( x, y, z );
  4908. x = positions[ vC * 3 ];
  4909. y = positions[ vC * 3 + 1 ];
  4910. z = positions[ vC * 3 + 2 ];
  4911. pC.set( x, y, z );
  4912. cb.subVectors( pC, pB );
  4913. ab.subVectors( pA, pB );
  4914. cb.cross( ab );
  4915. normals[ vA * 3 ] += cb.x;
  4916. normals[ vA * 3 + 1 ] += cb.y;
  4917. normals[ vA * 3 + 2 ] += cb.z;
  4918. normals[ vB * 3 ] += cb.x;
  4919. normals[ vB * 3 + 1 ] += cb.y;
  4920. normals[ vB * 3 + 2 ] += cb.z;
  4921. normals[ vC * 3 ] += cb.x;
  4922. normals[ vC * 3 + 1 ] += cb.y;
  4923. normals[ vC * 3 + 2 ] += cb.z;
  4924. }
  4925. }
  4926. // non-indexed elements (unconnected triangle soup)
  4927. } else {
  4928. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4929. x = positions[ i ];
  4930. y = positions[ i + 1 ];
  4931. z = positions[ i + 2 ];
  4932. pA.set( x, y, z );
  4933. x = positions[ i + 3 ];
  4934. y = positions[ i + 4 ];
  4935. z = positions[ i + 5 ];
  4936. pB.set( x, y, z );
  4937. x = positions[ i + 6 ];
  4938. y = positions[ i + 7 ];
  4939. z = positions[ i + 8 ];
  4940. pC.set( x, y, z );
  4941. cb.subVectors( pC, pB );
  4942. ab.subVectors( pA, pB );
  4943. cb.cross( ab );
  4944. normals[ i ] = cb.x;
  4945. normals[ i + 1 ] = cb.y;
  4946. normals[ i + 2 ] = cb.z;
  4947. normals[ i + 3 ] = cb.x;
  4948. normals[ i + 4 ] = cb.y;
  4949. normals[ i + 5 ] = cb.z;
  4950. normals[ i + 6 ] = cb.x;
  4951. normals[ i + 7 ] = cb.y;
  4952. normals[ i + 8 ] = cb.z;
  4953. }
  4954. }
  4955. this.normalizeNormals();
  4956. this.normalsNeedUpdate = true;
  4957. }
  4958. },
  4959. normalizeNormals: function () {
  4960. var normals = this.attributes[ "normal" ].array;
  4961. var x, y, z, n;
  4962. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  4963. x = normals[ i ];
  4964. y = normals[ i + 1 ];
  4965. z = normals[ i + 2 ];
  4966. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  4967. normals[ i ] *= n;
  4968. normals[ i + 1 ] *= n;
  4969. normals[ i + 2 ] *= n;
  4970. }
  4971. },
  4972. computeTangents: function () {
  4973. // based on http://www.terathon.com/code/tangent.html
  4974. // (per vertex tangents)
  4975. if ( this.attributes[ "index" ] === undefined ||
  4976. this.attributes[ "position" ] === undefined ||
  4977. this.attributes[ "normal" ] === undefined ||
  4978. this.attributes[ "uv" ] === undefined ) {
  4979. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  4980. return;
  4981. }
  4982. var indices = this.attributes[ "index" ].array;
  4983. var positions = this.attributes[ "position" ].array;
  4984. var normals = this.attributes[ "normal" ].array;
  4985. var uvs = this.attributes[ "uv" ].array;
  4986. var nVertices = positions.length / 3;
  4987. if ( this.attributes[ "tangent" ] === undefined ) {
  4988. var nTangentElements = 4 * nVertices;
  4989. this.attributes[ "tangent" ] = {
  4990. itemSize: 4,
  4991. array: new Float32Array( nTangentElements ),
  4992. numItems: nTangentElements
  4993. };
  4994. }
  4995. var tangents = this.attributes[ "tangent" ].array;
  4996. var tan1 = [], tan2 = [];
  4997. for ( var k = 0; k < nVertices; k ++ ) {
  4998. tan1[ k ] = new THREE.Vector3();
  4999. tan2[ k ] = new THREE.Vector3();
  5000. }
  5001. var xA, yA, zA,
  5002. xB, yB, zB,
  5003. xC, yC, zC,
  5004. uA, vA,
  5005. uB, vB,
  5006. uC, vC,
  5007. x1, x2, y1, y2, z1, z2,
  5008. s1, s2, t1, t2, r;
  5009. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5010. function handleTriangle( a, b, c ) {
  5011. xA = positions[ a * 3 ];
  5012. yA = positions[ a * 3 + 1 ];
  5013. zA = positions[ a * 3 + 2 ];
  5014. xB = positions[ b * 3 ];
  5015. yB = positions[ b * 3 + 1 ];
  5016. zB = positions[ b * 3 + 2 ];
  5017. xC = positions[ c * 3 ];
  5018. yC = positions[ c * 3 + 1 ];
  5019. zC = positions[ c * 3 + 2 ];
  5020. uA = uvs[ a * 2 ];
  5021. vA = uvs[ a * 2 + 1 ];
  5022. uB = uvs[ b * 2 ];
  5023. vB = uvs[ b * 2 + 1 ];
  5024. uC = uvs[ c * 2 ];
  5025. vC = uvs[ c * 2 + 1 ];
  5026. x1 = xB - xA;
  5027. x2 = xC - xA;
  5028. y1 = yB - yA;
  5029. y2 = yC - yA;
  5030. z1 = zB - zA;
  5031. z2 = zC - zA;
  5032. s1 = uB - uA;
  5033. s2 = uC - uA;
  5034. t1 = vB - vA;
  5035. t2 = vC - vA;
  5036. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5037. sdir.set(
  5038. ( t2 * x1 - t1 * x2 ) * r,
  5039. ( t2 * y1 - t1 * y2 ) * r,
  5040. ( t2 * z1 - t1 * z2 ) * r
  5041. );
  5042. tdir.set(
  5043. ( s1 * x2 - s2 * x1 ) * r,
  5044. ( s1 * y2 - s2 * y1 ) * r,
  5045. ( s1 * z2 - s2 * z1 ) * r
  5046. );
  5047. tan1[ a ].add( sdir );
  5048. tan1[ b ].add( sdir );
  5049. tan1[ c ].add( sdir );
  5050. tan2[ a ].add( tdir );
  5051. tan2[ b ].add( tdir );
  5052. tan2[ c ].add( tdir );
  5053. }
  5054. var i, il;
  5055. var j, jl;
  5056. var iA, iB, iC;
  5057. var offsets = this.offsets;
  5058. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5059. var start = offsets[ j ].start;
  5060. var count = offsets[ j ].count;
  5061. var index = offsets[ j ].index;
  5062. for ( i = start, il = start + count; i < il; i += 3 ) {
  5063. iA = index + indices[ i ];
  5064. iB = index + indices[ i + 1 ];
  5065. iC = index + indices[ i + 2 ];
  5066. handleTriangle( iA, iB, iC );
  5067. }
  5068. }
  5069. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5070. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5071. var w, t, test;
  5072. var nx, ny, nz;
  5073. function handleVertex( v ) {
  5074. n.x = normals[ v * 3 ];
  5075. n.y = normals[ v * 3 + 1 ];
  5076. n.z = normals[ v * 3 + 2 ];
  5077. n2.copy( n );
  5078. t = tan1[ v ];
  5079. // Gram-Schmidt orthogonalize
  5080. tmp.copy( t );
  5081. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5082. // Calculate handedness
  5083. tmp2.crossVectors( n2, t );
  5084. test = tmp2.dot( tan2[ v ] );
  5085. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5086. tangents[ v * 4 ] = tmp.x;
  5087. tangents[ v * 4 + 1 ] = tmp.y;
  5088. tangents[ v * 4 + 2 ] = tmp.z;
  5089. tangents[ v * 4 + 3 ] = w;
  5090. }
  5091. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5092. var start = offsets[ j ].start;
  5093. var count = offsets[ j ].count;
  5094. var index = offsets[ j ].index;
  5095. for ( i = start, il = start + count; i < il; i += 3 ) {
  5096. iA = index + indices[ i ];
  5097. iB = index + indices[ i + 1 ];
  5098. iC = index + indices[ i + 2 ];
  5099. handleVertex( iA );
  5100. handleVertex( iB );
  5101. handleVertex( iC );
  5102. }
  5103. }
  5104. this.hasTangents = true;
  5105. this.tangentsNeedUpdate = true;
  5106. },
  5107. dispose: function () {
  5108. this.dispatchEvent( { type: 'dispose' } );
  5109. }
  5110. };
  5111. /**
  5112. * @author mrdoob / http://mrdoob.com/
  5113. * @author mikael emtinger / http://gomo.se/
  5114. */
  5115. THREE.Camera = function () {
  5116. THREE.Object3D.call( this );
  5117. this.matrixWorldInverse = new THREE.Matrix4();
  5118. this.projectionMatrix = new THREE.Matrix4();
  5119. this.projectionMatrixInverse = new THREE.Matrix4();
  5120. };
  5121. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5122. THREE.Camera.prototype.lookAt = function ( vector ) {
  5123. // TODO: Add hierarchy support.
  5124. this.matrix.lookAt( this.position, vector, this.up );
  5125. if ( this.rotationAutoUpdate === true ) {
  5126. if ( this.useQuaternion === false ) {
  5127. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  5128. } else {
  5129. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  5130. }
  5131. }
  5132. };
  5133. /**
  5134. * @author alteredq / http://alteredqualia.com/
  5135. */
  5136. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5137. THREE.Camera.call( this );
  5138. this.left = left;
  5139. this.right = right;
  5140. this.top = top;
  5141. this.bottom = bottom;
  5142. this.near = ( near !== undefined ) ? near : 0.1;
  5143. this.far = ( far !== undefined ) ? far : 2000;
  5144. this.updateProjectionMatrix();
  5145. };
  5146. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5147. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5148. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5149. };
  5150. /**
  5151. * @author mrdoob / http://mrdoob.com/
  5152. * @author greggman / http://games.greggman.com/
  5153. * @author zz85 / http://www.lab4games.net/zz85/blog
  5154. */
  5155. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5156. THREE.Camera.call( this );
  5157. this.fov = fov !== undefined ? fov : 50;
  5158. this.aspect = aspect !== undefined ? aspect : 1;
  5159. this.near = near !== undefined ? near : 0.1;
  5160. this.far = far !== undefined ? far : 2000;
  5161. this.updateProjectionMatrix();
  5162. };
  5163. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5164. /**
  5165. * Uses Focal Length (in mm) to estimate and set FOV
  5166. * 35mm (fullframe) camera is used if frame size is not specified;
  5167. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5168. */
  5169. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5170. if ( frameHeight === undefined ) frameHeight = 24;
  5171. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5172. this.updateProjectionMatrix();
  5173. }
  5174. /**
  5175. * Sets an offset in a larger frustum. This is useful for multi-window or
  5176. * multi-monitor/multi-machine setups.
  5177. *
  5178. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5179. * the monitors are in grid like this
  5180. *
  5181. * +---+---+---+
  5182. * | A | B | C |
  5183. * +---+---+---+
  5184. * | D | E | F |
  5185. * +---+---+---+
  5186. *
  5187. * then for each monitor you would call it like this
  5188. *
  5189. * var w = 1920;
  5190. * var h = 1080;
  5191. * var fullWidth = w * 3;
  5192. * var fullHeight = h * 2;
  5193. *
  5194. * --A--
  5195. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5196. * --B--
  5197. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5198. * --C--
  5199. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5200. * --D--
  5201. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5202. * --E--
  5203. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5204. * --F--
  5205. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5206. *
  5207. * Note there is no reason monitors have to be the same size or in a grid.
  5208. */
  5209. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5210. this.fullWidth = fullWidth;
  5211. this.fullHeight = fullHeight;
  5212. this.x = x;
  5213. this.y = y;
  5214. this.width = width;
  5215. this.height = height;
  5216. this.updateProjectionMatrix();
  5217. };
  5218. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5219. if ( this.fullWidth ) {
  5220. var aspect = this.fullWidth / this.fullHeight;
  5221. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5222. var bottom = -top;
  5223. var left = aspect * bottom;
  5224. var right = aspect * top;
  5225. var width = Math.abs( right - left );
  5226. var height = Math.abs( top - bottom );
  5227. this.projectionMatrix.makeFrustum(
  5228. left + this.x * width / this.fullWidth,
  5229. left + ( this.x + this.width ) * width / this.fullWidth,
  5230. top - ( this.y + this.height ) * height / this.fullHeight,
  5231. top - this.y * height / this.fullHeight,
  5232. this.near,
  5233. this.far
  5234. );
  5235. } else {
  5236. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5237. }
  5238. };
  5239. /**
  5240. * @author mrdoob / http://mrdoob.com/
  5241. * @author alteredq / http://alteredqualia.com/
  5242. */
  5243. THREE.Light = function ( hex ) {
  5244. THREE.Object3D.call( this );
  5245. this.color = new THREE.Color( hex );
  5246. };
  5247. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5248. /**
  5249. * @author mrdoob / http://mrdoob.com/
  5250. */
  5251. THREE.AmbientLight = function ( hex ) {
  5252. THREE.Light.call( this, hex );
  5253. };
  5254. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5255. /**
  5256. * @author MPanknin / http://www.redplant.de/
  5257. * @author alteredq / http://alteredqualia.com/
  5258. */
  5259. THREE.AreaLight = function ( hex, intensity ) {
  5260. THREE.Light.call( this, hex );
  5261. this.normal = new THREE.Vector3( 0, -1, 0 );
  5262. this.right = new THREE.Vector3( 1, 0, 0 );
  5263. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5264. this.width = 1.0;
  5265. this.height = 1.0;
  5266. this.constantAttenuation = 1.5;
  5267. this.linearAttenuation = 0.5;
  5268. this.quadraticAttenuation = 0.1;
  5269. };
  5270. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5271. /**
  5272. * @author mrdoob / http://mrdoob.com/
  5273. * @author alteredq / http://alteredqualia.com/
  5274. */
  5275. THREE.DirectionalLight = function ( hex, intensity ) {
  5276. THREE.Light.call( this, hex );
  5277. this.position = new THREE.Vector3( 0, 1, 0 );
  5278. this.target = new THREE.Object3D();
  5279. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5280. this.castShadow = false;
  5281. this.onlyShadow = false;
  5282. //
  5283. this.shadowCameraNear = 50;
  5284. this.shadowCameraFar = 5000;
  5285. this.shadowCameraLeft = -500;
  5286. this.shadowCameraRight = 500;
  5287. this.shadowCameraTop = 500;
  5288. this.shadowCameraBottom = -500;
  5289. this.shadowCameraVisible = false;
  5290. this.shadowBias = 0;
  5291. this.shadowDarkness = 0.5;
  5292. this.shadowMapWidth = 512;
  5293. this.shadowMapHeight = 512;
  5294. //
  5295. this.shadowCascade = false;
  5296. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5297. this.shadowCascadeCount = 2;
  5298. this.shadowCascadeBias = [ 0, 0, 0 ];
  5299. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5300. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5301. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5302. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5303. this.shadowCascadeArray = [];
  5304. //
  5305. this.shadowMap = null;
  5306. this.shadowMapSize = null;
  5307. this.shadowCamera = null;
  5308. this.shadowMatrix = null;
  5309. };
  5310. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5311. /**
  5312. * @author alteredq / http://alteredqualia.com/
  5313. */
  5314. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5315. THREE.Light.call( this, skyColorHex );
  5316. this.groundColor = new THREE.Color( groundColorHex );
  5317. this.position = new THREE.Vector3( 0, 100, 0 );
  5318. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5319. };
  5320. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5321. /**
  5322. * @author mrdoob / http://mrdoob.com/
  5323. */
  5324. THREE.PointLight = function ( hex, intensity, distance ) {
  5325. THREE.Light.call( this, hex );
  5326. this.position = new THREE.Vector3( 0, 0, 0 );
  5327. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5328. this.distance = ( distance !== undefined ) ? distance : 0;
  5329. };
  5330. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5331. /**
  5332. * @author alteredq / http://alteredqualia.com/
  5333. */
  5334. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5335. THREE.Light.call( this, hex );
  5336. this.position = new THREE.Vector3( 0, 1, 0 );
  5337. this.target = new THREE.Object3D();
  5338. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5339. this.distance = ( distance !== undefined ) ? distance : 0;
  5340. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  5341. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5342. this.castShadow = false;
  5343. this.onlyShadow = false;
  5344. //
  5345. this.shadowCameraNear = 50;
  5346. this.shadowCameraFar = 5000;
  5347. this.shadowCameraFov = 50;
  5348. this.shadowCameraVisible = false;
  5349. this.shadowBias = 0;
  5350. this.shadowDarkness = 0.5;
  5351. this.shadowMapWidth = 512;
  5352. this.shadowMapHeight = 512;
  5353. //
  5354. this.shadowMap = null;
  5355. this.shadowMapSize = null;
  5356. this.shadowCamera = null;
  5357. this.shadowMatrix = null;
  5358. };
  5359. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5360. /**
  5361. * @author alteredq / http://alteredqualia.com/
  5362. */
  5363. THREE.Loader = function ( showStatus ) {
  5364. this.showStatus = showStatus;
  5365. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5366. this.onLoadStart = function () {};
  5367. this.onLoadProgress = function () {};
  5368. this.onLoadComplete = function () {};
  5369. };
  5370. THREE.Loader.prototype = {
  5371. constructor: THREE.Loader,
  5372. crossOrigin: 'anonymous',
  5373. addStatusElement: function () {
  5374. var e = document.createElement( "div" );
  5375. e.style.position = "absolute";
  5376. e.style.right = "0px";
  5377. e.style.top = "0px";
  5378. e.style.fontSize = "0.8em";
  5379. e.style.textAlign = "left";
  5380. e.style.background = "rgba(0,0,0,0.25)";
  5381. e.style.color = "#fff";
  5382. e.style.width = "120px";
  5383. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5384. e.style.zIndex = 1000;
  5385. e.innerHTML = "Loading ...";
  5386. return e;
  5387. },
  5388. updateProgress: function ( progress ) {
  5389. var message = "Loaded ";
  5390. if ( progress.total ) {
  5391. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5392. } else {
  5393. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5394. }
  5395. this.statusDomElement.innerHTML = message;
  5396. },
  5397. extractUrlBase: function ( url ) {
  5398. var parts = url.split( '/' );
  5399. parts.pop();
  5400. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5401. },
  5402. initMaterials: function ( materials, texturePath ) {
  5403. var array = [];
  5404. for ( var i = 0; i < materials.length; ++ i ) {
  5405. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5406. }
  5407. return array;
  5408. },
  5409. needsTangents: function ( materials ) {
  5410. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5411. var m = materials[ i ];
  5412. if ( m instanceof THREE.ShaderMaterial ) return true;
  5413. }
  5414. return false;
  5415. },
  5416. createMaterial: function ( m, texturePath ) {
  5417. var _this = this;
  5418. function is_pow2( n ) {
  5419. var l = Math.log( n ) / Math.LN2;
  5420. return Math.floor( l ) == l;
  5421. }
  5422. function nearest_pow2( n ) {
  5423. var l = Math.log( n ) / Math.LN2;
  5424. return Math.pow( 2, Math.round( l ) );
  5425. }
  5426. function load_image( where, url ) {
  5427. var image = new Image();
  5428. image.onload = function () {
  5429. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5430. var width = nearest_pow2( this.width );
  5431. var height = nearest_pow2( this.height );
  5432. where.image.width = width;
  5433. where.image.height = height;
  5434. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5435. } else {
  5436. where.image = this;
  5437. }
  5438. where.needsUpdate = true;
  5439. };
  5440. image.crossOrigin = _this.crossOrigin;
  5441. image.src = url;
  5442. }
  5443. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5444. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  5445. var fullPath = texturePath + "/" + sourceFile;
  5446. if ( isCompressed ) {
  5447. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5448. where[ name ] = texture;
  5449. } else {
  5450. var texture = document.createElement( 'canvas' );
  5451. where[ name ] = new THREE.Texture( texture );
  5452. }
  5453. where[ name ].sourceFile = sourceFile;
  5454. if( repeat ) {
  5455. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5456. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5457. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5458. }
  5459. if ( offset ) {
  5460. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5461. }
  5462. if ( wrap ) {
  5463. var wrapMap = {
  5464. "repeat": THREE.RepeatWrapping,
  5465. "mirror": THREE.MirroredRepeatWrapping
  5466. }
  5467. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5468. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5469. }
  5470. if ( anisotropy ) {
  5471. where[ name ].anisotropy = anisotropy;
  5472. }
  5473. if ( ! isCompressed ) {
  5474. load_image( where[ name ], fullPath );
  5475. }
  5476. }
  5477. function rgb2hex( rgb ) {
  5478. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5479. }
  5480. // defaults
  5481. var mtype = "MeshLambertMaterial";
  5482. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5483. // parameters from model file
  5484. if ( m.shading ) {
  5485. var shading = m.shading.toLowerCase();
  5486. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5487. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5488. }
  5489. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5490. mpars.blending = THREE[ m.blending ];
  5491. }
  5492. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5493. mpars.transparent = m.transparent;
  5494. }
  5495. if ( m.depthTest !== undefined ) {
  5496. mpars.depthTest = m.depthTest;
  5497. }
  5498. if ( m.depthWrite !== undefined ) {
  5499. mpars.depthWrite = m.depthWrite;
  5500. }
  5501. if ( m.visible !== undefined ) {
  5502. mpars.visible = m.visible;
  5503. }
  5504. if ( m.flipSided !== undefined ) {
  5505. mpars.side = THREE.BackSide;
  5506. }
  5507. if ( m.doubleSided !== undefined ) {
  5508. mpars.side = THREE.DoubleSide;
  5509. }
  5510. if ( m.wireframe !== undefined ) {
  5511. mpars.wireframe = m.wireframe;
  5512. }
  5513. if ( m.vertexColors !== undefined ) {
  5514. if ( m.vertexColors === "face" ) {
  5515. mpars.vertexColors = THREE.FaceColors;
  5516. } else if ( m.vertexColors ) {
  5517. mpars.vertexColors = THREE.VertexColors;
  5518. }
  5519. }
  5520. // colors
  5521. if ( m.colorDiffuse ) {
  5522. mpars.color = rgb2hex( m.colorDiffuse );
  5523. } else if ( m.DbgColor ) {
  5524. mpars.color = m.DbgColor;
  5525. }
  5526. if ( m.colorSpecular ) {
  5527. mpars.specular = rgb2hex( m.colorSpecular );
  5528. }
  5529. if ( m.colorAmbient ) {
  5530. mpars.ambient = rgb2hex( m.colorAmbient );
  5531. }
  5532. // modifiers
  5533. if ( m.transparency ) {
  5534. mpars.opacity = m.transparency;
  5535. }
  5536. if ( m.specularCoef ) {
  5537. mpars.shininess = m.specularCoef;
  5538. }
  5539. // textures
  5540. if ( m.mapDiffuse && texturePath ) {
  5541. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5542. }
  5543. if ( m.mapLight && texturePath ) {
  5544. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5545. }
  5546. if ( m.mapBump && texturePath ) {
  5547. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5548. }
  5549. if ( m.mapNormal && texturePath ) {
  5550. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5551. }
  5552. if ( m.mapSpecular && texturePath ) {
  5553. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5554. }
  5555. //
  5556. if ( m.mapBumpScale ) {
  5557. mpars.bumpScale = m.mapBumpScale;
  5558. }
  5559. // special case for normal mapped material
  5560. if ( m.mapNormal ) {
  5561. var shader = THREE.ShaderLib[ "normalmap" ];
  5562. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5563. uniforms[ "tNormal" ].value = mpars.normalMap;
  5564. if ( m.mapNormalFactor ) {
  5565. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5566. }
  5567. if ( mpars.map ) {
  5568. uniforms[ "tDiffuse" ].value = mpars.map;
  5569. uniforms[ "enableDiffuse" ].value = true;
  5570. }
  5571. if ( mpars.specularMap ) {
  5572. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5573. uniforms[ "enableSpecular" ].value = true;
  5574. }
  5575. if ( mpars.lightMap ) {
  5576. uniforms[ "tAO" ].value = mpars.lightMap;
  5577. uniforms[ "enableAO" ].value = true;
  5578. }
  5579. // for the moment don't handle displacement texture
  5580. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5581. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5582. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5583. uniforms[ "uShininess" ].value = mpars.shininess;
  5584. if ( mpars.opacity !== undefined ) {
  5585. uniforms[ "uOpacity" ].value = mpars.opacity;
  5586. }
  5587. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5588. var material = new THREE.ShaderMaterial( parameters );
  5589. if ( mpars.transparent ) {
  5590. material.transparent = true;
  5591. }
  5592. } else {
  5593. var material = new THREE[ mtype ]( mpars );
  5594. }
  5595. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5596. return material;
  5597. }
  5598. };
  5599. /**
  5600. * @author mrdoob / http://mrdoob.com/
  5601. */
  5602. THREE.ImageLoader = function () {
  5603. THREE.EventDispatcher.call( this );
  5604. this.crossOrigin = null;
  5605. };
  5606. THREE.ImageLoader.prototype = {
  5607. constructor: THREE.ImageLoader,
  5608. load: function ( url, image ) {
  5609. var scope = this;
  5610. if ( image === undefined ) image = new Image();
  5611. image.addEventListener( 'load', function () {
  5612. scope.dispatchEvent( { type: 'load', content: image } );
  5613. }, false );
  5614. image.addEventListener( 'error', function () {
  5615. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5616. }, false );
  5617. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5618. image.src = url;
  5619. }
  5620. }
  5621. /**
  5622. * @author mrdoob / http://mrdoob.com/
  5623. * @author alteredq / http://alteredqualia.com/
  5624. */
  5625. THREE.JSONLoader = function ( showStatus ) {
  5626. THREE.Loader.call( this, showStatus );
  5627. this.withCredentials = false;
  5628. };
  5629. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5630. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5631. var scope = this;
  5632. // todo: unify load API to for easier SceneLoader use
  5633. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5634. this.onLoadStart();
  5635. this.loadAjaxJSON( this, url, callback, texturePath );
  5636. };
  5637. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5638. var xhr = new XMLHttpRequest();
  5639. var length = 0;
  5640. xhr.onreadystatechange = function () {
  5641. if ( xhr.readyState === xhr.DONE ) {
  5642. if ( xhr.status === 200 || xhr.status === 0 ) {
  5643. if ( xhr.responseText ) {
  5644. var json = JSON.parse( xhr.responseText );
  5645. context.createModel( json, callback, texturePath );
  5646. } else {
  5647. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5648. }
  5649. // in context of more complex asset initialization
  5650. // do not block on single failed file
  5651. // maybe should go even one more level up
  5652. context.onLoadComplete();
  5653. } else {
  5654. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5655. }
  5656. } else if ( xhr.readyState === xhr.LOADING ) {
  5657. if ( callbackProgress ) {
  5658. if ( length === 0 ) {
  5659. length = xhr.getResponseHeader( "Content-Length" );
  5660. }
  5661. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5662. }
  5663. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5664. length = xhr.getResponseHeader( "Content-Length" );
  5665. }
  5666. };
  5667. xhr.open( "GET", url, true );
  5668. xhr.withCredentials = this.withCredentials;
  5669. xhr.send( null );
  5670. };
  5671. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5672. var scope = this,
  5673. geometry = new THREE.Geometry(),
  5674. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5675. parseModel( scale );
  5676. parseSkin();
  5677. parseMorphing( scale );
  5678. geometry.computeCentroids();
  5679. geometry.computeFaceNormals();
  5680. function parseModel( scale ) {
  5681. function isBitSet( value, position ) {
  5682. return value & ( 1 << position );
  5683. }
  5684. var i, j, fi,
  5685. offset, zLength, nVertices,
  5686. colorIndex, normalIndex, uvIndex, materialIndex,
  5687. type,
  5688. isQuad,
  5689. hasMaterial,
  5690. hasFaceUv, hasFaceVertexUv,
  5691. hasFaceNormal, hasFaceVertexNormal,
  5692. hasFaceColor, hasFaceVertexColor,
  5693. vertex, face, color, normal,
  5694. uvLayer, uvs, u, v,
  5695. faces = json.faces,
  5696. vertices = json.vertices,
  5697. normals = json.normals,
  5698. colors = json.colors,
  5699. nUvLayers = 0;
  5700. // disregard empty arrays
  5701. for ( i = 0; i < json.uvs.length; i++ ) {
  5702. if ( json.uvs[ i ].length ) nUvLayers ++;
  5703. }
  5704. for ( i = 0; i < nUvLayers; i++ ) {
  5705. geometry.faceUvs[ i ] = [];
  5706. geometry.faceVertexUvs[ i ] = [];
  5707. }
  5708. offset = 0;
  5709. zLength = vertices.length;
  5710. while ( offset < zLength ) {
  5711. vertex = new THREE.Vector3();
  5712. vertex.x = vertices[ offset ++ ] * scale;
  5713. vertex.y = vertices[ offset ++ ] * scale;
  5714. vertex.z = vertices[ offset ++ ] * scale;
  5715. geometry.vertices.push( vertex );
  5716. }
  5717. offset = 0;
  5718. zLength = faces.length;
  5719. while ( offset < zLength ) {
  5720. type = faces[ offset ++ ];
  5721. isQuad = isBitSet( type, 0 );
  5722. hasMaterial = isBitSet( type, 1 );
  5723. hasFaceUv = isBitSet( type, 2 );
  5724. hasFaceVertexUv = isBitSet( type, 3 );
  5725. hasFaceNormal = isBitSet( type, 4 );
  5726. hasFaceVertexNormal = isBitSet( type, 5 );
  5727. hasFaceColor = isBitSet( type, 6 );
  5728. hasFaceVertexColor = isBitSet( type, 7 );
  5729. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5730. if ( isQuad ) {
  5731. face = new THREE.Face4();
  5732. face.a = faces[ offset ++ ];
  5733. face.b = faces[ offset ++ ];
  5734. face.c = faces[ offset ++ ];
  5735. face.d = faces[ offset ++ ];
  5736. nVertices = 4;
  5737. } else {
  5738. face = new THREE.Face3();
  5739. face.a = faces[ offset ++ ];
  5740. face.b = faces[ offset ++ ];
  5741. face.c = faces[ offset ++ ];
  5742. nVertices = 3;
  5743. }
  5744. if ( hasMaterial ) {
  5745. materialIndex = faces[ offset ++ ];
  5746. face.materialIndex = materialIndex;
  5747. }
  5748. // to get face <=> uv index correspondence
  5749. fi = geometry.faces.length;
  5750. if ( hasFaceUv ) {
  5751. for ( i = 0; i < nUvLayers; i++ ) {
  5752. uvLayer = json.uvs[ i ];
  5753. uvIndex = faces[ offset ++ ];
  5754. u = uvLayer[ uvIndex * 2 ];
  5755. v = uvLayer[ uvIndex * 2 + 1 ];
  5756. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5757. }
  5758. }
  5759. if ( hasFaceVertexUv ) {
  5760. for ( i = 0; i < nUvLayers; i++ ) {
  5761. uvLayer = json.uvs[ i ];
  5762. uvs = [];
  5763. for ( j = 0; j < nVertices; j ++ ) {
  5764. uvIndex = faces[ offset ++ ];
  5765. u = uvLayer[ uvIndex * 2 ];
  5766. v = uvLayer[ uvIndex * 2 + 1 ];
  5767. uvs[ j ] = new THREE.Vector2( u, v );
  5768. }
  5769. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5770. }
  5771. }
  5772. if ( hasFaceNormal ) {
  5773. normalIndex = faces[ offset ++ ] * 3;
  5774. normal = new THREE.Vector3();
  5775. normal.x = normals[ normalIndex ++ ];
  5776. normal.y = normals[ normalIndex ++ ];
  5777. normal.z = normals[ normalIndex ];
  5778. face.normal = normal;
  5779. }
  5780. if ( hasFaceVertexNormal ) {
  5781. for ( i = 0; i < nVertices; i++ ) {
  5782. normalIndex = faces[ offset ++ ] * 3;
  5783. normal = new THREE.Vector3();
  5784. normal.x = normals[ normalIndex ++ ];
  5785. normal.y = normals[ normalIndex ++ ];
  5786. normal.z = normals[ normalIndex ];
  5787. face.vertexNormals.push( normal );
  5788. }
  5789. }
  5790. if ( hasFaceColor ) {
  5791. colorIndex = faces[ offset ++ ];
  5792. color = new THREE.Color( colors[ colorIndex ] );
  5793. face.color = color;
  5794. }
  5795. if ( hasFaceVertexColor ) {
  5796. for ( i = 0; i < nVertices; i++ ) {
  5797. colorIndex = faces[ offset ++ ];
  5798. color = new THREE.Color( colors[ colorIndex ] );
  5799. face.vertexColors.push( color );
  5800. }
  5801. }
  5802. geometry.faces.push( face );
  5803. }
  5804. };
  5805. function parseSkin() {
  5806. var i, l, x, y, z, w, a, b, c, d;
  5807. if ( json.skinWeights ) {
  5808. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5809. x = json.skinWeights[ i ];
  5810. y = json.skinWeights[ i + 1 ];
  5811. z = 0;
  5812. w = 0;
  5813. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5814. }
  5815. }
  5816. if ( json.skinIndices ) {
  5817. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5818. a = json.skinIndices[ i ];
  5819. b = json.skinIndices[ i + 1 ];
  5820. c = 0;
  5821. d = 0;
  5822. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5823. }
  5824. }
  5825. geometry.bones = json.bones;
  5826. geometry.animation = json.animation;
  5827. };
  5828. function parseMorphing( scale ) {
  5829. if ( json.morphTargets !== undefined ) {
  5830. var i, l, v, vl, dstVertices, srcVertices;
  5831. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5832. geometry.morphTargets[ i ] = {};
  5833. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5834. geometry.morphTargets[ i ].vertices = [];
  5835. dstVertices = geometry.morphTargets[ i ].vertices;
  5836. srcVertices = json.morphTargets [ i ].vertices;
  5837. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5838. var vertex = new THREE.Vector3();
  5839. vertex.x = srcVertices[ v ] * scale;
  5840. vertex.y = srcVertices[ v + 1 ] * scale;
  5841. vertex.z = srcVertices[ v + 2 ] * scale;
  5842. dstVertices.push( vertex );
  5843. }
  5844. }
  5845. }
  5846. if ( json.morphColors !== undefined ) {
  5847. var i, l, c, cl, dstColors, srcColors, color;
  5848. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5849. geometry.morphColors[ i ] = {};
  5850. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5851. geometry.morphColors[ i ].colors = [];
  5852. dstColors = geometry.morphColors[ i ].colors;
  5853. srcColors = json.morphColors [ i ].colors;
  5854. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5855. color = new THREE.Color( 0xffaa00 );
  5856. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5857. dstColors.push( color );
  5858. }
  5859. }
  5860. }
  5861. };
  5862. var materials = this.initMaterials( json.materials, texturePath );
  5863. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5864. callback( geometry, materials );
  5865. };
  5866. /**
  5867. * @author mrdoob / http://mrdoob.com/
  5868. */
  5869. THREE.LoadingMonitor = function () {
  5870. THREE.EventDispatcher.call( this );
  5871. var scope = this;
  5872. var loaded = 0;
  5873. var total = 0;
  5874. var onLoad = function ( event ) {
  5875. loaded ++;
  5876. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5877. if ( loaded === total ) {
  5878. scope.dispatchEvent( { type: 'load' } );
  5879. }
  5880. };
  5881. this.add = function ( loader ) {
  5882. total ++;
  5883. loader.addEventListener( 'load', onLoad, false );
  5884. };
  5885. };
  5886. /**
  5887. * @author alteredq / http://alteredqualia.com/
  5888. */
  5889. THREE.SceneLoader = function () {
  5890. this.onLoadStart = function () {};
  5891. this.onLoadProgress = function() {};
  5892. this.onLoadComplete = function () {};
  5893. this.callbackSync = function () {};
  5894. this.callbackProgress = function () {};
  5895. this.geometryHandlerMap = {};
  5896. this.hierarchyHandlerMap = {};
  5897. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5898. };
  5899. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5900. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5901. var scope = this;
  5902. var xhr = new XMLHttpRequest();
  5903. xhr.onreadystatechange = function () {
  5904. if ( xhr.readyState === 4 ) {
  5905. if ( xhr.status === 200 || xhr.status === 0 ) {
  5906. var json = JSON.parse( xhr.responseText );
  5907. scope.parse( json, callbackFinished, url );
  5908. } else {
  5909. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5910. }
  5911. }
  5912. };
  5913. xhr.open( "GET", url, true );
  5914. xhr.send( null );
  5915. };
  5916. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5917. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5918. };
  5919. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5920. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5921. };
  5922. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5923. var scope = this;
  5924. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5925. var geometry, material, camera, fog,
  5926. texture, images, color,
  5927. light, hex, intensity,
  5928. counter_models, counter_textures,
  5929. total_models, total_textures,
  5930. result;
  5931. var target_array = [];
  5932. var data = json;
  5933. // async geometry loaders
  5934. for ( var typeID in this.geometryHandlerMap ) {
  5935. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5936. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5937. }
  5938. // async hierachy loaders
  5939. for ( var typeID in this.hierarchyHandlerMap ) {
  5940. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5941. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5942. }
  5943. counter_models = 0;
  5944. counter_textures = 0;
  5945. result = {
  5946. scene: new THREE.Scene(),
  5947. geometries: {},
  5948. face_materials: {},
  5949. materials: {},
  5950. textures: {},
  5951. objects: {},
  5952. cameras: {},
  5953. lights: {},
  5954. fogs: {},
  5955. empties: {},
  5956. groups: {}
  5957. };
  5958. if ( data.transform ) {
  5959. var position = data.transform.position,
  5960. rotation = data.transform.rotation,
  5961. scale = data.transform.scale;
  5962. if ( position )
  5963. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5964. if ( rotation )
  5965. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5966. if ( scale )
  5967. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5968. if ( position || rotation || scale ) {
  5969. result.scene.updateMatrix();
  5970. result.scene.updateMatrixWorld();
  5971. }
  5972. }
  5973. function get_url( source_url, url_type ) {
  5974. if ( url_type == "relativeToHTML" ) {
  5975. return source_url;
  5976. } else {
  5977. return urlBase + "/" + source_url;
  5978. }
  5979. };
  5980. // toplevel loader function, delegates to handle_children
  5981. function handle_objects() {
  5982. handle_children( result.scene, data.objects );
  5983. }
  5984. // handle all the children from the loaded json and attach them to given parent
  5985. function handle_children( parent, children ) {
  5986. var mat, dst, pos, rot, scl, quat;
  5987. for ( var objID in children ) {
  5988. // check by id if child has already been handled,
  5989. // if not, create new object
  5990. if ( result.objects[ objID ] === undefined ) {
  5991. var objJSON = children[ objID ];
  5992. var object = null;
  5993. // meshes
  5994. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  5995. if ( objJSON.loading === undefined ) {
  5996. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  5997. "position": 1, "rotation": 1, "scale" : 1,
  5998. "visible": 1, "children": 1, "properties": 1,
  5999. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  6000. var loaderParameters = {};
  6001. for ( var parType in objJSON ) {
  6002. if ( ! ( parType in reservedTypes ) ) {
  6003. loaderParameters[ parType ] = objJSON[ parType ];
  6004. }
  6005. }
  6006. material = result.materials[ objJSON.material ];
  6007. objJSON.loading = true;
  6008. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6009. // ColladaLoader
  6010. if ( loader.options ) {
  6011. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6012. // UTF8Loader
  6013. // OBJLoader
  6014. } else {
  6015. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6016. }
  6017. }
  6018. } else if ( objJSON.geometry !== undefined ) {
  6019. geometry = result.geometries[ objJSON.geometry ];
  6020. // geometry already loaded
  6021. if ( geometry ) {
  6022. var needsTangents = false;
  6023. material = result.materials[ objJSON.material ];
  6024. needsTangents = material instanceof THREE.ShaderMaterial;
  6025. pos = objJSON.position;
  6026. rot = objJSON.rotation;
  6027. scl = objJSON.scale;
  6028. mat = objJSON.matrix;
  6029. quat = objJSON.quaternion;
  6030. // use materials from the model file
  6031. // if there is no material specified in the object
  6032. if ( ! objJSON.material ) {
  6033. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6034. }
  6035. // use materials from the model file
  6036. // if there is just empty face material
  6037. // (must create new material as each model has its own face material)
  6038. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6039. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6040. }
  6041. if ( material instanceof THREE.MeshFaceMaterial ) {
  6042. for ( var i = 0; i < material.materials.length; i ++ ) {
  6043. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6044. }
  6045. }
  6046. if ( needsTangents ) {
  6047. geometry.computeTangents();
  6048. }
  6049. if ( objJSON.skin ) {
  6050. object = new THREE.SkinnedMesh( geometry, material );
  6051. } else if ( objJSON.morph ) {
  6052. object = new THREE.MorphAnimMesh( geometry, material );
  6053. if ( objJSON.duration !== undefined ) {
  6054. object.duration = objJSON.duration;
  6055. }
  6056. if ( objJSON.time !== undefined ) {
  6057. object.time = objJSON.time;
  6058. }
  6059. if ( objJSON.mirroredLoop !== undefined ) {
  6060. object.mirroredLoop = objJSON.mirroredLoop;
  6061. }
  6062. if ( material.morphNormals ) {
  6063. geometry.computeMorphNormals();
  6064. }
  6065. } else {
  6066. object = new THREE.Mesh( geometry, material );
  6067. }
  6068. object.name = objID;
  6069. if ( mat ) {
  6070. object.matrixAutoUpdate = false;
  6071. object.matrix.set(
  6072. mat[0], mat[1], mat[2], mat[3],
  6073. mat[4], mat[5], mat[6], mat[7],
  6074. mat[8], mat[9], mat[10], mat[11],
  6075. mat[12], mat[13], mat[14], mat[15]
  6076. );
  6077. } else {
  6078. object.position.set( pos[0], pos[1], pos[2] );
  6079. if ( quat ) {
  6080. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6081. object.useQuaternion = true;
  6082. } else {
  6083. object.rotation.set( rot[0], rot[1], rot[2] );
  6084. }
  6085. object.scale.set( scl[0], scl[1], scl[2] );
  6086. }
  6087. object.visible = objJSON.visible;
  6088. object.castShadow = objJSON.castShadow;
  6089. object.receiveShadow = objJSON.receiveShadow;
  6090. parent.add( object );
  6091. result.objects[ objID ] = object;
  6092. }
  6093. // lights
  6094. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6095. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6096. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6097. if ( objJSON.type === "DirectionalLight" ) {
  6098. pos = objJSON.direction;
  6099. light = new THREE.DirectionalLight( hex, intensity );
  6100. light.position.set( pos[0], pos[1], pos[2] );
  6101. if ( objJSON.target ) {
  6102. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6103. // kill existing default target
  6104. // otherwise it gets added to scene when parent gets added
  6105. light.target = null;
  6106. }
  6107. } else if ( objJSON.type === "PointLight" ) {
  6108. pos = objJSON.position;
  6109. dst = objJSON.distance;
  6110. light = new THREE.PointLight( hex, intensity, dst );
  6111. light.position.set( pos[0], pos[1], pos[2] );
  6112. } else if ( objJSON.type === "AmbientLight" ) {
  6113. light = new THREE.AmbientLight( hex );
  6114. }
  6115. parent.add( light );
  6116. light.name = objID;
  6117. result.lights[ objID ] = light;
  6118. result.objects[ objID ] = light;
  6119. // cameras
  6120. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6121. if ( objJSON.type === "PerspectiveCamera" ) {
  6122. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6123. } else if ( objJSON.type === "OrthographicCamera" ) {
  6124. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6125. }
  6126. pos = objJSON.position;
  6127. camera.position.set( pos[0], pos[1], pos[2] );
  6128. parent.add( camera );
  6129. camera.name = objID;
  6130. result.cameras[ objID ] = camera;
  6131. result.objects[ objID ] = camera;
  6132. // pure Object3D
  6133. } else {
  6134. pos = objJSON.position;
  6135. rot = objJSON.rotation;
  6136. scl = objJSON.scale;
  6137. quat = objJSON.quaternion;
  6138. object = new THREE.Object3D();
  6139. object.name = objID;
  6140. object.position.set( pos[0], pos[1], pos[2] );
  6141. if ( quat ) {
  6142. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6143. object.useQuaternion = true;
  6144. } else {
  6145. object.rotation.set( rot[0], rot[1], rot[2] );
  6146. }
  6147. object.scale.set( scl[0], scl[1], scl[2] );
  6148. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6149. parent.add( object );
  6150. result.objects[ objID ] = object;
  6151. result.empties[ objID ] = object;
  6152. }
  6153. if ( object ) {
  6154. if ( objJSON.properties !== undefined ) {
  6155. for ( var key in objJSON.properties ) {
  6156. var value = objJSON.properties[ key ];
  6157. object.properties[ key ] = value;
  6158. }
  6159. }
  6160. if ( objJSON.groups !== undefined ) {
  6161. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6162. var groupID = objJSON.groups[ i ];
  6163. if ( result.groups[ groupID ] === undefined ) {
  6164. result.groups[ groupID ] = [];
  6165. }
  6166. result.groups[ groupID ].push( objID );
  6167. }
  6168. }
  6169. if ( objJSON.children !== undefined ) {
  6170. handle_children( object, objJSON.children );
  6171. }
  6172. }
  6173. }
  6174. }
  6175. };
  6176. function handle_mesh( geo, mat, id ) {
  6177. result.geometries[ id ] = geo;
  6178. result.face_materials[ id ] = mat;
  6179. handle_objects();
  6180. };
  6181. function handle_hierarchy( node, id, parent, material, obj ) {
  6182. var p = obj.position;
  6183. var r = obj.rotation;
  6184. var q = obj.quaternion;
  6185. var s = obj.scale;
  6186. node.position.set( p[0], p[1], p[2] );
  6187. if ( q ) {
  6188. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6189. node.useQuaternion = true;
  6190. } else {
  6191. node.rotation.set( r[0], r[1], r[2] );
  6192. }
  6193. node.scale.set( s[0], s[1], s[2] );
  6194. // override children materials
  6195. // if object material was specified in JSON explicitly
  6196. if ( material ) {
  6197. node.traverse( function ( child ) {
  6198. child.material = material;
  6199. } );
  6200. }
  6201. // override children visibility
  6202. // with root node visibility as specified in JSON
  6203. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6204. node.traverse( function ( child ) {
  6205. child.visible = visible;
  6206. } );
  6207. parent.add( node );
  6208. node.name = id;
  6209. result.objects[ id ] = node;
  6210. handle_objects();
  6211. };
  6212. function create_callback_geometry( id ) {
  6213. return function( geo, mat ) {
  6214. handle_mesh( geo, mat, id );
  6215. counter_models -= 1;
  6216. scope.onLoadComplete();
  6217. async_callback_gate();
  6218. }
  6219. };
  6220. function create_callback_hierachy( id, parent, material, obj ) {
  6221. return function( event ) {
  6222. var result;
  6223. // loaders which use EventDispatcher
  6224. if ( event.content ) {
  6225. result = event.content;
  6226. // ColladaLoader
  6227. } else if ( event.dae ) {
  6228. result = event.scene;
  6229. // UTF8Loader
  6230. } else {
  6231. result = event;
  6232. }
  6233. handle_hierarchy( result, id, parent, material, obj );
  6234. counter_models -= 1;
  6235. scope.onLoadComplete();
  6236. async_callback_gate();
  6237. }
  6238. };
  6239. function create_callback_embed( id ) {
  6240. return function( geo, mat ) {
  6241. result.geometries[ id ] = geo;
  6242. result.face_materials[ id ] = mat;
  6243. }
  6244. };
  6245. function async_callback_gate() {
  6246. var progress = {
  6247. totalModels : total_models,
  6248. totalTextures : total_textures,
  6249. loadedModels : total_models - counter_models,
  6250. loadedTextures : total_textures - counter_textures
  6251. };
  6252. scope.callbackProgress( progress, result );
  6253. scope.onLoadProgress();
  6254. if ( counter_models === 0 && counter_textures === 0 ) {
  6255. finalize();
  6256. callbackFinished( result );
  6257. }
  6258. };
  6259. function finalize() {
  6260. // take care of targets which could be asynchronously loaded objects
  6261. for ( var i = 0; i < target_array.length; i ++ ) {
  6262. var ta = target_array[ i ];
  6263. var target = result.objects[ ta.targetName ];
  6264. if ( target ) {
  6265. ta.object.target = target;
  6266. } else {
  6267. // if there was error and target of specified name doesn't exist in the scene file
  6268. // create instead dummy target
  6269. // (target must be added to scene explicitly as parent is already added)
  6270. ta.object.target = new THREE.Object3D();
  6271. result.scene.add( ta.object.target );
  6272. }
  6273. ta.object.target.properties.targetInverse = ta.object;
  6274. }
  6275. };
  6276. var callbackTexture = function ( count ) {
  6277. counter_textures -= count;
  6278. async_callback_gate();
  6279. scope.onLoadComplete();
  6280. };
  6281. // must use this instead of just directly calling callbackTexture
  6282. // because of closure in the calling context loop
  6283. var generateTextureCallback = function ( count ) {
  6284. return function() {
  6285. callbackTexture( count );
  6286. };
  6287. };
  6288. // first go synchronous elements
  6289. // fogs
  6290. var fogID, fogJSON;
  6291. for ( fogID in data.fogs ) {
  6292. fogJSON = data.fogs[ fogID ];
  6293. if ( fogJSON.type === "linear" ) {
  6294. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6295. } else if ( fogJSON.type === "exp2" ) {
  6296. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6297. }
  6298. color = fogJSON.color;
  6299. fog.color.setRGB( color[0], color[1], color[2] );
  6300. result.fogs[ fogID ] = fog;
  6301. }
  6302. // now come potentially asynchronous elements
  6303. // geometries
  6304. // count how many geometries will be loaded asynchronously
  6305. var geoID, geoJSON;
  6306. for ( geoID in data.geometries ) {
  6307. geoJSON = data.geometries[ geoID ];
  6308. if ( geoJSON.type in this.geometryHandlerMap ) {
  6309. counter_models += 1;
  6310. scope.onLoadStart();
  6311. }
  6312. }
  6313. // count how many hierarchies will be loaded asynchronously
  6314. var objID, objJSON;
  6315. for ( objID in data.objects ) {
  6316. objJSON = data.objects[ objID ];
  6317. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6318. counter_models += 1;
  6319. scope.onLoadStart();
  6320. }
  6321. }
  6322. total_models = counter_models;
  6323. for ( geoID in data.geometries ) {
  6324. geoJSON = data.geometries[ geoID ];
  6325. if ( geoJSON.type === "cube" ) {
  6326. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6327. result.geometries[ geoID ] = geometry;
  6328. } else if ( geoJSON.type === "plane" ) {
  6329. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6330. result.geometries[ geoID ] = geometry;
  6331. } else if ( geoJSON.type === "sphere" ) {
  6332. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6333. result.geometries[ geoID ] = geometry;
  6334. } else if ( geoJSON.type === "cylinder" ) {
  6335. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6336. result.geometries[ geoID ] = geometry;
  6337. } else if ( geoJSON.type === "torus" ) {
  6338. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6339. result.geometries[ geoID ] = geometry;
  6340. } else if ( geoJSON.type === "icosahedron" ) {
  6341. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6342. result.geometries[ geoID ] = geometry;
  6343. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6344. var loaderParameters = {};
  6345. for ( var parType in geoJSON ) {
  6346. if ( parType !== "type" && parType !== "url" ) {
  6347. loaderParameters[ parType ] = geoJSON[ parType ];
  6348. }
  6349. }
  6350. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6351. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6352. } else if ( geoJSON.type === "embedded" ) {
  6353. var modelJson = data.embeds[ geoJSON.id ],
  6354. texture_path = "";
  6355. // pass metadata along to jsonLoader so it knows the format version
  6356. modelJson.metadata = data.metadata;
  6357. if ( modelJson ) {
  6358. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6359. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6360. }
  6361. }
  6362. }
  6363. // textures
  6364. // count how many textures will be loaded asynchronously
  6365. var textureID, textureJSON;
  6366. for ( textureID in data.textures ) {
  6367. textureJSON = data.textures[ textureID ];
  6368. if ( textureJSON.url instanceof Array ) {
  6369. counter_textures += textureJSON.url.length;
  6370. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6371. scope.onLoadStart();
  6372. }
  6373. } else {
  6374. counter_textures += 1;
  6375. scope.onLoadStart();
  6376. }
  6377. }
  6378. total_textures = counter_textures;
  6379. for ( textureID in data.textures ) {
  6380. textureJSON = data.textures[ textureID ];
  6381. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6382. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6383. }
  6384. if ( textureJSON.url instanceof Array ) {
  6385. var count = textureJSON.url.length;
  6386. var url_array = [];
  6387. for( var i = 0; i < count; i ++ ) {
  6388. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6389. }
  6390. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6391. if ( isCompressed ) {
  6392. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6393. } else {
  6394. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6395. }
  6396. } else {
  6397. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  6398. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6399. var textureCallback = generateTextureCallback( 1 );
  6400. if ( isCompressed ) {
  6401. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6402. } else {
  6403. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6404. }
  6405. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6406. texture.minFilter = THREE[ textureJSON.minFilter ];
  6407. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6408. texture.magFilter = THREE[ textureJSON.magFilter ];
  6409. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6410. if ( textureJSON.repeat ) {
  6411. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6412. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6413. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6414. }
  6415. if ( textureJSON.offset ) {
  6416. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6417. }
  6418. // handle wrap after repeat so that default repeat can be overriden
  6419. if ( textureJSON.wrap ) {
  6420. var wrapMap = {
  6421. "repeat" : THREE.RepeatWrapping,
  6422. "mirror" : THREE.MirroredRepeatWrapping
  6423. }
  6424. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6425. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6426. }
  6427. }
  6428. result.textures[ textureID ] = texture;
  6429. }
  6430. // materials
  6431. var matID, matJSON;
  6432. var parID;
  6433. for ( matID in data.materials ) {
  6434. matJSON = data.materials[ matID ];
  6435. for ( parID in matJSON.parameters ) {
  6436. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6437. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6438. } else if ( parID === "shading" ) {
  6439. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6440. } else if ( parID === "side" ) {
  6441. if ( matJSON.parameters[ parID ] == "double" ) {
  6442. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6443. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6444. matJSON.parameters[ parID ] = THREE.BackSide;
  6445. } else {
  6446. matJSON.parameters[ parID ] = THREE.FrontSide;
  6447. }
  6448. } else if ( parID === "blending" ) {
  6449. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6450. } else if ( parID === "combine" ) {
  6451. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6452. } else if ( parID === "vertexColors" ) {
  6453. if ( matJSON.parameters[ parID ] == "face" ) {
  6454. matJSON.parameters[ parID ] = THREE.FaceColors;
  6455. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6456. } else if ( matJSON.parameters[ parID ] ) {
  6457. matJSON.parameters[ parID ] = THREE.VertexColors;
  6458. }
  6459. } else if ( parID === "wrapRGB" ) {
  6460. var v3 = matJSON.parameters[ parID ];
  6461. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6462. }
  6463. }
  6464. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6465. matJSON.parameters.transparent = true;
  6466. }
  6467. if ( matJSON.parameters.normalMap ) {
  6468. var shader = THREE.ShaderLib[ "normalmap" ];
  6469. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6470. var diffuse = matJSON.parameters.color;
  6471. var specular = matJSON.parameters.specular;
  6472. var ambient = matJSON.parameters.ambient;
  6473. var shininess = matJSON.parameters.shininess;
  6474. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6475. if ( matJSON.parameters.normalScale ) {
  6476. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6477. }
  6478. if ( matJSON.parameters.map ) {
  6479. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6480. uniforms[ "enableDiffuse" ].value = true;
  6481. }
  6482. if ( matJSON.parameters.envMap ) {
  6483. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6484. uniforms[ "enableReflection" ].value = true;
  6485. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6486. }
  6487. if ( matJSON.parameters.lightMap ) {
  6488. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6489. uniforms[ "enableAO" ].value = true;
  6490. }
  6491. if ( matJSON.parameters.specularMap ) {
  6492. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6493. uniforms[ "enableSpecular" ].value = true;
  6494. }
  6495. if ( matJSON.parameters.displacementMap ) {
  6496. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6497. uniforms[ "enableDisplacement" ].value = true;
  6498. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6499. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6500. }
  6501. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6502. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6503. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6504. uniforms[ "uShininess" ].value = shininess;
  6505. if ( matJSON.parameters.opacity ) {
  6506. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6507. }
  6508. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6509. material = new THREE.ShaderMaterial( parameters );
  6510. } else {
  6511. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6512. }
  6513. result.materials[ matID ] = material;
  6514. }
  6515. // second pass through all materials to initialize MeshFaceMaterials
  6516. // that could be referring to other materials out of order
  6517. for ( matID in data.materials ) {
  6518. matJSON = data.materials[ matID ];
  6519. if ( matJSON.parameters.materials ) {
  6520. var materialArray = [];
  6521. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6522. var label = matJSON.parameters.materials[ i ];
  6523. materialArray.push( result.materials[ label ] );
  6524. }
  6525. result.materials[ matID ].materials = materialArray;
  6526. }
  6527. }
  6528. // objects ( synchronous init of procedural primitives )
  6529. handle_objects();
  6530. // defaults
  6531. if ( result.cameras && data.defaults.camera ) {
  6532. result.currentCamera = result.cameras[ data.defaults.camera ];
  6533. }
  6534. if ( result.fogs && data.defaults.fog ) {
  6535. result.scene.fog = result.fogs[ data.defaults.fog ];
  6536. }
  6537. // synchronous callback
  6538. scope.callbackSync( result );
  6539. // just in case there are no async elements
  6540. async_callback_gate();
  6541. };
  6542. /**
  6543. * @author mrdoob / http://mrdoob.com/
  6544. */
  6545. THREE.TextureLoader = function () {
  6546. THREE.EventDispatcher.call( this );
  6547. this.crossOrigin = null;
  6548. };
  6549. THREE.TextureLoader.prototype = {
  6550. constructor: THREE.TextureLoader,
  6551. load: function ( url ) {
  6552. var scope = this;
  6553. var image = new Image();
  6554. image.addEventListener( 'load', function () {
  6555. var texture = new THREE.Texture( image );
  6556. texture.needsUpdate = true;
  6557. scope.dispatchEvent( { type: 'load', content: texture } );
  6558. }, false );
  6559. image.addEventListener( 'error', function () {
  6560. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6561. }, false );
  6562. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6563. image.src = url;
  6564. }
  6565. }
  6566. /**
  6567. * @author mrdoob / http://mrdoob.com/
  6568. * @author alteredq / http://alteredqualia.com/
  6569. */
  6570. THREE.Material = function () {
  6571. THREE.EventDispatcher.call( this );
  6572. this.id = THREE.MaterialIdCount ++;
  6573. this.name = '';
  6574. this.side = THREE.FrontSide;
  6575. this.opacity = 1;
  6576. this.transparent = false;
  6577. this.blending = THREE.NormalBlending;
  6578. this.blendSrc = THREE.SrcAlphaFactor;
  6579. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6580. this.blendEquation = THREE.AddEquation;
  6581. this.depthTest = true;
  6582. this.depthWrite = true;
  6583. this.polygonOffset = false;
  6584. this.polygonOffsetFactor = 0;
  6585. this.polygonOffsetUnits = 0;
  6586. this.alphaTest = 0;
  6587. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6588. this.visible = true;
  6589. this.needsUpdate = true;
  6590. };
  6591. THREE.Material.prototype.setValues = function ( values ) {
  6592. if ( values === undefined ) return;
  6593. for ( var key in values ) {
  6594. var newValue = values[ key ];
  6595. if ( newValue === undefined ) {
  6596. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6597. continue;
  6598. }
  6599. if ( key in this ) {
  6600. var currentValue = this[ key ];
  6601. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6602. currentValue.copy( newValue );
  6603. } else if ( currentValue instanceof THREE.Color ) {
  6604. currentValue.set( newValue );
  6605. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6606. currentValue.copy( newValue );
  6607. } else {
  6608. this[ key ] = newValue;
  6609. }
  6610. }
  6611. }
  6612. };
  6613. THREE.Material.prototype.clone = function ( material ) {
  6614. if ( material === undefined ) material = new THREE.Material();
  6615. material.name = this.name;
  6616. material.side = this.side;
  6617. material.opacity = this.opacity;
  6618. material.transparent = this.transparent;
  6619. material.blending = this.blending;
  6620. material.blendSrc = this.blendSrc;
  6621. material.blendDst = this.blendDst;
  6622. material.blendEquation = this.blendEquation;
  6623. material.depthTest = this.depthTest;
  6624. material.depthWrite = this.depthWrite;
  6625. material.polygonOffset = this.polygonOffset;
  6626. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6627. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6628. material.alphaTest = this.alphaTest;
  6629. material.overdraw = this.overdraw;
  6630. material.visible = this.visible;
  6631. return material;
  6632. };
  6633. THREE.Material.prototype.dispose = function () {
  6634. this.dispatchEvent( { type: 'dispose' } );
  6635. };
  6636. THREE.MaterialIdCount = 0;
  6637. /**
  6638. * @author mrdoob / http://mrdoob.com/
  6639. * @author alteredq / http://alteredqualia.com/
  6640. *
  6641. * parameters = {
  6642. * color: <hex>,
  6643. * opacity: <float>,
  6644. *
  6645. * blending: THREE.NormalBlending,
  6646. * depthTest: <bool>,
  6647. * depthWrite: <bool>,
  6648. *
  6649. * linewidth: <float>,
  6650. * linecap: "round",
  6651. * linejoin: "round",
  6652. *
  6653. * vertexColors: <bool>
  6654. *
  6655. * fog: <bool>
  6656. * }
  6657. */
  6658. THREE.LineBasicMaterial = function ( parameters ) {
  6659. THREE.Material.call( this );
  6660. this.color = new THREE.Color( 0xffffff );
  6661. this.linewidth = 1;
  6662. this.linecap = 'round';
  6663. this.linejoin = 'round';
  6664. this.vertexColors = false;
  6665. this.fog = true;
  6666. this.setValues( parameters );
  6667. };
  6668. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6669. THREE.LineBasicMaterial.prototype.clone = function () {
  6670. var material = new THREE.LineBasicMaterial();
  6671. THREE.Material.prototype.clone.call( this, material );
  6672. material.color.copy( this.color );
  6673. material.linewidth = this.linewidth;
  6674. material.linecap = this.linecap;
  6675. material.linejoin = this.linejoin;
  6676. material.vertexColors = this.vertexColors;
  6677. material.fog = this.fog;
  6678. return material;
  6679. };
  6680. /**
  6681. * @author alteredq / http://alteredqualia.com/
  6682. *
  6683. * parameters = {
  6684. * color: <hex>,
  6685. * opacity: <float>,
  6686. *
  6687. * blending: THREE.NormalBlending,
  6688. * depthTest: <bool>,
  6689. * depthWrite: <bool>,
  6690. *
  6691. * linewidth: <float>,
  6692. *
  6693. * scale: <float>,
  6694. * dashSize: <float>,
  6695. * gapSize: <float>,
  6696. *
  6697. * vertexColors: <bool>
  6698. *
  6699. * fog: <bool>
  6700. * }
  6701. */
  6702. THREE.LineDashedMaterial = function ( parameters ) {
  6703. THREE.Material.call( this );
  6704. this.color = new THREE.Color( 0xffffff );
  6705. this.linewidth = 1;
  6706. this.scale = 1;
  6707. this.dashSize = 3;
  6708. this.gapSize = 1;
  6709. this.vertexColors = false;
  6710. this.fog = true;
  6711. this.setValues( parameters );
  6712. };
  6713. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6714. THREE.LineDashedMaterial.prototype.clone = function () {
  6715. var material = new THREE.LineDashedMaterial();
  6716. THREE.Material.prototype.clone.call( this, material );
  6717. material.color.copy( this.color );
  6718. material.linewidth = this.linewidth;
  6719. material.scale = this.scale;
  6720. material.dashSize = this.dashSize;
  6721. material.gapSize = this.gapSize;
  6722. material.vertexColors = this.vertexColors;
  6723. material.fog = this.fog;
  6724. return material;
  6725. };
  6726. /**
  6727. * @author mrdoob / http://mrdoob.com/
  6728. * @author alteredq / http://alteredqualia.com/
  6729. *
  6730. * parameters = {
  6731. * color: <hex>,
  6732. * opacity: <float>,
  6733. * map: new THREE.Texture( <Image> ),
  6734. *
  6735. * lightMap: new THREE.Texture( <Image> ),
  6736. *
  6737. * specularMap: new THREE.Texture( <Image> ),
  6738. *
  6739. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6740. * combine: THREE.Multiply,
  6741. * reflectivity: <float>,
  6742. * refractionRatio: <float>,
  6743. *
  6744. * shading: THREE.SmoothShading,
  6745. * blending: THREE.NormalBlending,
  6746. * depthTest: <bool>,
  6747. * depthWrite: <bool>,
  6748. *
  6749. * wireframe: <boolean>,
  6750. * wireframeLinewidth: <float>,
  6751. *
  6752. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6753. *
  6754. * skinning: <bool>,
  6755. * morphTargets: <bool>,
  6756. *
  6757. * fog: <bool>
  6758. * }
  6759. */
  6760. THREE.MeshBasicMaterial = function ( parameters ) {
  6761. THREE.Material.call( this );
  6762. this.color = new THREE.Color( 0xffffff ); // emissive
  6763. this.map = null;
  6764. this.lightMap = null;
  6765. this.specularMap = null;
  6766. this.envMap = null;
  6767. this.combine = THREE.MultiplyOperation;
  6768. this.reflectivity = 1;
  6769. this.refractionRatio = 0.98;
  6770. this.fog = true;
  6771. this.shading = THREE.SmoothShading;
  6772. this.wireframe = false;
  6773. this.wireframeLinewidth = 1;
  6774. this.wireframeLinecap = 'round';
  6775. this.wireframeLinejoin = 'round';
  6776. this.vertexColors = THREE.NoColors;
  6777. this.skinning = false;
  6778. this.morphTargets = false;
  6779. this.setValues( parameters );
  6780. };
  6781. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6782. THREE.MeshBasicMaterial.prototype.clone = function () {
  6783. var material = new THREE.MeshBasicMaterial();
  6784. THREE.Material.prototype.clone.call( this, material );
  6785. material.color.copy( this.color );
  6786. material.map = this.map;
  6787. material.lightMap = this.lightMap;
  6788. material.specularMap = this.specularMap;
  6789. material.envMap = this.envMap;
  6790. material.combine = this.combine;
  6791. material.reflectivity = this.reflectivity;
  6792. material.refractionRatio = this.refractionRatio;
  6793. material.fog = this.fog;
  6794. material.shading = this.shading;
  6795. material.wireframe = this.wireframe;
  6796. material.wireframeLinewidth = this.wireframeLinewidth;
  6797. material.wireframeLinecap = this.wireframeLinecap;
  6798. material.wireframeLinejoin = this.wireframeLinejoin;
  6799. material.vertexColors = this.vertexColors;
  6800. material.skinning = this.skinning;
  6801. material.morphTargets = this.morphTargets;
  6802. return material;
  6803. };
  6804. /**
  6805. * @author mrdoob / http://mrdoob.com/
  6806. * @author alteredq / http://alteredqualia.com/
  6807. *
  6808. * parameters = {
  6809. * color: <hex>,
  6810. * ambient: <hex>,
  6811. * emissive: <hex>,
  6812. * opacity: <float>,
  6813. *
  6814. * map: new THREE.Texture( <Image> ),
  6815. *
  6816. * lightMap: new THREE.Texture( <Image> ),
  6817. *
  6818. * specularMap: new THREE.Texture( <Image> ),
  6819. *
  6820. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6821. * combine: THREE.Multiply,
  6822. * reflectivity: <float>,
  6823. * refractionRatio: <float>,
  6824. *
  6825. * shading: THREE.SmoothShading,
  6826. * blending: THREE.NormalBlending,
  6827. * depthTest: <bool>,
  6828. * depthWrite: <bool>,
  6829. *
  6830. * wireframe: <boolean>,
  6831. * wireframeLinewidth: <float>,
  6832. *
  6833. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6834. *
  6835. * skinning: <bool>,
  6836. * morphTargets: <bool>,
  6837. * morphNormals: <bool>,
  6838. *
  6839. * fog: <bool>
  6840. * }
  6841. */
  6842. THREE.MeshLambertMaterial = function ( parameters ) {
  6843. THREE.Material.call( this );
  6844. this.color = new THREE.Color( 0xffffff ); // diffuse
  6845. this.ambient = new THREE.Color( 0xffffff );
  6846. this.emissive = new THREE.Color( 0x000000 );
  6847. this.wrapAround = false;
  6848. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6849. this.map = null;
  6850. this.lightMap = null;
  6851. this.specularMap = null;
  6852. this.envMap = null;
  6853. this.combine = THREE.MultiplyOperation;
  6854. this.reflectivity = 1;
  6855. this.refractionRatio = 0.98;
  6856. this.fog = true;
  6857. this.shading = THREE.SmoothShading;
  6858. this.wireframe = false;
  6859. this.wireframeLinewidth = 1;
  6860. this.wireframeLinecap = 'round';
  6861. this.wireframeLinejoin = 'round';
  6862. this.vertexColors = THREE.NoColors;
  6863. this.skinning = false;
  6864. this.morphTargets = false;
  6865. this.morphNormals = false;
  6866. this.setValues( parameters );
  6867. };
  6868. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6869. THREE.MeshLambertMaterial.prototype.clone = function () {
  6870. var material = new THREE.MeshLambertMaterial();
  6871. THREE.Material.prototype.clone.call( this, material );
  6872. material.color.copy( this.color );
  6873. material.ambient.copy( this.ambient );
  6874. material.emissive.copy( this.emissive );
  6875. material.wrapAround = this.wrapAround;
  6876. material.wrapRGB.copy( this.wrapRGB );
  6877. material.map = this.map;
  6878. material.lightMap = this.lightMap;
  6879. material.specularMap = this.specularMap;
  6880. material.envMap = this.envMap;
  6881. material.combine = this.combine;
  6882. material.reflectivity = this.reflectivity;
  6883. material.refractionRatio = this.refractionRatio;
  6884. material.fog = this.fog;
  6885. material.shading = this.shading;
  6886. material.wireframe = this.wireframe;
  6887. material.wireframeLinewidth = this.wireframeLinewidth;
  6888. material.wireframeLinecap = this.wireframeLinecap;
  6889. material.wireframeLinejoin = this.wireframeLinejoin;
  6890. material.vertexColors = this.vertexColors;
  6891. material.skinning = this.skinning;
  6892. material.morphTargets = this.morphTargets;
  6893. material.morphNormals = this.morphNormals;
  6894. return material;
  6895. };
  6896. /**
  6897. * @author mrdoob / http://mrdoob.com/
  6898. * @author alteredq / http://alteredqualia.com/
  6899. *
  6900. * parameters = {
  6901. * color: <hex>,
  6902. * ambient: <hex>,
  6903. * emissive: <hex>,
  6904. * specular: <hex>,
  6905. * shininess: <float>,
  6906. * opacity: <float>,
  6907. *
  6908. * map: new THREE.Texture( <Image> ),
  6909. *
  6910. * lightMap: new THREE.Texture( <Image> ),
  6911. *
  6912. * bumpMap: new THREE.Texture( <Image> ),
  6913. * bumpScale: <float>,
  6914. *
  6915. * normalMap: new THREE.Texture( <Image> ),
  6916. * normalScale: <Vector2>,
  6917. *
  6918. * specularMap: new THREE.Texture( <Image> ),
  6919. *
  6920. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6921. * combine: THREE.Multiply,
  6922. * reflectivity: <float>,
  6923. * refractionRatio: <float>,
  6924. *
  6925. * shading: THREE.SmoothShading,
  6926. * blending: THREE.NormalBlending,
  6927. * depthTest: <bool>,
  6928. * depthWrite: <bool>,
  6929. *
  6930. * wireframe: <boolean>,
  6931. * wireframeLinewidth: <float>,
  6932. *
  6933. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6934. *
  6935. * skinning: <bool>,
  6936. * morphTargets: <bool>,
  6937. * morphNormals: <bool>,
  6938. *
  6939. * fog: <bool>
  6940. * }
  6941. */
  6942. THREE.MeshPhongMaterial = function ( parameters ) {
  6943. THREE.Material.call( this );
  6944. this.color = new THREE.Color( 0xffffff ); // diffuse
  6945. this.ambient = new THREE.Color( 0xffffff );
  6946. this.emissive = new THREE.Color( 0x000000 );
  6947. this.specular = new THREE.Color( 0x111111 );
  6948. this.shininess = 30;
  6949. this.metal = false;
  6950. this.perPixel = true;
  6951. this.wrapAround = false;
  6952. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6953. this.map = null;
  6954. this.lightMap = null;
  6955. this.bumpMap = null;
  6956. this.bumpScale = 1;
  6957. this.normalMap = null;
  6958. this.normalScale = new THREE.Vector2( 1, 1 );
  6959. this.specularMap = null;
  6960. this.envMap = null;
  6961. this.combine = THREE.MultiplyOperation;
  6962. this.reflectivity = 1;
  6963. this.refractionRatio = 0.98;
  6964. this.fog = true;
  6965. this.shading = THREE.SmoothShading;
  6966. this.wireframe = false;
  6967. this.wireframeLinewidth = 1;
  6968. this.wireframeLinecap = 'round';
  6969. this.wireframeLinejoin = 'round';
  6970. this.vertexColors = THREE.NoColors;
  6971. this.skinning = false;
  6972. this.morphTargets = false;
  6973. this.morphNormals = false;
  6974. this.setValues( parameters );
  6975. };
  6976. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6977. THREE.MeshPhongMaterial.prototype.clone = function () {
  6978. var material = new THREE.MeshPhongMaterial();
  6979. THREE.Material.prototype.clone.call( this, material );
  6980. material.color.copy( this.color );
  6981. material.ambient.copy( this.ambient );
  6982. material.emissive.copy( this.emissive );
  6983. material.specular.copy( this.specular );
  6984. material.shininess = this.shininess;
  6985. material.metal = this.metal;
  6986. material.perPixel = this.perPixel;
  6987. material.wrapAround = this.wrapAround;
  6988. material.wrapRGB.copy( this.wrapRGB );
  6989. material.map = this.map;
  6990. material.lightMap = this.lightMap;
  6991. material.bumpMap = this.bumpMap;
  6992. material.bumpScale = this.bumpScale;
  6993. material.normalMap = this.normalMap;
  6994. material.normalScale.copy( this.normalScale );
  6995. material.specularMap = this.specularMap;
  6996. material.envMap = this.envMap;
  6997. material.combine = this.combine;
  6998. material.reflectivity = this.reflectivity;
  6999. material.refractionRatio = this.refractionRatio;
  7000. material.fog = this.fog;
  7001. material.shading = this.shading;
  7002. material.wireframe = this.wireframe;
  7003. material.wireframeLinewidth = this.wireframeLinewidth;
  7004. material.wireframeLinecap = this.wireframeLinecap;
  7005. material.wireframeLinejoin = this.wireframeLinejoin;
  7006. material.vertexColors = this.vertexColors;
  7007. material.skinning = this.skinning;
  7008. material.morphTargets = this.morphTargets;
  7009. material.morphNormals = this.morphNormals;
  7010. return material;
  7011. };
  7012. /**
  7013. * @author mrdoob / http://mrdoob.com/
  7014. * @author alteredq / http://alteredqualia.com/
  7015. *
  7016. * parameters = {
  7017. * opacity: <float>,
  7018. *
  7019. * blending: THREE.NormalBlending,
  7020. * depthTest: <bool>,
  7021. * depthWrite: <bool>,
  7022. *
  7023. * wireframe: <boolean>,
  7024. * wireframeLinewidth: <float>
  7025. * }
  7026. */
  7027. THREE.MeshDepthMaterial = function ( parameters ) {
  7028. THREE.Material.call( this );
  7029. this.wireframe = false;
  7030. this.wireframeLinewidth = 1;
  7031. this.setValues( parameters );
  7032. };
  7033. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7034. THREE.MeshDepthMaterial.prototype.clone = function () {
  7035. var material = new THREE.LineBasicMaterial();
  7036. THREE.Material.prototype.clone.call( this, material );
  7037. material.wireframe = this.wireframe;
  7038. material.wireframeLinewidth = this.wireframeLinewidth;
  7039. return material;
  7040. };
  7041. /**
  7042. * @author mrdoob / http://mrdoob.com/
  7043. *
  7044. * parameters = {
  7045. * opacity: <float>,
  7046. *
  7047. * shading: THREE.FlatShading,
  7048. * blending: THREE.NormalBlending,
  7049. * depthTest: <bool>,
  7050. * depthWrite: <bool>,
  7051. *
  7052. * wireframe: <boolean>,
  7053. * wireframeLinewidth: <float>
  7054. * }
  7055. */
  7056. THREE.MeshNormalMaterial = function ( parameters ) {
  7057. THREE.Material.call( this, parameters );
  7058. this.shading = THREE.FlatShading;
  7059. this.wireframe = false;
  7060. this.wireframeLinewidth = 1;
  7061. this.setValues( parameters );
  7062. };
  7063. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7064. THREE.MeshNormalMaterial.prototype.clone = function () {
  7065. var material = new THREE.MeshNormalMaterial();
  7066. THREE.Material.prototype.clone.call( this, material );
  7067. material.shading = this.shading;
  7068. material.wireframe = this.wireframe;
  7069. material.wireframeLinewidth = this.wireframeLinewidth;
  7070. return material;
  7071. };
  7072. /**
  7073. * @author mrdoob / http://mrdoob.com/
  7074. */
  7075. THREE.MeshFaceMaterial = function ( materials ) {
  7076. this.materials = materials instanceof Array ? materials : [];
  7077. };
  7078. THREE.MeshFaceMaterial.prototype.clone = function () {
  7079. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7080. };
  7081. /**
  7082. * @author mrdoob / http://mrdoob.com/
  7083. * @author alteredq / http://alteredqualia.com/
  7084. *
  7085. * parameters = {
  7086. * color: <hex>,
  7087. * opacity: <float>,
  7088. * map: new THREE.Texture( <Image> ),
  7089. *
  7090. * size: <float>,
  7091. *
  7092. * blending: THREE.NormalBlending,
  7093. * depthTest: <bool>,
  7094. * depthWrite: <bool>,
  7095. *
  7096. * vertexColors: <bool>,
  7097. *
  7098. * fog: <bool>
  7099. * }
  7100. */
  7101. THREE.ParticleBasicMaterial = function ( parameters ) {
  7102. THREE.Material.call( this );
  7103. this.color = new THREE.Color( 0xffffff );
  7104. this.map = null;
  7105. this.size = 1;
  7106. this.sizeAttenuation = true;
  7107. this.vertexColors = false;
  7108. this.fog = true;
  7109. this.setValues( parameters );
  7110. };
  7111. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7112. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7113. var material = new THREE.ParticleBasicMaterial();
  7114. THREE.Material.prototype.clone.call( this, material );
  7115. material.color.copy( this.color );
  7116. material.map = this.map;
  7117. material.size = this.size;
  7118. material.sizeAttenuation = this.sizeAttenuation;
  7119. material.vertexColors = this.vertexColors;
  7120. material.fog = this.fog;
  7121. return material;
  7122. };
  7123. /**
  7124. * @author mrdoob / http://mrdoob.com/
  7125. *
  7126. * parameters = {
  7127. * color: <hex>,
  7128. * program: <function>,
  7129. * opacity: <float>,
  7130. * blending: THREE.NormalBlending
  7131. * }
  7132. */
  7133. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7134. THREE.Material.call( this );
  7135. this.color = new THREE.Color( 0xffffff );
  7136. this.program = function ( context, color ) {};
  7137. this.setValues( parameters );
  7138. };
  7139. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7140. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7141. var material = new THREE.ParticleCanvasMaterial();
  7142. THREE.Material.prototype.clone.call( this, material );
  7143. material.color.copy( this.color );
  7144. material.program = this.program;
  7145. return material;
  7146. };
  7147. /**
  7148. * @author alteredq / http://alteredqualia.com/
  7149. *
  7150. * parameters = {
  7151. * fragmentShader: <string>,
  7152. * vertexShader: <string>,
  7153. *
  7154. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7155. *
  7156. * defines: { "label" : "value" },
  7157. *
  7158. * shading: THREE.SmoothShading,
  7159. * blending: THREE.NormalBlending,
  7160. * depthTest: <bool>,
  7161. * depthWrite: <bool>,
  7162. *
  7163. * wireframe: <boolean>,
  7164. * wireframeLinewidth: <float>,
  7165. *
  7166. * lights: <bool>,
  7167. *
  7168. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7169. *
  7170. * skinning: <bool>,
  7171. * morphTargets: <bool>,
  7172. * morphNormals: <bool>,
  7173. *
  7174. * fog: <bool>
  7175. * }
  7176. */
  7177. THREE.ShaderMaterial = function ( parameters ) {
  7178. THREE.Material.call( this );
  7179. this.fragmentShader = "void main() {}";
  7180. this.vertexShader = "void main() {}";
  7181. this.uniforms = {};
  7182. this.defines = {};
  7183. this.attributes = null;
  7184. this.shading = THREE.SmoothShading;
  7185. this.wireframe = false;
  7186. this.wireframeLinewidth = 1;
  7187. this.fog = false; // set to use scene fog
  7188. this.lights = false; // set to use scene lights
  7189. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7190. this.skinning = false; // set to use skinning attribute streams
  7191. this.morphTargets = false; // set to use morph targets
  7192. this.morphNormals = false; // set to use morph normals
  7193. this.setValues( parameters );
  7194. };
  7195. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7196. THREE.ShaderMaterial.prototype.clone = function () {
  7197. var material = new THREE.ShaderMaterial();
  7198. THREE.Material.prototype.clone.call( this, material );
  7199. material.fragmentShader = this.fragmentShader;
  7200. material.vertexShader = this.vertexShader;
  7201. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7202. material.attributes = this.attributes;
  7203. material.defines = this.defines;
  7204. material.shading = this.shading;
  7205. material.wireframe = this.wireframe;
  7206. material.wireframeLinewidth = this.wireframeLinewidth;
  7207. material.fog = this.fog;
  7208. material.lights = this.lights;
  7209. material.vertexColors = this.vertexColors;
  7210. material.skinning = this.skinning;
  7211. material.morphTargets = this.morphTargets;
  7212. material.morphNormals = this.morphNormals;
  7213. return material;
  7214. };
  7215. /**
  7216. * @author alteredq / http://alteredqualia.com/
  7217. *
  7218. * parameters = {
  7219. * color: <hex>,
  7220. * opacity: <float>,
  7221. * map: new THREE.Texture( <Image> ),
  7222. *
  7223. * blending: THREE.NormalBlending,
  7224. * depthTest: <bool>,
  7225. * depthWrite: <bool>,
  7226. *
  7227. * useScreenCoordinates: <bool>,
  7228. * sizeAttenuation: <bool>,
  7229. * scaleByViewport: <bool>,
  7230. * alignment: THREE.SpriteAlignment.center,
  7231. *
  7232. * uvOffset: new THREE.Vector2(),
  7233. * uvScale: new THREE.Vector2(),
  7234. *
  7235. * fog: <bool>
  7236. * }
  7237. */
  7238. THREE.SpriteMaterial = function ( parameters ) {
  7239. THREE.Material.call( this );
  7240. // defaults
  7241. this.color = new THREE.Color( 0xffffff );
  7242. this.map = new THREE.Texture();
  7243. this.useScreenCoordinates = true;
  7244. this.depthTest = !this.useScreenCoordinates;
  7245. this.sizeAttenuation = !this.useScreenCoordinates;
  7246. this.scaleByViewport = !this.sizeAttenuation;
  7247. this.alignment = THREE.SpriteAlignment.center.clone();
  7248. this.fog = false;
  7249. this.uvOffset = new THREE.Vector2( 0, 0 );
  7250. this.uvScale = new THREE.Vector2( 1, 1 );
  7251. // set parameters
  7252. this.setValues( parameters );
  7253. // override coupled defaults if not specified explicitly by parameters
  7254. parameters = parameters || {};
  7255. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7256. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7257. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7258. };
  7259. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7260. THREE.SpriteMaterial.prototype.clone = function () {
  7261. var material = new THREE.SpriteMaterial();
  7262. THREE.Material.prototype.clone.call( this, material );
  7263. material.color.copy( this.color );
  7264. material.map = this.map;
  7265. material.useScreenCoordinates = this.useScreenCoordinates;
  7266. material.sizeAttenuation = this.sizeAttenuation;
  7267. material.scaleByViewport = this.scaleByViewport;
  7268. material.alignment.copy( this.alignment );
  7269. material.uvOffset.copy( this.uvOffset );
  7270. material.uvScale.copy( this.uvScale );
  7271. material.fog = this.fog;
  7272. return material;
  7273. };
  7274. // Alignment enums
  7275. THREE.SpriteAlignment = {};
  7276. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7277. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7278. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7279. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7280. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7281. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7282. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7283. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7284. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7285. /**
  7286. * @author mrdoob / http://mrdoob.com/
  7287. * @author alteredq / http://alteredqualia.com/
  7288. * @author szimek / https://github.com/szimek/
  7289. */
  7290. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7291. THREE.EventDispatcher.call( this );
  7292. this.id = THREE.TextureIdCount ++;
  7293. this.name = '';
  7294. this.image = image;
  7295. this.mipmaps = [];
  7296. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7297. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7298. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7299. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7300. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7301. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7302. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7303. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7304. this.offset = new THREE.Vector2( 0, 0 );
  7305. this.repeat = new THREE.Vector2( 1, 1 );
  7306. this.generateMipmaps = true;
  7307. this.premultiplyAlpha = false;
  7308. this.flipY = true;
  7309. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7310. this.needsUpdate = false;
  7311. this.onUpdate = null;
  7312. };
  7313. THREE.Texture.prototype = {
  7314. constructor: THREE.Texture,
  7315. clone: function ( texture ) {
  7316. if ( texture === undefined ) texture = new THREE.Texture();
  7317. texture.image = this.image;
  7318. texture.mipmaps = this.mipmaps.slice(0);
  7319. texture.mapping = this.mapping;
  7320. texture.wrapS = this.wrapS;
  7321. texture.wrapT = this.wrapT;
  7322. texture.magFilter = this.magFilter;
  7323. texture.minFilter = this.minFilter;
  7324. texture.anisotropy = this.anisotropy;
  7325. texture.format = this.format;
  7326. texture.type = this.type;
  7327. texture.offset.copy( this.offset );
  7328. texture.repeat.copy( this.repeat );
  7329. texture.generateMipmaps = this.generateMipmaps;
  7330. texture.premultiplyAlpha = this.premultiplyAlpha;
  7331. texture.flipY = this.flipY;
  7332. texture.unpackAlignment = this.unpackAlignment;
  7333. return texture;
  7334. },
  7335. dispose: function () {
  7336. this.dispatchEvent( { type: 'dispose' } );
  7337. }
  7338. };
  7339. THREE.TextureIdCount = 0;
  7340. /**
  7341. * @author alteredq / http://alteredqualia.com/
  7342. */
  7343. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7344. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7345. this.image = { width: width, height: height };
  7346. this.mipmaps = mipmaps;
  7347. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7348. };
  7349. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7350. THREE.CompressedTexture.prototype.clone = function () {
  7351. var texture = new THREE.CompressedTexture();
  7352. THREE.Texture.prototype.clone.call( this, texture );
  7353. return texture;
  7354. };
  7355. /**
  7356. * @author alteredq / http://alteredqualia.com/
  7357. */
  7358. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7359. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7360. this.image = { data: data, width: width, height: height };
  7361. };
  7362. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7363. THREE.DataTexture.prototype.clone = function () {
  7364. var texture = new THREE.DataTexture();
  7365. THREE.Texture.prototype.clone.call( this, texture );
  7366. return texture;
  7367. };
  7368. /**
  7369. * @author mrdoob / http://mrdoob.com/
  7370. */
  7371. THREE.Particle = function ( material ) {
  7372. THREE.Object3D.call( this );
  7373. this.material = material;
  7374. };
  7375. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7376. THREE.Particle.prototype.clone = function ( object ) {
  7377. if ( object === undefined ) object = new THREE.Particle( this.material );
  7378. THREE.Object3D.prototype.clone.call( this, object );
  7379. return object;
  7380. };
  7381. /**
  7382. * @author alteredq / http://alteredqualia.com/
  7383. */
  7384. THREE.ParticleSystem = function ( geometry, material ) {
  7385. THREE.Object3D.call( this );
  7386. this.geometry = geometry;
  7387. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7388. this.sortParticles = false;
  7389. if ( this.geometry ) {
  7390. // calc bound radius
  7391. if( this.geometry.boundingSphere === null ) {
  7392. this.geometry.computeBoundingSphere();
  7393. }
  7394. }
  7395. this.frustumCulled = false;
  7396. };
  7397. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7398. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7399. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7400. object.sortParticles = this.sortParticles;
  7401. THREE.Object3D.prototype.clone.call( this, object );
  7402. return object;
  7403. };
  7404. /**
  7405. * @author mrdoob / http://mrdoob.com/
  7406. */
  7407. THREE.Line = function ( geometry, material, type ) {
  7408. THREE.Object3D.call( this );
  7409. this.geometry = geometry;
  7410. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7411. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7412. if ( this.geometry ) {
  7413. if ( ! this.geometry.boundingSphere ) {
  7414. this.geometry.computeBoundingSphere();
  7415. }
  7416. }
  7417. };
  7418. THREE.LineStrip = 0;
  7419. THREE.LinePieces = 1;
  7420. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7421. THREE.Line.prototype.clone = function ( object ) {
  7422. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7423. THREE.Object3D.prototype.clone.call( this, object );
  7424. return object;
  7425. };
  7426. /**
  7427. * @author mrdoob / http://mrdoob.com/
  7428. * @author alteredq / http://alteredqualia.com/
  7429. * @author mikael emtinger / http://gomo.se/
  7430. * @author jonobr1 / http://jonobr1.com/
  7431. */
  7432. THREE.Mesh = function ( geometry, material ) {
  7433. THREE.Object3D.call( this );
  7434. this.geometry = geometry;
  7435. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7436. if ( this.geometry !== undefined ) {
  7437. if ( this.geometry.boundingSphere === null ) {
  7438. this.geometry.computeBoundingSphere();
  7439. }
  7440. this.updateMorphTargets();
  7441. }
  7442. };
  7443. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7444. THREE.Mesh.prototype.updateMorphTargets = function () {
  7445. if ( this.geometry.morphTargets.length > 0 ) {
  7446. this.morphTargetBase = -1;
  7447. this.morphTargetForcedOrder = [];
  7448. this.morphTargetInfluences = [];
  7449. this.morphTargetDictionary = {};
  7450. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7451. this.morphTargetInfluences.push( 0 );
  7452. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7453. }
  7454. }
  7455. };
  7456. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7457. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7458. return this.morphTargetDictionary[ name ];
  7459. }
  7460. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7461. return 0;
  7462. };
  7463. THREE.Mesh.prototype.clone = function ( object ) {
  7464. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7465. THREE.Object3D.prototype.clone.call( this, object );
  7466. return object;
  7467. };
  7468. /**
  7469. * @author mikael emtinger / http://gomo.se/
  7470. * @author alteredq / http://alteredqualia.com/
  7471. */
  7472. THREE.Bone = function( belongsToSkin ) {
  7473. THREE.Object3D.call( this );
  7474. this.skin = belongsToSkin;
  7475. this.skinMatrix = new THREE.Matrix4();
  7476. };
  7477. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7478. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7479. // update local
  7480. if ( this.matrixAutoUpdate ) {
  7481. forceUpdate |= this.updateMatrix();
  7482. }
  7483. // update skin matrix
  7484. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7485. if( parentSkinMatrix ) {
  7486. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7487. } else {
  7488. this.skinMatrix.copy( this.matrix );
  7489. }
  7490. this.matrixWorldNeedsUpdate = false;
  7491. forceUpdate = true;
  7492. }
  7493. // update children
  7494. var child, i, l = this.children.length;
  7495. for ( i = 0; i < l; i ++ ) {
  7496. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7497. }
  7498. };
  7499. /**
  7500. * @author mikael emtinger / http://gomo.se/
  7501. * @author alteredq / http://alteredqualia.com/
  7502. */
  7503. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7504. THREE.Mesh.call( this, geometry, material );
  7505. //
  7506. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7507. // init bones
  7508. this.identityMatrix = new THREE.Matrix4();
  7509. this.bones = [];
  7510. this.boneMatrices = [];
  7511. var b, bone, gbone, p, q, s;
  7512. if ( this.geometry && this.geometry.bones !== undefined ) {
  7513. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7514. gbone = this.geometry.bones[ b ];
  7515. p = gbone.pos;
  7516. q = gbone.rotq;
  7517. s = gbone.scl;
  7518. bone = this.addBone();
  7519. bone.name = gbone.name;
  7520. bone.position.set( p[0], p[1], p[2] );
  7521. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7522. bone.useQuaternion = true;
  7523. if ( s !== undefined ) {
  7524. bone.scale.set( s[0], s[1], s[2] );
  7525. } else {
  7526. bone.scale.set( 1, 1, 1 );
  7527. }
  7528. }
  7529. for ( b = 0; b < this.bones.length; b ++ ) {
  7530. gbone = this.geometry.bones[ b ];
  7531. bone = this.bones[ b ];
  7532. if ( gbone.parent === -1 ) {
  7533. this.add( bone );
  7534. } else {
  7535. this.bones[ gbone.parent ].add( bone );
  7536. }
  7537. }
  7538. //
  7539. var nBones = this.bones.length;
  7540. if ( this.useVertexTexture ) {
  7541. // layout (1 matrix = 4 pixels)
  7542. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7543. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7544. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7545. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7546. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7547. var size;
  7548. if ( nBones > 256 )
  7549. size = 64;
  7550. else if ( nBones > 64 )
  7551. size = 32;
  7552. else if ( nBones > 16 )
  7553. size = 16;
  7554. else
  7555. size = 8;
  7556. this.boneTextureWidth = size;
  7557. this.boneTextureHeight = size;
  7558. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7559. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7560. this.boneTexture.minFilter = THREE.NearestFilter;
  7561. this.boneTexture.magFilter = THREE.NearestFilter;
  7562. this.boneTexture.generateMipmaps = false;
  7563. this.boneTexture.flipY = false;
  7564. } else {
  7565. this.boneMatrices = new Float32Array( 16 * nBones );
  7566. }
  7567. this.pose();
  7568. }
  7569. };
  7570. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7571. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7572. if ( bone === undefined ) {
  7573. bone = new THREE.Bone( this );
  7574. }
  7575. this.bones.push( bone );
  7576. return bone;
  7577. };
  7578. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7579. this.matrixAutoUpdate && this.updateMatrix();
  7580. // update matrixWorld
  7581. if ( this.matrixWorldNeedsUpdate || force ) {
  7582. if ( this.parent ) {
  7583. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7584. } else {
  7585. this.matrixWorld.copy( this.matrix );
  7586. }
  7587. this.matrixWorldNeedsUpdate = false;
  7588. force = true;
  7589. }
  7590. // update children
  7591. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7592. var child = this.children[ i ];
  7593. if ( child instanceof THREE.Bone ) {
  7594. child.update( this.identityMatrix, false );
  7595. } else {
  7596. child.updateMatrixWorld( true );
  7597. }
  7598. }
  7599. // make a snapshot of the bones' rest position
  7600. if ( this.boneInverses == undefined ) {
  7601. this.boneInverses = [];
  7602. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7603. var inverse = new THREE.Matrix4();
  7604. inverse.getInverse( this.bones[ b ].skinMatrix );
  7605. this.boneInverses.push( inverse );
  7606. }
  7607. }
  7608. // flatten bone matrices to array
  7609. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7610. // compute the offset between the current and the original transform;
  7611. //TODO: we could get rid of this multiplication step if the skinMatrix
  7612. // was already representing the offset; however, this requires some
  7613. // major changes to the animation system
  7614. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7615. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7616. }
  7617. if ( this.useVertexTexture ) {
  7618. this.boneTexture.needsUpdate = true;
  7619. }
  7620. };
  7621. THREE.SkinnedMesh.prototype.pose = function () {
  7622. this.updateMatrixWorld( true );
  7623. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7624. // normalize weights
  7625. var sw = this.geometry.skinWeights[ i ];
  7626. var scale = 1.0 / sw.lengthManhattan();
  7627. if ( scale !== Infinity ) {
  7628. sw.multiplyScalar( scale );
  7629. } else {
  7630. sw.set( 1 ); // this will be normalized by the shader anyway
  7631. }
  7632. }
  7633. };
  7634. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7635. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7636. THREE.Mesh.prototype.clone.call( this, object );
  7637. return object;
  7638. };
  7639. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7640. /**
  7641. * @author alteredq / http://alteredqualia.com/
  7642. */
  7643. THREE.MorphAnimMesh = function ( geometry, material ) {
  7644. THREE.Mesh.call( this, geometry, material );
  7645. // API
  7646. this.duration = 1000; // milliseconds
  7647. this.mirroredLoop = false;
  7648. this.time = 0;
  7649. // internals
  7650. this.lastKeyframe = 0;
  7651. this.currentKeyframe = 0;
  7652. this.direction = 1;
  7653. this.directionBackwards = false;
  7654. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7655. };
  7656. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7657. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7658. this.startKeyframe = start;
  7659. this.endKeyframe = end;
  7660. this.length = this.endKeyframe - this.startKeyframe + 1;
  7661. };
  7662. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7663. this.direction = 1;
  7664. this.directionBackwards = false;
  7665. };
  7666. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7667. this.direction = -1;
  7668. this.directionBackwards = true;
  7669. };
  7670. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7671. var geometry = this.geometry;
  7672. if ( ! geometry.animations ) geometry.animations = {};
  7673. var firstAnimation, animations = geometry.animations;
  7674. var pattern = /([a-z]+)(\d+)/;
  7675. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7676. var morph = geometry.morphTargets[ i ];
  7677. var parts = morph.name.match( pattern );
  7678. if ( parts && parts.length > 1 ) {
  7679. var label = parts[ 1 ];
  7680. var num = parts[ 2 ];
  7681. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7682. var animation = animations[ label ];
  7683. if ( i < animation.start ) animation.start = i;
  7684. if ( i > animation.end ) animation.end = i;
  7685. if ( ! firstAnimation ) firstAnimation = label;
  7686. }
  7687. }
  7688. geometry.firstAnimation = firstAnimation;
  7689. };
  7690. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7691. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7692. this.geometry.animations[ label ] = { start: start, end: end };
  7693. };
  7694. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7695. var animation = this.geometry.animations[ label ];
  7696. if ( animation ) {
  7697. this.setFrameRange( animation.start, animation.end );
  7698. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7699. this.time = 0;
  7700. } else {
  7701. console.warn( "animation[" + label + "] undefined" );
  7702. }
  7703. };
  7704. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7705. var frameTime = this.duration / this.length;
  7706. this.time += this.direction * delta;
  7707. if ( this.mirroredLoop ) {
  7708. if ( this.time > this.duration || this.time < 0 ) {
  7709. this.direction *= -1;
  7710. if ( this.time > this.duration ) {
  7711. this.time = this.duration;
  7712. this.directionBackwards = true;
  7713. }
  7714. if ( this.time < 0 ) {
  7715. this.time = 0;
  7716. this.directionBackwards = false;
  7717. }
  7718. }
  7719. } else {
  7720. this.time = this.time % this.duration;
  7721. if ( this.time < 0 ) this.time += this.duration;
  7722. }
  7723. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7724. if ( keyframe !== this.currentKeyframe ) {
  7725. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7726. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7727. this.morphTargetInfluences[ keyframe ] = 0;
  7728. this.lastKeyframe = this.currentKeyframe;
  7729. this.currentKeyframe = keyframe;
  7730. }
  7731. var mix = ( this.time % frameTime ) / frameTime;
  7732. if ( this.directionBackwards ) {
  7733. mix = 1 - mix;
  7734. }
  7735. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7736. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7737. };
  7738. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7739. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7740. object.duration = this.duration;
  7741. object.mirroredLoop = this.mirroredLoop;
  7742. object.time = this.time;
  7743. object.lastKeyframe = this.lastKeyframe;
  7744. object.currentKeyframe = this.currentKeyframe;
  7745. object.direction = this.direction;
  7746. object.directionBackwards = this.directionBackwards;
  7747. THREE.Mesh.prototype.clone.call( this, object );
  7748. return object;
  7749. };
  7750. /**
  7751. * @author alteredq / http://alteredqualia.com/
  7752. */
  7753. THREE.Ribbon = function ( geometry, material ) {
  7754. THREE.Object3D.call( this );
  7755. this.geometry = geometry;
  7756. this.material = material;
  7757. };
  7758. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7759. THREE.Ribbon.prototype.clone = function ( object ) {
  7760. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7761. THREE.Object3D.prototype.clone.call( this, object );
  7762. return object;
  7763. };
  7764. /**
  7765. * @author mikael emtinger / http://gomo.se/
  7766. * @author alteredq / http://alteredqualia.com/
  7767. * @author mrdoob / http://mrdoob.com/
  7768. */
  7769. THREE.LOD = function () {
  7770. THREE.Object3D.call( this );
  7771. this.LODs = [];
  7772. };
  7773. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7774. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7775. if ( visibleAtDistance === undefined ) {
  7776. visibleAtDistance = 0;
  7777. }
  7778. visibleAtDistance = Math.abs( visibleAtDistance );
  7779. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7780. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7781. break;
  7782. }
  7783. }
  7784. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7785. this.add( object3D );
  7786. };
  7787. THREE.LOD.prototype.update = function ( camera ) {
  7788. if ( this.LODs.length > 1 ) {
  7789. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7790. var inverse = camera.matrixWorldInverse;
  7791. var distance = -( inverse.elements[2] * this.matrixWorld.elements[12] + inverse.elements[6] * this.matrixWorld.elements[13] + inverse.elements[10] * this.matrixWorld.elements[14] + inverse.elements[14] );
  7792. this.LODs[ 0 ].object3D.visible = true;
  7793. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7794. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7795. this.LODs[ l - 1 ].object3D.visible = false;
  7796. this.LODs[ l ].object3D.visible = true;
  7797. } else {
  7798. break;
  7799. }
  7800. }
  7801. for( ; l < this.LODs.length; l ++ ) {
  7802. this.LODs[ l ].object3D.visible = false;
  7803. }
  7804. }
  7805. };
  7806. THREE.LOD.prototype.clone = function () {
  7807. // TODO
  7808. };
  7809. /**
  7810. * @author mikael emtinger / http://gomo.se/
  7811. * @author alteredq / http://alteredqualia.com/
  7812. */
  7813. THREE.Sprite = function ( material ) {
  7814. THREE.Object3D.call( this );
  7815. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7816. this.rotation3d = this.rotation;
  7817. this.rotation = 0;
  7818. };
  7819. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7820. /*
  7821. * Custom update matrix
  7822. */
  7823. THREE.Sprite.prototype.updateMatrix = function () {
  7824. this.matrix.setPosition( this.position );
  7825. this.rotation3d.set( 0, 0, this.rotation );
  7826. this.matrix.setRotationFromEuler( this.rotation3d );
  7827. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7828. this.matrix.scale( this.scale );
  7829. }
  7830. this.matrixWorldNeedsUpdate = true;
  7831. };
  7832. THREE.Sprite.prototype.clone = function ( object ) {
  7833. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7834. THREE.Object3D.prototype.clone.call( this, object );
  7835. return object;
  7836. };
  7837. /**
  7838. * @author mrdoob / http://mrdoob.com/
  7839. */
  7840. THREE.Scene = function () {
  7841. THREE.Object3D.call( this );
  7842. this.fog = null;
  7843. this.overrideMaterial = null;
  7844. this.matrixAutoUpdate = false;
  7845. this.__objects = [];
  7846. this.__lights = [];
  7847. this.__objectsAdded = [];
  7848. this.__objectsRemoved = [];
  7849. };
  7850. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7851. THREE.Scene.prototype.__addObject = function ( object ) {
  7852. if ( object instanceof THREE.Light ) {
  7853. if ( this.__lights.indexOf( object ) === - 1 ) {
  7854. this.__lights.push( object );
  7855. }
  7856. if ( object.target && object.target.parent === undefined ) {
  7857. this.add( object.target );
  7858. }
  7859. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7860. if ( this.__objects.indexOf( object ) === - 1 ) {
  7861. this.__objects.push( object );
  7862. this.__objectsAdded.push( object );
  7863. // check if previously removed
  7864. var i = this.__objectsRemoved.indexOf( object );
  7865. if ( i !== -1 ) {
  7866. this.__objectsRemoved.splice( i, 1 );
  7867. }
  7868. }
  7869. }
  7870. for ( var c = 0; c < object.children.length; c ++ ) {
  7871. this.__addObject( object.children[ c ] );
  7872. }
  7873. };
  7874. THREE.Scene.prototype.__removeObject = function ( object ) {
  7875. if ( object instanceof THREE.Light ) {
  7876. var i = this.__lights.indexOf( object );
  7877. if ( i !== -1 ) {
  7878. this.__lights.splice( i, 1 );
  7879. }
  7880. } else if ( !( object instanceof THREE.Camera ) ) {
  7881. var i = this.__objects.indexOf( object );
  7882. if( i !== -1 ) {
  7883. this.__objects.splice( i, 1 );
  7884. this.__objectsRemoved.push( object );
  7885. // check if previously added
  7886. var ai = this.__objectsAdded.indexOf( object );
  7887. if ( ai !== -1 ) {
  7888. this.__objectsAdded.splice( ai, 1 );
  7889. }
  7890. }
  7891. }
  7892. for ( var c = 0; c < object.children.length; c ++ ) {
  7893. this.__removeObject( object.children[ c ] );
  7894. }
  7895. };
  7896. /**
  7897. * @author mrdoob / http://mrdoob.com/
  7898. * @author alteredq / http://alteredqualia.com/
  7899. */
  7900. THREE.Fog = function ( hex, near, far ) {
  7901. this.name = '';
  7902. this.color = new THREE.Color( hex );
  7903. this.near = ( near !== undefined ) ? near : 1;
  7904. this.far = ( far !== undefined ) ? far : 1000;
  7905. };
  7906. THREE.Fog.prototype.clone = function () {
  7907. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7908. };
  7909. /**
  7910. * @author mrdoob / http://mrdoob.com/
  7911. * @author alteredq / http://alteredqualia.com/
  7912. */
  7913. THREE.FogExp2 = function ( hex, density ) {
  7914. this.name = '';
  7915. this.color = new THREE.Color( hex );
  7916. this.density = ( density !== undefined ) ? density : 0.00025;
  7917. };
  7918. THREE.FogExp2.prototype.clone = function () {
  7919. return new THREE.FogExp2( this.color.getHex(), this.density );
  7920. };
  7921. /**
  7922. * @author mrdoob / http://mrdoob.com/
  7923. */
  7924. THREE.CanvasRenderer = function ( parameters ) {
  7925. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7926. parameters = parameters || {};
  7927. var _this = this,
  7928. _renderData, _elements, _lights,
  7929. _projector = new THREE.Projector(),
  7930. _canvas = parameters.canvas !== undefined
  7931. ? parameters.canvas
  7932. : document.createElement( 'canvas' ),
  7933. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7934. _context = _canvas.getContext( '2d' ),
  7935. _clearColor = new THREE.Color( 0x000000 ),
  7936. _clearOpacity = 0,
  7937. _contextGlobalAlpha = 1,
  7938. _contextGlobalCompositeOperation = 0,
  7939. _contextStrokeStyle = null,
  7940. _contextFillStyle = null,
  7941. _contextLineWidth = null,
  7942. _contextLineCap = null,
  7943. _contextLineJoin = null,
  7944. _contextDashSize = null,
  7945. _contextGapSize = 0,
  7946. _v1, _v2, _v3, _v4,
  7947. _v5 = new THREE.RenderableVertex(),
  7948. _v6 = new THREE.RenderableVertex(),
  7949. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7950. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7951. _color = new THREE.Color(),
  7952. _color1 = new THREE.Color(),
  7953. _color2 = new THREE.Color(),
  7954. _color3 = new THREE.Color(),
  7955. _color4 = new THREE.Color(),
  7956. _diffuseColor = new THREE.Color(),
  7957. _emissiveColor = new THREE.Color(),
  7958. _lightColor = new THREE.Color(),
  7959. _patterns = {}, _imagedatas = {},
  7960. _near, _far,
  7961. _image, _uvs,
  7962. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7963. _clipBox = new THREE.Box2(),
  7964. _clearBox = new THREE.Box2(),
  7965. _elemBox = new THREE.Box2(),
  7966. _enableLighting = false,
  7967. _ambientLight = new THREE.Color(),
  7968. _directionalLights = new THREE.Color(),
  7969. _pointLights = new THREE.Color(),
  7970. _pi2 = Math.PI * 2,
  7971. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7972. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7973. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7974. _pixelMap = document.createElement( 'canvas' );
  7975. _pixelMap.width = _pixelMap.height = 2;
  7976. _pixelMapContext = _pixelMap.getContext( '2d' );
  7977. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7978. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7979. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7980. _pixelMapData = _pixelMapImage.data;
  7981. _gradientMap = document.createElement( 'canvas' );
  7982. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7983. _gradientMapContext = _gradientMap.getContext( '2d' );
  7984. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7985. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7986. _gradientMapQuality --; // Fix UVs
  7987. // dash+gap fallbacks for Firefox and everything else
  7988. if ( _context.setLineDash === undefined ) {
  7989. if ( _context.mozDash !== undefined ) {
  7990. _context.setLineDash = function ( values ) {
  7991. _context.mozDash = values[ 0 ] !== null ? values : null;
  7992. }
  7993. } else {
  7994. _context.setLineDash = function ( values ) {}
  7995. }
  7996. }
  7997. this.domElement = _canvas;
  7998. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  7999. ? parameters.devicePixelRatio
  8000. : window.devicePixelRatio !== undefined
  8001. ? window.devicePixelRatio
  8002. : 1;
  8003. this.autoClear = true;
  8004. this.sortObjects = true;
  8005. this.sortElements = true;
  8006. this.info = {
  8007. render: {
  8008. vertices: 0,
  8009. faces: 0
  8010. }
  8011. }
  8012. // WebGLRenderer compatibility
  8013. this.supportsVertexTextures = function () {};
  8014. this.setFaceCulling = function () {};
  8015. this.setSize = function ( width, height ) {
  8016. _canvasWidth = width * this.devicePixelRatio;
  8017. _canvasHeight = height * this.devicePixelRatio;
  8018. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8019. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8020. _canvas.width = _canvasWidth;
  8021. _canvas.height = _canvasHeight;
  8022. _canvas.style.width = width + 'px';
  8023. _canvas.style.height = height + 'px';
  8024. _clipBox.set(
  8025. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8026. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8027. );
  8028. _clearBox.set(
  8029. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8030. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8031. );
  8032. _contextGlobalAlpha = 1;
  8033. _contextGlobalCompositeOperation = 0;
  8034. _contextStrokeStyle = null;
  8035. _contextFillStyle = null;
  8036. _contextLineWidth = null;
  8037. _contextLineCap = null;
  8038. _contextLineJoin = null;
  8039. };
  8040. this.setClearColor = function ( color, opacity ) {
  8041. _clearColor.copy( color );
  8042. _clearOpacity = opacity !== undefined ? opacity : 1;
  8043. _clearBox.set(
  8044. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8045. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8046. );
  8047. };
  8048. this.setClearColorHex = function ( hex, opacity ) {
  8049. _clearColor.setHex( hex );
  8050. _clearOpacity = opacity !== undefined ? opacity : 1;
  8051. _clearBox.set(
  8052. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8053. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8054. );
  8055. };
  8056. this.getMaxAnisotropy = function () {
  8057. return 0;
  8058. };
  8059. this.clear = function () {
  8060. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8061. if ( _clearBox.empty() === false ) {
  8062. _clearBox.intersect( _clipBox );
  8063. _clearBox.expandByScalar( 2 );
  8064. if ( _clearOpacity < 1 ) {
  8065. _context.clearRect(
  8066. _clearBox.min.x | 0,
  8067. _clearBox.min.y | 0,
  8068. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8069. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8070. );
  8071. }
  8072. if ( _clearOpacity > 0 ) {
  8073. setBlending( THREE.NormalBlending );
  8074. setOpacity( 1 );
  8075. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  8076. _context.fillRect(
  8077. _clearBox.min.x | 0,
  8078. _clearBox.min.y | 0,
  8079. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8080. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8081. );
  8082. }
  8083. _clearBox.makeEmpty();
  8084. }
  8085. };
  8086. this.render = function ( scene, camera ) {
  8087. if ( camera instanceof THREE.Camera === false ) {
  8088. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8089. return;
  8090. }
  8091. if ( this.autoClear === true ) {
  8092. this.clear();
  8093. }
  8094. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8095. _this.info.render.vertices = 0;
  8096. _this.info.render.faces = 0;
  8097. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8098. _elements = _renderData.elements;
  8099. _lights = _renderData.lights;
  8100. /* DEBUG
  8101. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8102. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8103. */
  8104. _enableLighting = _lights.length > 0;
  8105. if ( _enableLighting === true ) {
  8106. calculateLights();
  8107. }
  8108. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8109. var element = _elements[ e ];
  8110. var material = element.material;
  8111. if ( material === undefined || material.visible === false ) continue;
  8112. _elemBox.makeEmpty();
  8113. if ( element instanceof THREE.RenderableParticle ) {
  8114. _v1 = element;
  8115. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8116. renderParticle( _v1, element, material, scene );
  8117. } else if ( element instanceof THREE.RenderableLine ) {
  8118. _v1 = element.v1; _v2 = element.v2;
  8119. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8120. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8121. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  8122. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8123. renderLine( _v1, _v2, element, material, scene );
  8124. }
  8125. } else if ( element instanceof THREE.RenderableFace3 ) {
  8126. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8127. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8128. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8129. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8130. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8131. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8132. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8133. if ( material.overdraw === true ) {
  8134. expand( _v1.positionScreen, _v2.positionScreen );
  8135. expand( _v2.positionScreen, _v3.positionScreen );
  8136. expand( _v3.positionScreen, _v1.positionScreen );
  8137. }
  8138. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  8139. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  8140. } else if ( element instanceof THREE.RenderableFace4 ) {
  8141. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8142. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8143. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8144. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8145. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8146. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8147. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8148. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8149. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8150. _v5.positionScreen.copy( _v2.positionScreen );
  8151. _v6.positionScreen.copy( _v4.positionScreen );
  8152. if ( material.overdraw === true ) {
  8153. expand( _v1.positionScreen, _v2.positionScreen );
  8154. expand( _v2.positionScreen, _v4.positionScreen );
  8155. expand( _v4.positionScreen, _v1.positionScreen );
  8156. expand( _v3.positionScreen, _v5.positionScreen );
  8157. expand( _v3.positionScreen, _v6.positionScreen );
  8158. }
  8159. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8160. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8161. }
  8162. /* DEBUG
  8163. setLineWidth( 1 );
  8164. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8165. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8166. */
  8167. _clearBox.union( _elemBox );
  8168. }
  8169. /* DEBUG
  8170. setLineWidth( 1 );
  8171. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  8172. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8173. */
  8174. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8175. //
  8176. function calculateLights() {
  8177. _ambientLight.setRGB( 0, 0, 0 );
  8178. _directionalLights.setRGB( 0, 0, 0 );
  8179. _pointLights.setRGB( 0, 0, 0 );
  8180. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8181. var light = _lights[ l ];
  8182. var lightColor = light.color;
  8183. if ( light instanceof THREE.AmbientLight ) {
  8184. _ambientLight.add( lightColor );
  8185. } else if ( light instanceof THREE.DirectionalLight ) {
  8186. // for particles
  8187. _directionalLights.add( lightColor );
  8188. } else if ( light instanceof THREE.PointLight ) {
  8189. // for particles
  8190. _pointLights.add( lightColor );
  8191. }
  8192. }
  8193. }
  8194. function calculateLight( position, normal, color ) {
  8195. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8196. var light = _lights[ l ];
  8197. _lightColor.copy( light.color );
  8198. if ( light instanceof THREE.DirectionalLight ) {
  8199. var lightPosition = light.matrixWorld.getPosition().normalize();
  8200. var amount = normal.dot( lightPosition );
  8201. if ( amount <= 0 ) continue;
  8202. amount *= light.intensity;
  8203. color.add( _lightColor.multiplyScalar( amount ) );
  8204. } else if ( light instanceof THREE.PointLight ) {
  8205. var lightPosition = light.matrixWorld.getPosition();
  8206. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8207. if ( amount <= 0 ) continue;
  8208. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8209. if ( amount == 0 ) continue;
  8210. amount *= light.intensity;
  8211. color.add( _lightColor.multiplyScalar( amount ) );
  8212. }
  8213. }
  8214. }
  8215. function renderParticle( v1, element, material, scene ) {
  8216. setOpacity( material.opacity );
  8217. setBlending( material.blending );
  8218. var width, height, scaleX, scaleY,
  8219. bitmap, bitmapWidth, bitmapHeight;
  8220. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8221. if ( material.map === null ) {
  8222. scaleX = element.object.scale.x;
  8223. scaleY = element.object.scale.y;
  8224. // TODO: Be able to disable this
  8225. scaleX *= element.scale.x * _canvasWidthHalf;
  8226. scaleY *= element.scale.y * _canvasHeightHalf;
  8227. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8228. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8229. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8230. return;
  8231. }
  8232. setFillStyle( material.color.getStyle() );
  8233. _context.save();
  8234. _context.translate( v1.x, v1.y );
  8235. _context.rotate( - element.rotation );
  8236. _context.scale( scaleX, scaleY );
  8237. _context.fillRect( -1, -1, 2, 2 );
  8238. _context.restore();
  8239. } else {
  8240. bitmap = material.map.image;
  8241. bitmapWidth = bitmap.width >> 1;
  8242. bitmapHeight = bitmap.height >> 1;
  8243. scaleX = element.scale.x * _canvasWidthHalf;
  8244. scaleY = element.scale.y * _canvasHeightHalf;
  8245. width = scaleX * bitmapWidth;
  8246. height = scaleY * bitmapHeight;
  8247. // TODO: Rotations break this...
  8248. _elemBox.min.set( v1.x - width, v1.y - height );
  8249. _elemBox.max.set( v1.x + width, v1.y + height );
  8250. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8251. return;
  8252. }
  8253. _context.save();
  8254. _context.translate( v1.x, v1.y );
  8255. _context.rotate( - element.rotation );
  8256. _context.scale( scaleX, - scaleY );
  8257. _context.translate( - bitmapWidth, - bitmapHeight );
  8258. _context.drawImage( bitmap, 0, 0 );
  8259. _context.restore();
  8260. }
  8261. /* DEBUG
  8262. setStrokeStyle( 'rgb(255,255,0)' );
  8263. _context.beginPath();
  8264. _context.moveTo( v1.x - 10, v1.y );
  8265. _context.lineTo( v1.x + 10, v1.y );
  8266. _context.moveTo( v1.x, v1.y - 10 );
  8267. _context.lineTo( v1.x, v1.y + 10 );
  8268. _context.stroke();
  8269. */
  8270. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8271. width = element.scale.x * _canvasWidthHalf;
  8272. height = element.scale.y * _canvasHeightHalf;
  8273. _elemBox.min.set( v1.x - width, v1.y - height );
  8274. _elemBox.max.set( v1.x + width, v1.y + height );
  8275. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8276. return;
  8277. }
  8278. setStrokeStyle( material.color.getStyle() );
  8279. setFillStyle( material.color.getStyle() );
  8280. _context.save();
  8281. _context.translate( v1.x, v1.y );
  8282. _context.rotate( - element.rotation );
  8283. _context.scale( width, height );
  8284. material.program( _context );
  8285. _context.restore();
  8286. }
  8287. }
  8288. function renderLine( v1, v2, element, material, scene ) {
  8289. setOpacity( material.opacity );
  8290. setBlending( material.blending );
  8291. _context.beginPath();
  8292. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8293. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8294. if ( material instanceof THREE.LineBasicMaterial ) {
  8295. setLineWidth( material.linewidth );
  8296. setLineCap( material.linecap );
  8297. setLineJoin( material.linejoin );
  8298. setStrokeStyle( material.color.getStyle() );
  8299. setDashAndGap( null, null );
  8300. _context.stroke();
  8301. _elemBox.expandByScalar( material.linewidth * 2 );
  8302. } else if ( material instanceof THREE.LineDashedMaterial ) {
  8303. setLineWidth( material.linewidth );
  8304. setLineCap( material.linecap );
  8305. setLineJoin( material.linejoin );
  8306. setStrokeStyle( material.color.getStyle() );
  8307. setDashAndGap( material.dashSize, material.gapSize );
  8308. _context.stroke();
  8309. _elemBox.expandByScalar( material.linewidth * 2 );
  8310. }
  8311. }
  8312. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  8313. _this.info.render.vertices += 3;
  8314. _this.info.render.faces ++;
  8315. setOpacity( material.opacity );
  8316. setBlending( material.blending );
  8317. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8318. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8319. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8320. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8321. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  8322. _diffuseColor.copy( material.color );
  8323. _emissiveColor.copy( material.emissive );
  8324. if ( material.vertexColors === THREE.FaceColors ) {
  8325. _diffuseColor.multiply( element.color );
  8326. }
  8327. if ( _enableLighting === true ) {
  8328. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8329. _color1.copy( _ambientLight );
  8330. _color2.copy( _ambientLight );
  8331. _color3.copy( _ambientLight );
  8332. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8333. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8334. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8335. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8336. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8337. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8338. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8339. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8340. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8341. } else {
  8342. _color.copy( _ambientLight );
  8343. calculateLight( element.centroidModel, element.normalModel, _color );
  8344. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8345. material.wireframe === true
  8346. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8347. : fillPath( _color );
  8348. }
  8349. } else {
  8350. material.wireframe === true
  8351. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8352. : fillPath( material.color );
  8353. }
  8354. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8355. if ( material.map !== null ) {
  8356. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8357. _uvs = element.uvs[ 0 ];
  8358. 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 );
  8359. }
  8360. } else if ( material.envMap !== null ) {
  8361. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8362. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8363. _uv1x = 0.5 * _vector3.x + 0.5;
  8364. _uv1y = 0.5 * _vector3.y + 0.5;
  8365. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8366. _uv2x = 0.5 * _vector3.x + 0.5;
  8367. _uv2y = 0.5 * _vector3.y + 0.5;
  8368. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8369. _uv3x = 0.5 * _vector3.x + 0.5;
  8370. _uv3y = 0.5 * _vector3.y + 0.5;
  8371. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8372. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8373. }*/
  8374. } else {
  8375. _color.copy( material.color );
  8376. if ( material.vertexColors === THREE.FaceColors ) {
  8377. _color.multiply( element.color );
  8378. }
  8379. material.wireframe === true
  8380. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8381. : fillPath( _color );
  8382. }
  8383. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8384. _near = camera.near;
  8385. _far = camera.far;
  8386. var depth;
  8387. depth = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8388. _color1.setRGB( depth, depth, depth );
  8389. depth = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far )
  8390. _color2.setRGB( depth, depth, depth );
  8391. depth = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8392. _color3.setRGB( depth, depth, depth );
  8393. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8394. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8395. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8396. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8397. var normal;
  8398. if ( material.shading == THREE.FlatShading ) {
  8399. normal = element.normalModelView;
  8400. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8401. material.wireframe === true
  8402. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8403. : fillPath( _color );
  8404. } else if ( material.shading == THREE.SmoothShading ) {
  8405. normal = element.vertexNormalsModelView[ uv1 ];
  8406. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8407. normal = element.vertexNormalsModelView[ uv2 ];
  8408. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8409. normal = element.vertexNormalsModelView[ uv3 ];
  8410. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8411. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8412. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8413. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8414. }
  8415. }
  8416. }
  8417. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  8418. _this.info.render.vertices += 4;
  8419. _this.info.render.faces ++;
  8420. setOpacity( material.opacity );
  8421. setBlending( material.blending );
  8422. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8423. // Let renderFace3() handle this
  8424. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  8425. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  8426. return;
  8427. }
  8428. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8429. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8430. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8431. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8432. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8433. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8434. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8435. _diffuseColor.copy( material.color );
  8436. _emissiveColor.copy( material.emissive );
  8437. if ( material.vertexColors === THREE.FaceColors ) {
  8438. _diffuseColor.multiply( element.color );
  8439. }
  8440. if ( _enableLighting === true ) {
  8441. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8442. _color1.copy( _ambientLight );
  8443. _color2.copy( _ambientLight );
  8444. _color3.copy( _ambientLight );
  8445. _color4.copy( _ambientLight );
  8446. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8447. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8448. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8449. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8450. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8451. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8452. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8453. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8454. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8455. // TODO: UVs are incorrect, v4->v3?
  8456. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8457. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8458. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8459. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8460. } else {
  8461. _color.copy( _ambientLight );
  8462. calculateLight( element.centroidModel, element.normalModel, _color );
  8463. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8464. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8465. material.wireframe === true
  8466. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8467. : fillPath( _color );
  8468. }
  8469. } else {
  8470. _color.addColors( _diffuseColor, _emissiveColor );
  8471. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8472. material.wireframe === true
  8473. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8474. : fillPath( _color );
  8475. }
  8476. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8477. _color.copy( material.color );
  8478. if ( material.vertexColors === THREE.FaceColors ) {
  8479. _color.multiply( element.color );
  8480. }
  8481. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8482. material.wireframe === true
  8483. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8484. : fillPath( _color );
  8485. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8486. var normal;
  8487. if ( material.shading == THREE.FlatShading ) {
  8488. normal = element.normalModelView;
  8489. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8490. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8491. material.wireframe === true
  8492. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8493. : fillPath( _color );
  8494. } else if ( material.shading == THREE.SmoothShading ) {
  8495. normal = element.vertexNormalsModelView[ 0 ];
  8496. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8497. normal = element.vertexNormalsModelView[ 1 ];
  8498. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8499. normal = element.vertexNormalsModelView[ 3 ];
  8500. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8501. normal = element.vertexNormalsModelView[ 2 ];
  8502. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8503. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8504. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8505. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8506. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8507. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8508. }
  8509. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8510. _near = camera.near;
  8511. _far = camera.far;
  8512. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8513. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8514. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  8515. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8516. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8517. // TODO: UVs are incorrect, v4->v3?
  8518. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8519. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8520. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8521. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8522. }
  8523. }
  8524. //
  8525. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8526. _context.beginPath();
  8527. _context.moveTo( x0, y0 );
  8528. _context.lineTo( x1, y1 );
  8529. _context.lineTo( x2, y2 );
  8530. _context.closePath();
  8531. }
  8532. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8533. _context.beginPath();
  8534. _context.moveTo( x0, y0 );
  8535. _context.lineTo( x1, y1 );
  8536. _context.lineTo( x2, y2 );
  8537. _context.lineTo( x3, y3 );
  8538. _context.closePath();
  8539. }
  8540. function strokePath( color, linewidth, linecap, linejoin ) {
  8541. setLineWidth( linewidth );
  8542. setLineCap( linecap );
  8543. setLineJoin( linejoin );
  8544. setStrokeStyle( color.getStyle() );
  8545. _context.stroke();
  8546. _elemBox.expandByScalar( linewidth * 2 );
  8547. }
  8548. function fillPath( color ) {
  8549. setFillStyle( color.getStyle() );
  8550. _context.fill();
  8551. }
  8552. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8553. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8554. if ( texture.needsUpdate === true ) {
  8555. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8556. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8557. _patterns[ texture.id ] = _context.createPattern(
  8558. texture.image, repeatX === true && repeatY === true
  8559. ? 'repeat'
  8560. : repeatX === true && repeatY === false
  8561. ? 'repeat-x'
  8562. : repeatX === false && repeatY === true
  8563. ? 'repeat-y'
  8564. : 'no-repeat'
  8565. );
  8566. texture.needsUpdate = false;
  8567. }
  8568. _patterns[ texture.id ] === undefined
  8569. ? setFillStyle( 'rgba(0,0,0,1)' )
  8570. : setFillStyle( _patterns[ texture.id ] );
  8571. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8572. var a, b, c, d, e, f, det, idet,
  8573. offsetX = texture.offset.x / texture.repeat.x,
  8574. offsetY = texture.offset.y / texture.repeat.y,
  8575. width = texture.image.width * texture.repeat.x,
  8576. height = texture.image.height * texture.repeat.y;
  8577. u0 = ( u0 + offsetX ) * width;
  8578. v0 = ( 1.0 - v0 + offsetY ) * height;
  8579. u1 = ( u1 + offsetX ) * width;
  8580. v1 = ( 1.0 - v1 + offsetY ) * height;
  8581. u2 = ( u2 + offsetX ) * width;
  8582. v2 = ( 1.0 - v2 + offsetY ) * height;
  8583. x1 -= x0; y1 -= y0;
  8584. x2 -= x0; y2 -= y0;
  8585. u1 -= u0; v1 -= v0;
  8586. u2 -= u0; v2 -= v0;
  8587. det = u1 * v2 - u2 * v1;
  8588. if ( det === 0 ) {
  8589. if ( _imagedatas[ texture.id ] === undefined ) {
  8590. var canvas = document.createElement( 'canvas' )
  8591. canvas.width = texture.image.width;
  8592. canvas.height = texture.image.height;
  8593. var context = canvas.getContext( '2d' );
  8594. context.drawImage( texture.image, 0, 0 );
  8595. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8596. }
  8597. var data = _imagedatas[ texture.id ];
  8598. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8599. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8600. fillPath( _color );
  8601. return;
  8602. }
  8603. idet = 1 / det;
  8604. a = ( v2 * x1 - v1 * x2 ) * idet;
  8605. b = ( v2 * y1 - v1 * y2 ) * idet;
  8606. c = ( u1 * x2 - u2 * x1 ) * idet;
  8607. d = ( u1 * y2 - u2 * y1 ) * idet;
  8608. e = x0 - a * u0 - c * v0;
  8609. f = y0 - b * u0 - d * v0;
  8610. _context.save();
  8611. _context.transform( a, b, c, d, e, f );
  8612. _context.fill();
  8613. _context.restore();
  8614. }
  8615. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8616. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8617. var a, b, c, d, e, f, det, idet,
  8618. width = image.width - 1,
  8619. height = image.height - 1;
  8620. u0 *= width; v0 *= height;
  8621. u1 *= width; v1 *= height;
  8622. u2 *= width; v2 *= height;
  8623. x1 -= x0; y1 -= y0;
  8624. x2 -= x0; y2 -= y0;
  8625. u1 -= u0; v1 -= v0;
  8626. u2 -= u0; v2 -= v0;
  8627. det = u1 * v2 - u2 * v1;
  8628. idet = 1 / det;
  8629. a = ( v2 * x1 - v1 * x2 ) * idet;
  8630. b = ( v2 * y1 - v1 * y2 ) * idet;
  8631. c = ( u1 * x2 - u2 * x1 ) * idet;
  8632. d = ( u1 * y2 - u2 * y1 ) * idet;
  8633. e = x0 - a * u0 - c * v0;
  8634. f = y0 - b * u0 - d * v0;
  8635. _context.save();
  8636. _context.transform( a, b, c, d, e, f );
  8637. _context.clip();
  8638. _context.drawImage( image, 0, 0 );
  8639. _context.restore();
  8640. }
  8641. function getGradientTexture( color1, color2, color3, color4 ) {
  8642. // http://mrdoob.com/blog/post/710
  8643. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8644. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8645. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8646. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8647. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8648. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8649. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8650. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8651. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8652. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8653. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8654. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8655. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8656. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8657. return _gradientMap;
  8658. }
  8659. function smoothstep( value, min, max ) {
  8660. var x = ( value - min ) / ( max - min );
  8661. return x * x * ( 3 - 2 * x );
  8662. }
  8663. // Hide anti-alias gaps
  8664. function expand( v1, v2 ) {
  8665. var x = v2.x - v1.x, y = v2.y - v1.y,
  8666. det = x * x + y * y, idet;
  8667. if ( det === 0 ) return;
  8668. idet = 1 / Math.sqrt( det );
  8669. x *= idet; y *= idet;
  8670. v2.x += x; v2.y += y;
  8671. v1.x -= x; v1.y -= y;
  8672. }
  8673. };
  8674. // Context cached methods.
  8675. function setOpacity( value ) {
  8676. if ( _contextGlobalAlpha !== value ) {
  8677. _context.globalAlpha = value;
  8678. _contextGlobalAlpha = value;
  8679. }
  8680. }
  8681. function setBlending( value ) {
  8682. if ( _contextGlobalCompositeOperation !== value ) {
  8683. if ( value === THREE.NormalBlending ) {
  8684. _context.globalCompositeOperation = 'source-over';
  8685. } else if ( value === THREE.AdditiveBlending ) {
  8686. _context.globalCompositeOperation = 'lighter';
  8687. } else if ( value === THREE.SubtractiveBlending ) {
  8688. _context.globalCompositeOperation = 'darker';
  8689. }
  8690. _contextGlobalCompositeOperation = value;
  8691. }
  8692. }
  8693. function setLineWidth( value ) {
  8694. if ( _contextLineWidth !== value ) {
  8695. _context.lineWidth = value;
  8696. _contextLineWidth = value;
  8697. }
  8698. }
  8699. function setLineCap( value ) {
  8700. // "butt", "round", "square"
  8701. if ( _contextLineCap !== value ) {
  8702. _context.lineCap = value;
  8703. _contextLineCap = value;
  8704. }
  8705. }
  8706. function setLineJoin( value ) {
  8707. // "round", "bevel", "miter"
  8708. if ( _contextLineJoin !== value ) {
  8709. _context.lineJoin = value;
  8710. _contextLineJoin = value;
  8711. }
  8712. }
  8713. function setStrokeStyle( value ) {
  8714. if ( _contextStrokeStyle !== value ) {
  8715. _context.strokeStyle = value;
  8716. _contextStrokeStyle = value;
  8717. }
  8718. }
  8719. function setFillStyle( value ) {
  8720. if ( _contextFillStyle !== value ) {
  8721. _context.fillStyle = value;
  8722. _contextFillStyle = value;
  8723. }
  8724. }
  8725. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  8726. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  8727. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  8728. _contextDashSize = dashSizeValue;
  8729. _contextGapSize = gapSizeValue;
  8730. }
  8731. }
  8732. };
  8733. /**
  8734. * @author alteredq / http://alteredqualia.com/
  8735. * @author mrdoob / http://mrdoob.com/
  8736. * @author mikael emtinger / http://gomo.se/
  8737. */
  8738. THREE.ShaderChunk = {
  8739. // FOG
  8740. fog_pars_fragment: [
  8741. "#ifdef USE_FOG",
  8742. "uniform vec3 fogColor;",
  8743. "#ifdef FOG_EXP2",
  8744. "uniform float fogDensity;",
  8745. "#else",
  8746. "uniform float fogNear;",
  8747. "uniform float fogFar;",
  8748. "#endif",
  8749. "#endif"
  8750. ].join("\n"),
  8751. fog_fragment: [
  8752. "#ifdef USE_FOG",
  8753. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8754. "#ifdef FOG_EXP2",
  8755. "const float LOG2 = 1.442695;",
  8756. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8757. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8758. "#else",
  8759. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8760. "#endif",
  8761. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8762. "#endif"
  8763. ].join("\n"),
  8764. // ENVIRONMENT MAP
  8765. envmap_pars_fragment: [
  8766. "#ifdef USE_ENVMAP",
  8767. "uniform float reflectivity;",
  8768. "uniform samplerCube envMap;",
  8769. "uniform float flipEnvMap;",
  8770. "uniform int combine;",
  8771. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8772. "uniform bool useRefract;",
  8773. "uniform float refractionRatio;",
  8774. "#else",
  8775. "varying vec3 vReflect;",
  8776. "#endif",
  8777. "#endif"
  8778. ].join("\n"),
  8779. envmap_fragment: [
  8780. "#ifdef USE_ENVMAP",
  8781. "vec3 reflectVec;",
  8782. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8783. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8784. "if ( useRefract ) {",
  8785. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8786. "} else { ",
  8787. "reflectVec = reflect( cameraToVertex, normal );",
  8788. "}",
  8789. "#else",
  8790. "reflectVec = vReflect;",
  8791. "#endif",
  8792. "#ifdef DOUBLE_SIDED",
  8793. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8794. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8795. "#else",
  8796. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8797. "#endif",
  8798. "#ifdef GAMMA_INPUT",
  8799. "cubeColor.xyz *= cubeColor.xyz;",
  8800. "#endif",
  8801. "if ( combine == 1 ) {",
  8802. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8803. "} else if ( combine == 2 ) {",
  8804. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8805. "} else {",
  8806. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8807. "}",
  8808. "#endif"
  8809. ].join("\n"),
  8810. envmap_pars_vertex: [
  8811. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8812. "varying vec3 vReflect;",
  8813. "uniform float refractionRatio;",
  8814. "uniform bool useRefract;",
  8815. "#endif"
  8816. ].join("\n"),
  8817. worldpos_vertex : [
  8818. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8819. "#ifdef USE_SKINNING",
  8820. "vec4 worldPosition = modelMatrix * skinned;",
  8821. "#endif",
  8822. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8823. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8824. "#endif",
  8825. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8826. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8827. "#endif",
  8828. "#endif"
  8829. ].join("\n"),
  8830. envmap_vertex : [
  8831. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8832. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8833. "worldNormal = normalize( worldNormal );",
  8834. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8835. "if ( useRefract ) {",
  8836. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8837. "} else {",
  8838. "vReflect = reflect( cameraToVertex, worldNormal );",
  8839. "}",
  8840. "#endif"
  8841. ].join("\n"),
  8842. // COLOR MAP (particles)
  8843. map_particle_pars_fragment: [
  8844. "#ifdef USE_MAP",
  8845. "uniform sampler2D map;",
  8846. "#endif"
  8847. ].join("\n"),
  8848. map_particle_fragment: [
  8849. "#ifdef USE_MAP",
  8850. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8851. "#endif"
  8852. ].join("\n"),
  8853. // COLOR MAP (triangles)
  8854. map_pars_vertex: [
  8855. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8856. "varying vec2 vUv;",
  8857. "uniform vec4 offsetRepeat;",
  8858. "#endif"
  8859. ].join("\n"),
  8860. map_pars_fragment: [
  8861. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8862. "varying vec2 vUv;",
  8863. "#endif",
  8864. "#ifdef USE_MAP",
  8865. "uniform sampler2D map;",
  8866. "#endif"
  8867. ].join("\n"),
  8868. map_vertex: [
  8869. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8870. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8871. "#endif"
  8872. ].join("\n"),
  8873. map_fragment: [
  8874. "#ifdef USE_MAP",
  8875. "vec4 texelColor = texture2D( map, vUv );",
  8876. "#ifdef GAMMA_INPUT",
  8877. "texelColor.xyz *= texelColor.xyz;",
  8878. "#endif",
  8879. "gl_FragColor = gl_FragColor * texelColor;",
  8880. "#endif"
  8881. ].join("\n"),
  8882. // LIGHT MAP
  8883. lightmap_pars_fragment: [
  8884. "#ifdef USE_LIGHTMAP",
  8885. "varying vec2 vUv2;",
  8886. "uniform sampler2D lightMap;",
  8887. "#endif"
  8888. ].join("\n"),
  8889. lightmap_pars_vertex: [
  8890. "#ifdef USE_LIGHTMAP",
  8891. "varying vec2 vUv2;",
  8892. "#endif"
  8893. ].join("\n"),
  8894. lightmap_fragment: [
  8895. "#ifdef USE_LIGHTMAP",
  8896. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8897. "#endif"
  8898. ].join("\n"),
  8899. lightmap_vertex: [
  8900. "#ifdef USE_LIGHTMAP",
  8901. "vUv2 = uv2;",
  8902. "#endif"
  8903. ].join("\n"),
  8904. // BUMP MAP
  8905. bumpmap_pars_fragment: [
  8906. "#ifdef USE_BUMPMAP",
  8907. "uniform sampler2D bumpMap;",
  8908. "uniform float bumpScale;",
  8909. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8910. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8911. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8912. "vec2 dHdxy_fwd() {",
  8913. "vec2 dSTdx = dFdx( vUv );",
  8914. "vec2 dSTdy = dFdy( vUv );",
  8915. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8916. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8917. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8918. "return vec2( dBx, dBy );",
  8919. "}",
  8920. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8921. "vec3 vSigmaX = dFdx( surf_pos );",
  8922. "vec3 vSigmaY = dFdy( surf_pos );",
  8923. "vec3 vN = surf_norm;", // normalized
  8924. "vec3 R1 = cross( vSigmaY, vN );",
  8925. "vec3 R2 = cross( vN, vSigmaX );",
  8926. "float fDet = dot( vSigmaX, R1 );",
  8927. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8928. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8929. "}",
  8930. "#endif"
  8931. ].join("\n"),
  8932. // NORMAL MAP
  8933. normalmap_pars_fragment: [
  8934. "#ifdef USE_NORMALMAP",
  8935. "uniform sampler2D normalMap;",
  8936. "uniform vec2 normalScale;",
  8937. // Per-Pixel Tangent Space Normal Mapping
  8938. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8939. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8940. "vec3 q0 = dFdx( eye_pos.xyz );",
  8941. "vec3 q1 = dFdy( eye_pos.xyz );",
  8942. "vec2 st0 = dFdx( vUv.st );",
  8943. "vec2 st1 = dFdy( vUv.st );",
  8944. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8945. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8946. "vec3 N = normalize( surf_norm );",
  8947. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8948. "mapN.xy = normalScale * mapN.xy;",
  8949. "mat3 tsn = mat3( S, T, N );",
  8950. "return normalize( tsn * mapN );",
  8951. "}",
  8952. "#endif"
  8953. ].join("\n"),
  8954. // SPECULAR MAP
  8955. specularmap_pars_fragment: [
  8956. "#ifdef USE_SPECULARMAP",
  8957. "uniform sampler2D specularMap;",
  8958. "#endif"
  8959. ].join("\n"),
  8960. specularmap_fragment: [
  8961. "float specularStrength;",
  8962. "#ifdef USE_SPECULARMAP",
  8963. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8964. "specularStrength = texelSpecular.r;",
  8965. "#else",
  8966. "specularStrength = 1.0;",
  8967. "#endif"
  8968. ].join("\n"),
  8969. // LIGHTS LAMBERT
  8970. lights_lambert_pars_vertex: [
  8971. "uniform vec3 ambient;",
  8972. "uniform vec3 diffuse;",
  8973. "uniform vec3 emissive;",
  8974. "uniform vec3 ambientLightColor;",
  8975. "#if MAX_DIR_LIGHTS > 0",
  8976. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8977. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8978. "#endif",
  8979. "#if MAX_HEMI_LIGHTS > 0",
  8980. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8981. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8982. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8983. "#endif",
  8984. "#if MAX_POINT_LIGHTS > 0",
  8985. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8986. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8987. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8988. "#endif",
  8989. "#if MAX_SPOT_LIGHTS > 0",
  8990. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8991. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8992. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8993. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8994. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8995. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8996. "#endif",
  8997. "#ifdef WRAP_AROUND",
  8998. "uniform vec3 wrapRGB;",
  8999. "#endif"
  9000. ].join("\n"),
  9001. lights_lambert_vertex: [
  9002. "vLightFront = vec3( 0.0 );",
  9003. "#ifdef DOUBLE_SIDED",
  9004. "vLightBack = vec3( 0.0 );",
  9005. "#endif",
  9006. "transformedNormal = normalize( transformedNormal );",
  9007. "#if MAX_DIR_LIGHTS > 0",
  9008. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9009. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9010. "vec3 dirVector = normalize( lDirection.xyz );",
  9011. "float dotProduct = dot( transformedNormal, dirVector );",
  9012. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9013. "#ifdef DOUBLE_SIDED",
  9014. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9015. "#ifdef WRAP_AROUND",
  9016. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9017. "#endif",
  9018. "#endif",
  9019. "#ifdef WRAP_AROUND",
  9020. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9021. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9022. "#ifdef DOUBLE_SIDED",
  9023. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9024. "#endif",
  9025. "#endif",
  9026. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9027. "#ifdef DOUBLE_SIDED",
  9028. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9029. "#endif",
  9030. "}",
  9031. "#endif",
  9032. "#if MAX_POINT_LIGHTS > 0",
  9033. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9034. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9035. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9036. "float lDistance = 1.0;",
  9037. "if ( pointLightDistance[ i ] > 0.0 )",
  9038. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9039. "lVector = normalize( lVector );",
  9040. "float dotProduct = dot( transformedNormal, lVector );",
  9041. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9042. "#ifdef DOUBLE_SIDED",
  9043. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9044. "#ifdef WRAP_AROUND",
  9045. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9046. "#endif",
  9047. "#endif",
  9048. "#ifdef WRAP_AROUND",
  9049. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9050. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9051. "#ifdef DOUBLE_SIDED",
  9052. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9053. "#endif",
  9054. "#endif",
  9055. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9056. "#ifdef DOUBLE_SIDED",
  9057. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9058. "#endif",
  9059. "}",
  9060. "#endif",
  9061. "#if MAX_SPOT_LIGHTS > 0",
  9062. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9063. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9064. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9065. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9066. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9067. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9068. "float lDistance = 1.0;",
  9069. "if ( spotLightDistance[ i ] > 0.0 )",
  9070. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9071. "lVector = normalize( lVector );",
  9072. "float dotProduct = dot( transformedNormal, lVector );",
  9073. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9074. "#ifdef DOUBLE_SIDED",
  9075. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9076. "#ifdef WRAP_AROUND",
  9077. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9078. "#endif",
  9079. "#endif",
  9080. "#ifdef WRAP_AROUND",
  9081. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9082. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9083. "#ifdef DOUBLE_SIDED",
  9084. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9085. "#endif",
  9086. "#endif",
  9087. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9088. "#ifdef DOUBLE_SIDED",
  9089. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9090. "#endif",
  9091. "}",
  9092. "}",
  9093. "#endif",
  9094. "#if MAX_HEMI_LIGHTS > 0",
  9095. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9096. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9097. "vec3 lVector = normalize( lDirection.xyz );",
  9098. "float dotProduct = dot( transformedNormal, lVector );",
  9099. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9100. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9101. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9102. "#ifdef DOUBLE_SIDED",
  9103. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9104. "#endif",
  9105. "}",
  9106. "#endif",
  9107. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9108. "#ifdef DOUBLE_SIDED",
  9109. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9110. "#endif"
  9111. ].join("\n"),
  9112. // LIGHTS PHONG
  9113. lights_phong_pars_vertex: [
  9114. "#ifndef PHONG_PER_PIXEL",
  9115. "#if MAX_POINT_LIGHTS > 0",
  9116. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9117. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9118. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9119. "#endif",
  9120. "#if MAX_SPOT_LIGHTS > 0",
  9121. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9122. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9123. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9124. "#endif",
  9125. "#endif",
  9126. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9127. "varying vec3 vWorldPosition;",
  9128. "#endif"
  9129. ].join("\n"),
  9130. lights_phong_vertex: [
  9131. "#ifndef PHONG_PER_PIXEL",
  9132. "#if MAX_POINT_LIGHTS > 0",
  9133. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9134. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9135. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9136. "float lDistance = 1.0;",
  9137. "if ( pointLightDistance[ i ] > 0.0 )",
  9138. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9139. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9140. "}",
  9141. "#endif",
  9142. "#if MAX_SPOT_LIGHTS > 0",
  9143. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9144. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9145. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9146. "float lDistance = 1.0;",
  9147. "if ( spotLightDistance[ i ] > 0.0 )",
  9148. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9149. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9150. "}",
  9151. "#endif",
  9152. "#endif",
  9153. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9154. "vWorldPosition = worldPosition.xyz;",
  9155. "#endif"
  9156. ].join("\n"),
  9157. lights_phong_pars_fragment: [
  9158. "uniform vec3 ambientLightColor;",
  9159. "#if MAX_DIR_LIGHTS > 0",
  9160. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9161. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9162. "#endif",
  9163. "#if MAX_HEMI_LIGHTS > 0",
  9164. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9165. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9166. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9167. "#endif",
  9168. "#if MAX_POINT_LIGHTS > 0",
  9169. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9170. "#ifdef PHONG_PER_PIXEL",
  9171. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9172. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9173. "#else",
  9174. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9175. "#endif",
  9176. "#endif",
  9177. "#if MAX_SPOT_LIGHTS > 0",
  9178. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9179. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9180. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9181. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9182. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9183. "#ifdef PHONG_PER_PIXEL",
  9184. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9185. "#else",
  9186. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9187. "#endif",
  9188. "#endif",
  9189. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9190. "varying vec3 vWorldPosition;",
  9191. "#endif",
  9192. "#ifdef WRAP_AROUND",
  9193. "uniform vec3 wrapRGB;",
  9194. "#endif",
  9195. "varying vec3 vViewPosition;",
  9196. "varying vec3 vNormal;"
  9197. ].join("\n"),
  9198. lights_phong_fragment: [
  9199. "vec3 normal = normalize( vNormal );",
  9200. "vec3 viewPosition = normalize( vViewPosition );",
  9201. "#ifdef DOUBLE_SIDED",
  9202. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9203. "#endif",
  9204. "#ifdef USE_NORMALMAP",
  9205. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9206. "#elif defined( USE_BUMPMAP )",
  9207. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9208. "#endif",
  9209. "#if MAX_POINT_LIGHTS > 0",
  9210. "vec3 pointDiffuse = vec3( 0.0 );",
  9211. "vec3 pointSpecular = vec3( 0.0 );",
  9212. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9213. "#ifdef PHONG_PER_PIXEL",
  9214. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9215. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9216. "float lDistance = 1.0;",
  9217. "if ( pointLightDistance[ i ] > 0.0 )",
  9218. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9219. "lVector = normalize( lVector );",
  9220. "#else",
  9221. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9222. "float lDistance = vPointLight[ i ].w;",
  9223. "#endif",
  9224. // diffuse
  9225. "float dotProduct = dot( normal, lVector );",
  9226. "#ifdef WRAP_AROUND",
  9227. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9228. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9229. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9230. "#else",
  9231. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9232. "#endif",
  9233. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9234. // specular
  9235. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9236. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9237. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9238. "#ifdef PHYSICALLY_BASED_SHADING",
  9239. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9240. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9241. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9242. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9243. "#else",
  9244. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9245. "#endif",
  9246. "}",
  9247. "#endif",
  9248. "#if MAX_SPOT_LIGHTS > 0",
  9249. "vec3 spotDiffuse = vec3( 0.0 );",
  9250. "vec3 spotSpecular = vec3( 0.0 );",
  9251. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9252. "#ifdef PHONG_PER_PIXEL",
  9253. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9254. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9255. "float lDistance = 1.0;",
  9256. "if ( spotLightDistance[ i ] > 0.0 )",
  9257. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9258. "lVector = normalize( lVector );",
  9259. "#else",
  9260. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9261. "float lDistance = vSpotLight[ i ].w;",
  9262. "#endif",
  9263. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9264. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9265. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9266. // diffuse
  9267. "float dotProduct = dot( normal, lVector );",
  9268. "#ifdef WRAP_AROUND",
  9269. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9270. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9271. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9272. "#else",
  9273. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9274. "#endif",
  9275. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9276. // specular
  9277. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9278. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9279. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9280. "#ifdef PHYSICALLY_BASED_SHADING",
  9281. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9282. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9283. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9284. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9285. "#else",
  9286. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9287. "#endif",
  9288. "}",
  9289. "}",
  9290. "#endif",
  9291. "#if MAX_DIR_LIGHTS > 0",
  9292. "vec3 dirDiffuse = vec3( 0.0 );",
  9293. "vec3 dirSpecular = vec3( 0.0 );" ,
  9294. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9295. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9296. "vec3 dirVector = normalize( lDirection.xyz );",
  9297. // diffuse
  9298. "float dotProduct = dot( normal, dirVector );",
  9299. "#ifdef WRAP_AROUND",
  9300. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9301. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9302. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9303. "#else",
  9304. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9305. "#endif",
  9306. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9307. // specular
  9308. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9309. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9310. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9311. "#ifdef PHYSICALLY_BASED_SHADING",
  9312. /*
  9313. // fresnel term from skin shader
  9314. "const float F0 = 0.128;",
  9315. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9316. "float exponential = pow( base, 5.0 );",
  9317. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9318. */
  9319. /*
  9320. // fresnel term from fresnel shader
  9321. "const float mFresnelBias = 0.08;",
  9322. "const float mFresnelScale = 0.3;",
  9323. "const float mFresnelPower = 5.0;",
  9324. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9325. */
  9326. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9327. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9328. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9329. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9330. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9331. "#else",
  9332. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9333. "#endif",
  9334. "}",
  9335. "#endif",
  9336. "#if MAX_HEMI_LIGHTS > 0",
  9337. "vec3 hemiDiffuse = vec3( 0.0 );",
  9338. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9339. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9340. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9341. "vec3 lVector = normalize( lDirection.xyz );",
  9342. // diffuse
  9343. "float dotProduct = dot( normal, lVector );",
  9344. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9345. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9346. "hemiDiffuse += diffuse * hemiColor;",
  9347. // specular (sky light)
  9348. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9349. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9350. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9351. // specular (ground light)
  9352. "vec3 lVectorGround = -lVector;",
  9353. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9354. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9355. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9356. "#ifdef PHYSICALLY_BASED_SHADING",
  9357. "float dotProductGround = dot( normal, lVectorGround );",
  9358. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9359. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9360. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9361. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9362. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9363. "#else",
  9364. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9365. "#endif",
  9366. "}",
  9367. "#endif",
  9368. "vec3 totalDiffuse = vec3( 0.0 );",
  9369. "vec3 totalSpecular = vec3( 0.0 );",
  9370. "#if MAX_DIR_LIGHTS > 0",
  9371. "totalDiffuse += dirDiffuse;",
  9372. "totalSpecular += dirSpecular;",
  9373. "#endif",
  9374. "#if MAX_HEMI_LIGHTS > 0",
  9375. "totalDiffuse += hemiDiffuse;",
  9376. "totalSpecular += hemiSpecular;",
  9377. "#endif",
  9378. "#if MAX_POINT_LIGHTS > 0",
  9379. "totalDiffuse += pointDiffuse;",
  9380. "totalSpecular += pointSpecular;",
  9381. "#endif",
  9382. "#if MAX_SPOT_LIGHTS > 0",
  9383. "totalDiffuse += spotDiffuse;",
  9384. "totalSpecular += spotSpecular;",
  9385. "#endif",
  9386. "#ifdef METAL",
  9387. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9388. "#else",
  9389. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9390. "#endif"
  9391. ].join("\n"),
  9392. // VERTEX COLORS
  9393. color_pars_fragment: [
  9394. "#ifdef USE_COLOR",
  9395. "varying vec3 vColor;",
  9396. "#endif"
  9397. ].join("\n"),
  9398. color_fragment: [
  9399. "#ifdef USE_COLOR",
  9400. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9401. "#endif"
  9402. ].join("\n"),
  9403. color_pars_vertex: [
  9404. "#ifdef USE_COLOR",
  9405. "varying vec3 vColor;",
  9406. "#endif"
  9407. ].join("\n"),
  9408. color_vertex: [
  9409. "#ifdef USE_COLOR",
  9410. "#ifdef GAMMA_INPUT",
  9411. "vColor = color * color;",
  9412. "#else",
  9413. "vColor = color;",
  9414. "#endif",
  9415. "#endif"
  9416. ].join("\n"),
  9417. // SKINNING
  9418. skinning_pars_vertex: [
  9419. "#ifdef USE_SKINNING",
  9420. "#ifdef BONE_TEXTURE",
  9421. "uniform sampler2D boneTexture;",
  9422. "mat4 getBoneMatrix( const in float i ) {",
  9423. "float j = i * 4.0;",
  9424. "float x = mod( j, N_BONE_PIXEL_X );",
  9425. "float y = floor( j / N_BONE_PIXEL_X );",
  9426. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9427. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9428. "y = dy * ( y + 0.5 );",
  9429. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9430. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9431. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9432. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9433. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9434. "return bone;",
  9435. "}",
  9436. "#else",
  9437. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9438. "mat4 getBoneMatrix( const in float i ) {",
  9439. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9440. "return bone;",
  9441. "}",
  9442. "#endif",
  9443. "#endif"
  9444. ].join("\n"),
  9445. skinbase_vertex: [
  9446. "#ifdef USE_SKINNING",
  9447. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9448. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9449. "#endif"
  9450. ].join("\n"),
  9451. skinning_vertex: [
  9452. "#ifdef USE_SKINNING",
  9453. "#ifdef USE_MORPHTARGETS",
  9454. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9455. "#else",
  9456. "vec4 skinVertex = vec4( position, 1.0 );",
  9457. "#endif",
  9458. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9459. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9460. "#endif"
  9461. ].join("\n"),
  9462. // MORPHING
  9463. morphtarget_pars_vertex: [
  9464. "#ifdef USE_MORPHTARGETS",
  9465. "#ifndef USE_MORPHNORMALS",
  9466. "uniform float morphTargetInfluences[ 8 ];",
  9467. "#else",
  9468. "uniform float morphTargetInfluences[ 4 ];",
  9469. "#endif",
  9470. "#endif"
  9471. ].join("\n"),
  9472. morphtarget_vertex: [
  9473. "#ifdef USE_MORPHTARGETS",
  9474. "vec3 morphed = vec3( 0.0 );",
  9475. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9476. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9477. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9478. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9479. "#ifndef USE_MORPHNORMALS",
  9480. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9481. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9482. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9483. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9484. "#endif",
  9485. "morphed += position;",
  9486. "#endif"
  9487. ].join("\n"),
  9488. default_vertex : [
  9489. "vec4 mvPosition;",
  9490. "#ifdef USE_SKINNING",
  9491. "mvPosition = modelViewMatrix * skinned;",
  9492. "#endif",
  9493. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9494. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9495. "#endif",
  9496. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9497. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9498. "#endif",
  9499. "gl_Position = projectionMatrix * mvPosition;"
  9500. ].join("\n"),
  9501. morphnormal_vertex: [
  9502. "#ifdef USE_MORPHNORMALS",
  9503. "vec3 morphedNormal = vec3( 0.0 );",
  9504. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9505. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9506. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9507. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9508. "morphedNormal += normal;",
  9509. "#endif"
  9510. ].join("\n"),
  9511. skinnormal_vertex: [
  9512. "#ifdef USE_SKINNING",
  9513. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9514. "skinMatrix += skinWeight.y * boneMatY;",
  9515. "#ifdef USE_MORPHNORMALS",
  9516. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9517. "#else",
  9518. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9519. "#endif",
  9520. "#endif"
  9521. ].join("\n"),
  9522. defaultnormal_vertex: [
  9523. "vec3 objectNormal;",
  9524. "#ifdef USE_SKINNING",
  9525. "objectNormal = skinnedNormal.xyz;",
  9526. "#endif",
  9527. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9528. "objectNormal = morphedNormal;",
  9529. "#endif",
  9530. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9531. "objectNormal = normal;",
  9532. "#endif",
  9533. "#ifdef FLIP_SIDED",
  9534. "objectNormal = -objectNormal;",
  9535. "#endif",
  9536. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9537. ].join("\n"),
  9538. // SHADOW MAP
  9539. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9540. // http://spidergl.org/example.php?id=6
  9541. // http://fabiensanglard.net/shadowmapping
  9542. shadowmap_pars_fragment: [
  9543. "#ifdef USE_SHADOWMAP",
  9544. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9545. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9546. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9547. "uniform float shadowBias[ MAX_SHADOWS ];",
  9548. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9549. "float unpackDepth( const in vec4 rgba_depth ) {",
  9550. "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 );",
  9551. "float depth = dot( rgba_depth, bit_shift );",
  9552. "return depth;",
  9553. "}",
  9554. "#endif"
  9555. ].join("\n"),
  9556. shadowmap_fragment: [
  9557. "#ifdef USE_SHADOWMAP",
  9558. "#ifdef SHADOWMAP_DEBUG",
  9559. "vec3 frustumColors[3];",
  9560. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9561. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9562. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9563. "#endif",
  9564. "#ifdef SHADOWMAP_CASCADE",
  9565. "int inFrustumCount = 0;",
  9566. "#endif",
  9567. "float fDepth;",
  9568. "vec3 shadowColor = vec3( 1.0 );",
  9569. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9570. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9571. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9572. // "if ( all( something, something ) )" using this instead
  9573. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9574. "bool inFrustum = all( inFrustumVec );",
  9575. // don't shadow pixels outside of light frustum
  9576. // use just first frustum (for cascades)
  9577. // don't shadow pixels behind far plane of light frustum
  9578. "#ifdef SHADOWMAP_CASCADE",
  9579. "inFrustumCount += int( inFrustum );",
  9580. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9581. "#else",
  9582. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9583. "#endif",
  9584. "bool frustumTest = all( frustumTestVec );",
  9585. "if ( frustumTest ) {",
  9586. "shadowCoord.z += shadowBias[ i ];",
  9587. "#if defined( SHADOWMAP_TYPE_PCF )",
  9588. // Percentage-close filtering
  9589. // (9 pixel kernel)
  9590. // http://fabiensanglard.net/shadowmappingPCF/
  9591. "float shadow = 0.0;",
  9592. /*
  9593. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9594. // must enroll loop manually
  9595. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9596. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9597. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9598. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9599. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9600. "float fDepth = unpackDepth( rgbaDepth );",
  9601. "if ( fDepth < shadowCoord.z )",
  9602. "shadow += 1.0;",
  9603. "}",
  9604. "shadow /= 9.0;",
  9605. */
  9606. "const float shadowDelta = 1.0 / 9.0;",
  9607. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9608. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9609. "float dx0 = -1.25 * xPixelOffset;",
  9610. "float dy0 = -1.25 * yPixelOffset;",
  9611. "float dx1 = 1.25 * xPixelOffset;",
  9612. "float dy1 = 1.25 * yPixelOffset;",
  9613. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9614. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9615. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9616. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9617. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9618. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9619. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9620. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9621. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9622. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9623. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9624. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9625. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9626. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9627. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9628. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9629. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9630. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9631. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9632. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9633. // Percentage-close filtering
  9634. // (9 pixel kernel)
  9635. // http://fabiensanglard.net/shadowmappingPCF/
  9636. "float shadow = 0.0;",
  9637. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9638. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9639. "float dx0 = -1.0 * xPixelOffset;",
  9640. "float dy0 = -1.0 * yPixelOffset;",
  9641. "float dx1 = 1.0 * xPixelOffset;",
  9642. "float dy1 = 1.0 * yPixelOffset;",
  9643. "mat3 shadowKernel;",
  9644. "mat3 depthKernel;",
  9645. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9646. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9647. "else shadowKernel[0][0] = 0.0;",
  9648. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9649. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9650. "else shadowKernel[0][1] = 0.0;",
  9651. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9652. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9653. "else shadowKernel[0][2] = 0.0;",
  9654. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9655. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9656. "else shadowKernel[1][0] = 0.0;",
  9657. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9658. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9659. "else shadowKernel[1][1] = 0.0;",
  9660. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9661. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9662. "else shadowKernel[1][2] = 0.0;",
  9663. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9664. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9665. "else shadowKernel[2][0] = 0.0;",
  9666. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9667. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9668. "else shadowKernel[2][1] = 0.0;",
  9669. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9670. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9671. "else shadowKernel[2][2] = 0.0;",
  9672. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9673. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9674. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9675. "vec4 shadowValues;",
  9676. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9677. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9678. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9679. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9680. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9681. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9682. "#else",
  9683. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9684. "float fDepth = unpackDepth( rgbaDepth );",
  9685. "if ( fDepth < shadowCoord.z )",
  9686. // spot with multiple shadows is darker
  9687. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9688. // spot with multiple shadows has the same color as single shadow spot
  9689. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9690. "#endif",
  9691. "}",
  9692. "#ifdef SHADOWMAP_DEBUG",
  9693. "#ifdef SHADOWMAP_CASCADE",
  9694. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9695. "#else",
  9696. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9697. "#endif",
  9698. "#endif",
  9699. "}",
  9700. "#ifdef GAMMA_OUTPUT",
  9701. "shadowColor *= shadowColor;",
  9702. "#endif",
  9703. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9704. "#endif"
  9705. ].join("\n"),
  9706. shadowmap_pars_vertex: [
  9707. "#ifdef USE_SHADOWMAP",
  9708. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9709. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9710. "#endif"
  9711. ].join("\n"),
  9712. shadowmap_vertex: [
  9713. "#ifdef USE_SHADOWMAP",
  9714. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9715. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9716. "}",
  9717. "#endif"
  9718. ].join("\n"),
  9719. // ALPHATEST
  9720. alphatest_fragment: [
  9721. "#ifdef ALPHATEST",
  9722. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9723. "#endif"
  9724. ].join("\n"),
  9725. // LINEAR SPACE
  9726. linear_to_gamma_fragment: [
  9727. "#ifdef GAMMA_OUTPUT",
  9728. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9729. "#endif"
  9730. ].join("\n")
  9731. };
  9732. THREE.UniformsUtils = {
  9733. merge: function ( uniforms ) {
  9734. var u, p, tmp, merged = {};
  9735. for ( u = 0; u < uniforms.length; u ++ ) {
  9736. tmp = this.clone( uniforms[ u ] );
  9737. for ( p in tmp ) {
  9738. merged[ p ] = tmp[ p ];
  9739. }
  9740. }
  9741. return merged;
  9742. },
  9743. clone: function ( uniforms_src ) {
  9744. var u, p, parameter, parameter_src, uniforms_dst = {};
  9745. for ( u in uniforms_src ) {
  9746. uniforms_dst[ u ] = {};
  9747. for ( p in uniforms_src[ u ] ) {
  9748. parameter_src = uniforms_src[ u ][ p ];
  9749. if ( parameter_src instanceof THREE.Color ||
  9750. parameter_src instanceof THREE.Vector2 ||
  9751. parameter_src instanceof THREE.Vector3 ||
  9752. parameter_src instanceof THREE.Vector4 ||
  9753. parameter_src instanceof THREE.Matrix4 ||
  9754. parameter_src instanceof THREE.Texture ) {
  9755. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9756. } else if ( parameter_src instanceof Array ) {
  9757. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9758. } else {
  9759. uniforms_dst[ u ][ p ] = parameter_src;
  9760. }
  9761. }
  9762. }
  9763. return uniforms_dst;
  9764. }
  9765. };
  9766. THREE.UniformsLib = {
  9767. common: {
  9768. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9769. "opacity" : { type: "f", value: 1.0 },
  9770. "map" : { type: "t", value: null },
  9771. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9772. "lightMap" : { type: "t", value: null },
  9773. "specularMap" : { type: "t", value: null },
  9774. "envMap" : { type: "t", value: null },
  9775. "flipEnvMap" : { type: "f", value: -1 },
  9776. "useRefract" : { type: "i", value: 0 },
  9777. "reflectivity" : { type: "f", value: 1.0 },
  9778. "refractionRatio" : { type: "f", value: 0.98 },
  9779. "combine" : { type: "i", value: 0 },
  9780. "morphTargetInfluences" : { type: "f", value: 0 }
  9781. },
  9782. bump: {
  9783. "bumpMap" : { type: "t", value: null },
  9784. "bumpScale" : { type: "f", value: 1 }
  9785. },
  9786. normalmap: {
  9787. "normalMap" : { type: "t", value: null },
  9788. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9789. },
  9790. fog : {
  9791. "fogDensity" : { type: "f", value: 0.00025 },
  9792. "fogNear" : { type: "f", value: 1 },
  9793. "fogFar" : { type: "f", value: 2000 },
  9794. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9795. },
  9796. lights: {
  9797. "ambientLightColor" : { type: "fv", value: [] },
  9798. "directionalLightDirection" : { type: "fv", value: [] },
  9799. "directionalLightColor" : { type: "fv", value: [] },
  9800. "hemisphereLightDirection" : { type: "fv", value: [] },
  9801. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9802. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9803. "pointLightColor" : { type: "fv", value: [] },
  9804. "pointLightPosition" : { type: "fv", value: [] },
  9805. "pointLightDistance" : { type: "fv1", value: [] },
  9806. "spotLightColor" : { type: "fv", value: [] },
  9807. "spotLightPosition" : { type: "fv", value: [] },
  9808. "spotLightDirection" : { type: "fv", value: [] },
  9809. "spotLightDistance" : { type: "fv1", value: [] },
  9810. "spotLightAngleCos" : { type: "fv1", value: [] },
  9811. "spotLightExponent" : { type: "fv1", value: [] }
  9812. },
  9813. particle: {
  9814. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9815. "opacity" : { type: "f", value: 1.0 },
  9816. "size" : { type: "f", value: 1.0 },
  9817. "scale" : { type: "f", value: 1.0 },
  9818. "map" : { type: "t", value: null },
  9819. "fogDensity" : { type: "f", value: 0.00025 },
  9820. "fogNear" : { type: "f", value: 1 },
  9821. "fogFar" : { type: "f", value: 2000 },
  9822. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9823. },
  9824. shadowmap: {
  9825. "shadowMap": { type: "tv", value: [] },
  9826. "shadowMapSize": { type: "v2v", value: [] },
  9827. "shadowBias" : { type: "fv1", value: [] },
  9828. "shadowDarkness": { type: "fv1", value: [] },
  9829. "shadowMatrix" : { type: "m4v", value: [] }
  9830. }
  9831. };
  9832. THREE.ShaderLib = {
  9833. 'basic': {
  9834. uniforms: THREE.UniformsUtils.merge( [
  9835. THREE.UniformsLib[ "common" ],
  9836. THREE.UniformsLib[ "fog" ],
  9837. THREE.UniformsLib[ "shadowmap" ]
  9838. ] ),
  9839. vertexShader: [
  9840. THREE.ShaderChunk[ "map_pars_vertex" ],
  9841. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9842. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9843. THREE.ShaderChunk[ "color_pars_vertex" ],
  9844. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9845. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9846. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9847. "void main() {",
  9848. THREE.ShaderChunk[ "map_vertex" ],
  9849. THREE.ShaderChunk[ "lightmap_vertex" ],
  9850. THREE.ShaderChunk[ "color_vertex" ],
  9851. THREE.ShaderChunk[ "skinbase_vertex" ],
  9852. "#ifdef USE_ENVMAP",
  9853. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9854. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9855. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9856. "#endif",
  9857. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9858. THREE.ShaderChunk[ "skinning_vertex" ],
  9859. THREE.ShaderChunk[ "default_vertex" ],
  9860. THREE.ShaderChunk[ "worldpos_vertex" ],
  9861. THREE.ShaderChunk[ "envmap_vertex" ],
  9862. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9863. "}"
  9864. ].join("\n"),
  9865. fragmentShader: [
  9866. "uniform vec3 diffuse;",
  9867. "uniform float opacity;",
  9868. THREE.ShaderChunk[ "color_pars_fragment" ],
  9869. THREE.ShaderChunk[ "map_pars_fragment" ],
  9870. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9871. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9872. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9873. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9874. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9875. "void main() {",
  9876. "gl_FragColor = vec4( diffuse, opacity );",
  9877. THREE.ShaderChunk[ "map_fragment" ],
  9878. THREE.ShaderChunk[ "alphatest_fragment" ],
  9879. THREE.ShaderChunk[ "specularmap_fragment" ],
  9880. THREE.ShaderChunk[ "lightmap_fragment" ],
  9881. THREE.ShaderChunk[ "color_fragment" ],
  9882. THREE.ShaderChunk[ "envmap_fragment" ],
  9883. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9884. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9885. THREE.ShaderChunk[ "fog_fragment" ],
  9886. "}"
  9887. ].join("\n")
  9888. },
  9889. 'lambert': {
  9890. uniforms: THREE.UniformsUtils.merge( [
  9891. THREE.UniformsLib[ "common" ],
  9892. THREE.UniformsLib[ "fog" ],
  9893. THREE.UniformsLib[ "lights" ],
  9894. THREE.UniformsLib[ "shadowmap" ],
  9895. {
  9896. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9897. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9898. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9899. }
  9900. ] ),
  9901. vertexShader: [
  9902. "#define LAMBERT",
  9903. "varying vec3 vLightFront;",
  9904. "#ifdef DOUBLE_SIDED",
  9905. "varying vec3 vLightBack;",
  9906. "#endif",
  9907. THREE.ShaderChunk[ "map_pars_vertex" ],
  9908. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9909. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9910. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9911. THREE.ShaderChunk[ "color_pars_vertex" ],
  9912. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9913. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9914. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9915. "void main() {",
  9916. THREE.ShaderChunk[ "map_vertex" ],
  9917. THREE.ShaderChunk[ "lightmap_vertex" ],
  9918. THREE.ShaderChunk[ "color_vertex" ],
  9919. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9920. THREE.ShaderChunk[ "skinbase_vertex" ],
  9921. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9922. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9923. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9924. THREE.ShaderChunk[ "skinning_vertex" ],
  9925. THREE.ShaderChunk[ "default_vertex" ],
  9926. THREE.ShaderChunk[ "worldpos_vertex" ],
  9927. THREE.ShaderChunk[ "envmap_vertex" ],
  9928. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9929. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9930. "}"
  9931. ].join("\n"),
  9932. fragmentShader: [
  9933. "uniform float opacity;",
  9934. "varying vec3 vLightFront;",
  9935. "#ifdef DOUBLE_SIDED",
  9936. "varying vec3 vLightBack;",
  9937. "#endif",
  9938. THREE.ShaderChunk[ "color_pars_fragment" ],
  9939. THREE.ShaderChunk[ "map_pars_fragment" ],
  9940. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9941. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9942. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9943. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9944. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9945. "void main() {",
  9946. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9947. THREE.ShaderChunk[ "map_fragment" ],
  9948. THREE.ShaderChunk[ "alphatest_fragment" ],
  9949. THREE.ShaderChunk[ "specularmap_fragment" ],
  9950. "#ifdef DOUBLE_SIDED",
  9951. //"float isFront = float( gl_FrontFacing );",
  9952. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9953. "if ( gl_FrontFacing )",
  9954. "gl_FragColor.xyz *= vLightFront;",
  9955. "else",
  9956. "gl_FragColor.xyz *= vLightBack;",
  9957. "#else",
  9958. "gl_FragColor.xyz *= vLightFront;",
  9959. "#endif",
  9960. THREE.ShaderChunk[ "lightmap_fragment" ],
  9961. THREE.ShaderChunk[ "color_fragment" ],
  9962. THREE.ShaderChunk[ "envmap_fragment" ],
  9963. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9964. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9965. THREE.ShaderChunk[ "fog_fragment" ],
  9966. "}"
  9967. ].join("\n")
  9968. },
  9969. 'phong': {
  9970. uniforms: THREE.UniformsUtils.merge( [
  9971. THREE.UniformsLib[ "common" ],
  9972. THREE.UniformsLib[ "bump" ],
  9973. THREE.UniformsLib[ "normalmap" ],
  9974. THREE.UniformsLib[ "fog" ],
  9975. THREE.UniformsLib[ "lights" ],
  9976. THREE.UniformsLib[ "shadowmap" ],
  9977. {
  9978. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9979. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9980. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9981. "shininess": { type: "f", value: 30 },
  9982. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9983. }
  9984. ] ),
  9985. vertexShader: [
  9986. "#define PHONG",
  9987. "varying vec3 vViewPosition;",
  9988. "varying vec3 vNormal;",
  9989. THREE.ShaderChunk[ "map_pars_vertex" ],
  9990. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9991. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9992. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9993. THREE.ShaderChunk[ "color_pars_vertex" ],
  9994. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9995. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9996. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9997. "void main() {",
  9998. THREE.ShaderChunk[ "map_vertex" ],
  9999. THREE.ShaderChunk[ "lightmap_vertex" ],
  10000. THREE.ShaderChunk[ "color_vertex" ],
  10001. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10002. THREE.ShaderChunk[ "skinbase_vertex" ],
  10003. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10004. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10005. "vNormal = normalize( transformedNormal );",
  10006. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10007. THREE.ShaderChunk[ "skinning_vertex" ],
  10008. THREE.ShaderChunk[ "default_vertex" ],
  10009. "vViewPosition = -mvPosition.xyz;",
  10010. THREE.ShaderChunk[ "worldpos_vertex" ],
  10011. THREE.ShaderChunk[ "envmap_vertex" ],
  10012. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10013. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10014. "}"
  10015. ].join("\n"),
  10016. fragmentShader: [
  10017. "uniform vec3 diffuse;",
  10018. "uniform float opacity;",
  10019. "uniform vec3 ambient;",
  10020. "uniform vec3 emissive;",
  10021. "uniform vec3 specular;",
  10022. "uniform float shininess;",
  10023. THREE.ShaderChunk[ "color_pars_fragment" ],
  10024. THREE.ShaderChunk[ "map_pars_fragment" ],
  10025. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10026. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10027. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10028. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10029. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10030. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10031. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10032. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10033. "void main() {",
  10034. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10035. THREE.ShaderChunk[ "map_fragment" ],
  10036. THREE.ShaderChunk[ "alphatest_fragment" ],
  10037. THREE.ShaderChunk[ "specularmap_fragment" ],
  10038. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10039. THREE.ShaderChunk[ "lightmap_fragment" ],
  10040. THREE.ShaderChunk[ "color_fragment" ],
  10041. THREE.ShaderChunk[ "envmap_fragment" ],
  10042. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10043. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10044. THREE.ShaderChunk[ "fog_fragment" ],
  10045. "}"
  10046. ].join("\n")
  10047. },
  10048. 'particle_basic': {
  10049. uniforms: THREE.UniformsUtils.merge( [
  10050. THREE.UniformsLib[ "particle" ],
  10051. THREE.UniformsLib[ "shadowmap" ]
  10052. ] ),
  10053. vertexShader: [
  10054. "uniform float size;",
  10055. "uniform float scale;",
  10056. THREE.ShaderChunk[ "color_pars_vertex" ],
  10057. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10058. "void main() {",
  10059. THREE.ShaderChunk[ "color_vertex" ],
  10060. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10061. "#ifdef USE_SIZEATTENUATION",
  10062. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10063. "#else",
  10064. "gl_PointSize = size;",
  10065. "#endif",
  10066. "gl_Position = projectionMatrix * mvPosition;",
  10067. THREE.ShaderChunk[ "worldpos_vertex" ],
  10068. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10069. "}"
  10070. ].join("\n"),
  10071. fragmentShader: [
  10072. "uniform vec3 psColor;",
  10073. "uniform float opacity;",
  10074. THREE.ShaderChunk[ "color_pars_fragment" ],
  10075. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10076. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10077. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10078. "void main() {",
  10079. "gl_FragColor = vec4( psColor, opacity );",
  10080. THREE.ShaderChunk[ "map_particle_fragment" ],
  10081. THREE.ShaderChunk[ "alphatest_fragment" ],
  10082. THREE.ShaderChunk[ "color_fragment" ],
  10083. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10084. THREE.ShaderChunk[ "fog_fragment" ],
  10085. "}"
  10086. ].join("\n")
  10087. },
  10088. 'dashed': {
  10089. uniforms: THREE.UniformsUtils.merge( [
  10090. THREE.UniformsLib[ "common" ],
  10091. THREE.UniformsLib[ "fog" ],
  10092. {
  10093. "scale": { type: "f", value: 1 },
  10094. "dashSize": { type: "f", value: 1 },
  10095. "totalSize": { type: "f", value: 2 }
  10096. }
  10097. ] ),
  10098. vertexShader: [
  10099. "uniform float scale;",
  10100. "attribute float lineDistance;",
  10101. "varying float vLineDistance;",
  10102. THREE.ShaderChunk[ "color_pars_vertex" ],
  10103. "void main() {",
  10104. THREE.ShaderChunk[ "color_vertex" ],
  10105. "vLineDistance = scale * lineDistance;",
  10106. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10107. "gl_Position = projectionMatrix * mvPosition;",
  10108. "}"
  10109. ].join("\n"),
  10110. fragmentShader: [
  10111. "uniform vec3 diffuse;",
  10112. "uniform float opacity;",
  10113. "uniform float dashSize;",
  10114. "uniform float totalSize;",
  10115. "varying float vLineDistance;",
  10116. THREE.ShaderChunk[ "color_pars_fragment" ],
  10117. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10118. "void main() {",
  10119. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10120. "discard;",
  10121. "}",
  10122. "gl_FragColor = vec4( diffuse, opacity );",
  10123. THREE.ShaderChunk[ "color_fragment" ],
  10124. THREE.ShaderChunk[ "fog_fragment" ],
  10125. "}"
  10126. ].join("\n")
  10127. },
  10128. 'depth': {
  10129. uniforms: {
  10130. "mNear": { type: "f", value: 1.0 },
  10131. "mFar" : { type: "f", value: 2000.0 },
  10132. "opacity" : { type: "f", value: 1.0 }
  10133. },
  10134. vertexShader: [
  10135. "void main() {",
  10136. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10137. "}"
  10138. ].join("\n"),
  10139. fragmentShader: [
  10140. "uniform float mNear;",
  10141. "uniform float mFar;",
  10142. "uniform float opacity;",
  10143. "void main() {",
  10144. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10145. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10146. "gl_FragColor = vec4( vec3( color ), opacity );",
  10147. "}"
  10148. ].join("\n")
  10149. },
  10150. 'normal': {
  10151. uniforms: {
  10152. "opacity" : { type: "f", value: 1.0 }
  10153. },
  10154. vertexShader: [
  10155. "varying vec3 vNormal;",
  10156. "void main() {",
  10157. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10158. "vNormal = normalize( normalMatrix * normal );",
  10159. "gl_Position = projectionMatrix * mvPosition;",
  10160. "}"
  10161. ].join("\n"),
  10162. fragmentShader: [
  10163. "uniform float opacity;",
  10164. "varying vec3 vNormal;",
  10165. "void main() {",
  10166. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10167. "}"
  10168. ].join("\n")
  10169. },
  10170. /* -------------------------------------------------------------------------
  10171. // Normal map shader
  10172. // - Blinn-Phong
  10173. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10174. // - point and directional lights (use with "lights: true" material option)
  10175. ------------------------------------------------------------------------- */
  10176. 'normalmap' : {
  10177. uniforms: THREE.UniformsUtils.merge( [
  10178. THREE.UniformsLib[ "fog" ],
  10179. THREE.UniformsLib[ "lights" ],
  10180. THREE.UniformsLib[ "shadowmap" ],
  10181. {
  10182. "enableAO" : { type: "i", value: 0 },
  10183. "enableDiffuse" : { type: "i", value: 0 },
  10184. "enableSpecular" : { type: "i", value: 0 },
  10185. "enableReflection": { type: "i", value: 0 },
  10186. "enableDisplacement": { type: "i", value: 0 },
  10187. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  10188. "tDiffuse" : { type: "t", value: null },
  10189. "tCube" : { type: "t", value: null },
  10190. "tNormal" : { type: "t", value: null },
  10191. "tSpecular" : { type: "t", value: null },
  10192. "tAO" : { type: "t", value: null },
  10193. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10194. "uDisplacementBias": { type: "f", value: 0.0 },
  10195. "uDisplacementScale": { type: "f", value: 1.0 },
  10196. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10197. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10198. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10199. "uShininess": { type: "f", value: 30 },
  10200. "uOpacity": { type: "f", value: 1 },
  10201. "useRefract": { type: "i", value: 0 },
  10202. "uRefractionRatio": { type: "f", value: 0.98 },
  10203. "uReflectivity": { type: "f", value: 0.5 },
  10204. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  10205. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10206. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10207. }
  10208. ] ),
  10209. fragmentShader: [
  10210. "uniform vec3 uAmbientColor;",
  10211. "uniform vec3 uDiffuseColor;",
  10212. "uniform vec3 uSpecularColor;",
  10213. "uniform float uShininess;",
  10214. "uniform float uOpacity;",
  10215. "uniform bool enableDiffuse;",
  10216. "uniform bool enableSpecular;",
  10217. "uniform bool enableAO;",
  10218. "uniform bool enableReflection;",
  10219. "uniform sampler2D tDiffuse;",
  10220. "uniform sampler2D tNormal;",
  10221. "uniform sampler2D tSpecular;",
  10222. "uniform sampler2D tAO;",
  10223. "uniform samplerCube tCube;",
  10224. "uniform vec2 uNormalScale;",
  10225. "uniform bool useRefract;",
  10226. "uniform float uRefractionRatio;",
  10227. "uniform float uReflectivity;",
  10228. "varying vec3 vTangent;",
  10229. "varying vec3 vBinormal;",
  10230. "varying vec3 vNormal;",
  10231. "varying vec2 vUv;",
  10232. "uniform vec3 ambientLightColor;",
  10233. "#if MAX_DIR_LIGHTS > 0",
  10234. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10235. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10236. "#endif",
  10237. "#if MAX_HEMI_LIGHTS > 0",
  10238. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10239. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10240. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10241. "#endif",
  10242. "#if MAX_POINT_LIGHTS > 0",
  10243. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10244. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10245. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10246. "#endif",
  10247. "#if MAX_SPOT_LIGHTS > 0",
  10248. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10249. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10250. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10251. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10252. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10253. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10254. "#endif",
  10255. "#ifdef WRAP_AROUND",
  10256. "uniform vec3 wrapRGB;",
  10257. "#endif",
  10258. "varying vec3 vWorldPosition;",
  10259. "varying vec3 vViewPosition;",
  10260. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10261. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10262. "void main() {",
  10263. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  10264. "vec3 specularTex = vec3( 1.0 );",
  10265. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  10266. "normalTex.xy *= uNormalScale;",
  10267. "normalTex = normalize( normalTex );",
  10268. "if( enableDiffuse ) {",
  10269. "#ifdef GAMMA_INPUT",
  10270. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  10271. "texelColor.xyz *= texelColor.xyz;",
  10272. "gl_FragColor = gl_FragColor * texelColor;",
  10273. "#else",
  10274. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  10275. "#endif",
  10276. "}",
  10277. "if( enableAO ) {",
  10278. "#ifdef GAMMA_INPUT",
  10279. "vec4 aoColor = texture2D( tAO, vUv );",
  10280. "aoColor.xyz *= aoColor.xyz;",
  10281. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  10282. "#else",
  10283. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  10284. "#endif",
  10285. "}",
  10286. "if( enableSpecular )",
  10287. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  10288. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  10289. "vec3 finalNormal = tsb * normalTex;",
  10290. "#ifdef FLIP_SIDED",
  10291. "finalNormal = -finalNormal;",
  10292. "#endif",
  10293. "vec3 normal = normalize( finalNormal );",
  10294. "vec3 viewPosition = normalize( vViewPosition );",
  10295. // point lights
  10296. "#if MAX_POINT_LIGHTS > 0",
  10297. "vec3 pointDiffuse = vec3( 0.0 );",
  10298. "vec3 pointSpecular = vec3( 0.0 );",
  10299. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10300. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10301. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  10302. "float pointDistance = 1.0;",
  10303. "if ( pointLightDistance[ i ] > 0.0 )",
  10304. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  10305. "pointVector = normalize( pointVector );",
  10306. // diffuse
  10307. "#ifdef WRAP_AROUND",
  10308. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  10309. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  10310. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10311. "#else",
  10312. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  10313. "#endif",
  10314. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  10315. // specular
  10316. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  10317. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10318. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  10319. "#ifdef PHYSICALLY_BASED_SHADING",
  10320. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10321. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10322. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  10323. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  10324. "#else",
  10325. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  10326. "#endif",
  10327. "}",
  10328. "#endif",
  10329. // spot lights
  10330. "#if MAX_SPOT_LIGHTS > 0",
  10331. "vec3 spotDiffuse = vec3( 0.0 );",
  10332. "vec3 spotSpecular = vec3( 0.0 );",
  10333. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10334. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10335. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  10336. "float spotDistance = 1.0;",
  10337. "if ( spotLightDistance[ i ] > 0.0 )",
  10338. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  10339. "spotVector = normalize( spotVector );",
  10340. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10341. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10342. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10343. // diffuse
  10344. "#ifdef WRAP_AROUND",
  10345. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  10346. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  10347. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10348. "#else",
  10349. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  10350. "#endif",
  10351. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  10352. // specular
  10353. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  10354. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10355. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  10356. "#ifdef PHYSICALLY_BASED_SHADING",
  10357. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10358. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10359. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  10360. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  10361. "#else",
  10362. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  10363. "#endif",
  10364. "}",
  10365. "}",
  10366. "#endif",
  10367. // directional lights
  10368. "#if MAX_DIR_LIGHTS > 0",
  10369. "vec3 dirDiffuse = vec3( 0.0 );",
  10370. "vec3 dirSpecular = vec3( 0.0 );",
  10371. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  10372. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10373. "vec3 dirVector = normalize( lDirection.xyz );",
  10374. // diffuse
  10375. "#ifdef WRAP_AROUND",
  10376. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  10377. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  10378. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  10379. "#else",
  10380. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  10381. "#endif",
  10382. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  10383. // specular
  10384. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10385. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10386. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  10387. "#ifdef PHYSICALLY_BASED_SHADING",
  10388. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10389. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10390. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10391. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10392. "#else",
  10393. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  10394. "#endif",
  10395. "}",
  10396. "#endif",
  10397. // hemisphere lights
  10398. "#if MAX_HEMI_LIGHTS > 0",
  10399. "vec3 hemiDiffuse = vec3( 0.0 );",
  10400. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10401. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10402. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10403. "vec3 lVector = normalize( lDirection.xyz );",
  10404. // diffuse
  10405. "float dotProduct = dot( normal, lVector );",
  10406. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10407. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10408. "hemiDiffuse += uDiffuseColor * hemiColor;",
  10409. // specular (sky light)
  10410. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10411. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10412. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  10413. // specular (ground light)
  10414. "vec3 lVectorGround = -lVector;",
  10415. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10416. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10417. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  10418. "#ifdef PHYSICALLY_BASED_SHADING",
  10419. "float dotProductGround = dot( normal, lVectorGround );",
  10420. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10421. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10422. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10423. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10424. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10425. "#else",
  10426. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10427. "#endif",
  10428. "}",
  10429. "#endif",
  10430. // all lights contribution summation
  10431. "vec3 totalDiffuse = vec3( 0.0 );",
  10432. "vec3 totalSpecular = vec3( 0.0 );",
  10433. "#if MAX_DIR_LIGHTS > 0",
  10434. "totalDiffuse += dirDiffuse;",
  10435. "totalSpecular += dirSpecular;",
  10436. "#endif",
  10437. "#if MAX_HEMI_LIGHTS > 0",
  10438. "totalDiffuse += hemiDiffuse;",
  10439. "totalSpecular += hemiSpecular;",
  10440. "#endif",
  10441. "#if MAX_POINT_LIGHTS > 0",
  10442. "totalDiffuse += pointDiffuse;",
  10443. "totalSpecular += pointSpecular;",
  10444. "#endif",
  10445. "#if MAX_SPOT_LIGHTS > 0",
  10446. "totalDiffuse += spotDiffuse;",
  10447. "totalSpecular += spotSpecular;",
  10448. "#endif",
  10449. "#ifdef METAL",
  10450. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  10451. "#else",
  10452. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  10453. "#endif",
  10454. "if ( enableReflection ) {",
  10455. "vec3 vReflect;",
  10456. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10457. "if ( useRefract ) {",
  10458. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  10459. "} else {",
  10460. "vReflect = reflect( cameraToVertex, normal );",
  10461. "}",
  10462. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10463. "#ifdef GAMMA_INPUT",
  10464. "cubeColor.xyz *= cubeColor.xyz;",
  10465. "#endif",
  10466. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  10467. "}",
  10468. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10469. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10470. THREE.ShaderChunk[ "fog_fragment" ],
  10471. "}"
  10472. ].join("\n"),
  10473. vertexShader: [
  10474. "attribute vec4 tangent;",
  10475. "uniform vec2 uOffset;",
  10476. "uniform vec2 uRepeat;",
  10477. "uniform bool enableDisplacement;",
  10478. "#ifdef VERTEX_TEXTURES",
  10479. "uniform sampler2D tDisplacement;",
  10480. "uniform float uDisplacementScale;",
  10481. "uniform float uDisplacementBias;",
  10482. "#endif",
  10483. "varying vec3 vTangent;",
  10484. "varying vec3 vBinormal;",
  10485. "varying vec3 vNormal;",
  10486. "varying vec2 vUv;",
  10487. "varying vec3 vWorldPosition;",
  10488. "varying vec3 vViewPosition;",
  10489. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10490. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10491. "void main() {",
  10492. THREE.ShaderChunk[ "skinbase_vertex" ],
  10493. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10494. // normal, tangent and binormal vectors
  10495. "#ifdef USE_SKINNING",
  10496. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  10497. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  10498. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  10499. "#else",
  10500. "vNormal = normalize( normalMatrix * normal );",
  10501. "vTangent = normalize( normalMatrix * tangent.xyz );",
  10502. "#endif",
  10503. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  10504. "vUv = uv * uRepeat + uOffset;",
  10505. // displacement mapping
  10506. "vec3 displacedPosition;",
  10507. "#ifdef VERTEX_TEXTURES",
  10508. "if ( enableDisplacement ) {",
  10509. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  10510. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  10511. "displacedPosition = position + normalize( normal ) * df;",
  10512. "} else {",
  10513. "#ifdef USE_SKINNING",
  10514. "vec4 skinVertex = vec4( position, 1.0 );",
  10515. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10516. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10517. "displacedPosition = skinned.xyz;",
  10518. "#else",
  10519. "displacedPosition = position;",
  10520. "#endif",
  10521. "}",
  10522. "#else",
  10523. "#ifdef USE_SKINNING",
  10524. "vec4 skinVertex = vec4( position, 1.0 );",
  10525. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10526. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10527. "displacedPosition = skinned.xyz;",
  10528. "#else",
  10529. "displacedPosition = position;",
  10530. "#endif",
  10531. "#endif",
  10532. //
  10533. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  10534. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  10535. "gl_Position = projectionMatrix * mvPosition;",
  10536. //
  10537. "vWorldPosition = worldPosition.xyz;",
  10538. "vViewPosition = -mvPosition.xyz;",
  10539. // shadows
  10540. "#ifdef USE_SHADOWMAP",
  10541. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10542. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10543. "}",
  10544. "#endif",
  10545. "}"
  10546. ].join("\n")
  10547. },
  10548. /* -------------------------------------------------------------------------
  10549. // Cube map shader
  10550. ------------------------------------------------------------------------- */
  10551. 'cube': {
  10552. uniforms: { "tCube": { type: "t", value: null },
  10553. "tFlip": { type: "f", value: -1 } },
  10554. vertexShader: [
  10555. "varying vec3 vWorldPosition;",
  10556. "void main() {",
  10557. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10558. "vWorldPosition = worldPosition.xyz;",
  10559. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10560. "}"
  10561. ].join("\n"),
  10562. fragmentShader: [
  10563. "uniform samplerCube tCube;",
  10564. "uniform float tFlip;",
  10565. "varying vec3 vWorldPosition;",
  10566. "void main() {",
  10567. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10568. "}"
  10569. ].join("\n")
  10570. },
  10571. // Depth encoding into RGBA texture
  10572. // based on SpiderGL shadow map example
  10573. // http://spidergl.org/example.php?id=6
  10574. // originally from
  10575. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10576. // see also here:
  10577. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10578. 'depthRGBA': {
  10579. uniforms: {},
  10580. vertexShader: [
  10581. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10582. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10583. "void main() {",
  10584. THREE.ShaderChunk[ "skinbase_vertex" ],
  10585. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10586. THREE.ShaderChunk[ "skinning_vertex" ],
  10587. THREE.ShaderChunk[ "default_vertex" ],
  10588. "}"
  10589. ].join("\n"),
  10590. fragmentShader: [
  10591. "vec4 pack_depth( const in float depth ) {",
  10592. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10593. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10594. "vec4 res = fract( depth * bit_shift );",
  10595. "res -= res.xxyz * bit_mask;",
  10596. "return res;",
  10597. "}",
  10598. "void main() {",
  10599. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10600. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10601. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10602. //"gl_FragData[ 0 ] = pack_depth( z );",
  10603. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10604. "}"
  10605. ].join("\n")
  10606. }
  10607. };
  10608. /**
  10609. * @author supereggbert / http://www.paulbrunt.co.uk/
  10610. * @author mrdoob / http://mrdoob.com/
  10611. * @author alteredq / http://alteredqualia.com/
  10612. * @author szimek / https://github.com/szimek/
  10613. */
  10614. THREE.WebGLRenderer = function ( parameters ) {
  10615. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10616. parameters = parameters || {};
  10617. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10618. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10619. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10620. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10621. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10622. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10623. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10624. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10625. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10626. // public properties
  10627. this.domElement = _canvas;
  10628. this.context = null;
  10629. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10630. ? parameters.devicePixelRatio
  10631. : window.devicePixelRatio !== undefined
  10632. ? window.devicePixelRatio
  10633. : 1;
  10634. // clearing
  10635. this.autoClear = true;
  10636. this.autoClearColor = true;
  10637. this.autoClearDepth = true;
  10638. this.autoClearStencil = true;
  10639. // scene graph
  10640. this.sortObjects = true;
  10641. this.autoUpdateObjects = true;
  10642. this.autoUpdateScene = true;
  10643. // physically based shading
  10644. this.gammaInput = false;
  10645. this.gammaOutput = false;
  10646. this.physicallyBasedShading = false;
  10647. // shadow map
  10648. this.shadowMapEnabled = false;
  10649. this.shadowMapAutoUpdate = true;
  10650. this.shadowMapType = THREE.PCFShadowMap;
  10651. this.shadowMapCullFace = THREE.CullFaceFront;
  10652. this.shadowMapDebug = false;
  10653. this.shadowMapCascade = false;
  10654. // morphs
  10655. this.maxMorphTargets = 8;
  10656. this.maxMorphNormals = 4;
  10657. // flags
  10658. this.autoScaleCubemaps = true;
  10659. // custom render plugins
  10660. this.renderPluginsPre = [];
  10661. this.renderPluginsPost = [];
  10662. // info
  10663. this.info = {
  10664. memory: {
  10665. programs: 0,
  10666. geometries: 0,
  10667. textures: 0
  10668. },
  10669. render: {
  10670. calls: 0,
  10671. vertices: 0,
  10672. faces: 0,
  10673. points: 0
  10674. }
  10675. };
  10676. // internal properties
  10677. var _this = this,
  10678. _programs = [],
  10679. _programs_counter = 0,
  10680. // internal state cache
  10681. _currentProgram = null,
  10682. _currentFramebuffer = null,
  10683. _currentMaterialId = -1,
  10684. _currentGeometryGroupHash = null,
  10685. _currentCamera = null,
  10686. _geometryGroupCounter = 0,
  10687. _usedTextureUnits = 0,
  10688. // GL state cache
  10689. _oldDoubleSided = -1,
  10690. _oldFlipSided = -1,
  10691. _oldBlending = -1,
  10692. _oldBlendEquation = -1,
  10693. _oldBlendSrc = -1,
  10694. _oldBlendDst = -1,
  10695. _oldDepthTest = -1,
  10696. _oldDepthWrite = -1,
  10697. _oldPolygonOffset = null,
  10698. _oldPolygonOffsetFactor = null,
  10699. _oldPolygonOffsetUnits = null,
  10700. _oldLineWidth = null,
  10701. _viewportX = 0,
  10702. _viewportY = 0,
  10703. _viewportWidth = 0,
  10704. _viewportHeight = 0,
  10705. _currentWidth = 0,
  10706. _currentHeight = 0,
  10707. _enabledAttributes = {},
  10708. // frustum
  10709. _frustum = new THREE.Frustum(),
  10710. // camera matrices cache
  10711. _projScreenMatrix = new THREE.Matrix4(),
  10712. _projScreenMatrixPS = new THREE.Matrix4(),
  10713. _vector3 = new THREE.Vector3(),
  10714. // light arrays cache
  10715. _direction = new THREE.Vector3(),
  10716. _lightsNeedUpdate = true,
  10717. _lights = {
  10718. ambient: [ 0, 0, 0 ],
  10719. directional: { length: 0, colors: new Array(), positions: new Array() },
  10720. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10721. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10722. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10723. };
  10724. // initialize
  10725. var _gl;
  10726. var _glExtensionTextureFloat;
  10727. var _glExtensionStandardDerivatives;
  10728. var _glExtensionTextureFilterAnisotropic;
  10729. var _glExtensionCompressedTextureS3TC;
  10730. initGL();
  10731. setDefaultGLState();
  10732. this.context = _gl;
  10733. // GPU capabilities
  10734. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10735. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10736. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10737. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10738. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10739. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10740. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10741. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10742. //
  10743. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10744. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10745. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10746. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10747. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10748. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10749. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10750. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10751. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10752. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10753. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10754. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10755. // clamp precision to maximum available
  10756. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10757. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10758. if ( _precision === "highp" && ! highpAvailable ) {
  10759. if ( mediumpAvailable ) {
  10760. _precision = "mediump";
  10761. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10762. } else {
  10763. _precision = "lowp";
  10764. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  10765. }
  10766. }
  10767. if ( _precision === "mediump" && ! mediumpAvailable ) {
  10768. _precision = "lowp";
  10769. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  10770. }
  10771. // API
  10772. this.getContext = function () {
  10773. return _gl;
  10774. };
  10775. this.supportsVertexTextures = function () {
  10776. return _supportsVertexTextures;
  10777. };
  10778. this.supportsFloatTextures = function () {
  10779. return _glExtensionTextureFloat;
  10780. };
  10781. this.supportsStandardDerivatives = function () {
  10782. return _glExtensionStandardDerivatives;
  10783. };
  10784. this.supportsCompressedTextureS3TC = function () {
  10785. return _glExtensionCompressedTextureS3TC;
  10786. };
  10787. this.getMaxAnisotropy = function () {
  10788. return _maxAnisotropy;
  10789. };
  10790. this.getPrecision = function () {
  10791. return _precision;
  10792. };
  10793. this.setSize = function ( width, height ) {
  10794. _canvas.width = width * this.devicePixelRatio;
  10795. _canvas.height = height * this.devicePixelRatio;
  10796. _canvas.style.width = width + 'px';
  10797. _canvas.style.height = height + 'px';
  10798. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10799. };
  10800. this.setViewport = function ( x, y, width, height ) {
  10801. _viewportX = x !== undefined ? x : 0;
  10802. _viewportY = y !== undefined ? y : 0;
  10803. _viewportWidth = width !== undefined ? width : _canvas.width;
  10804. _viewportHeight = height !== undefined ? height : _canvas.height;
  10805. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10806. };
  10807. this.setScissor = function ( x, y, width, height ) {
  10808. _gl.scissor( x, y, width, height );
  10809. };
  10810. this.enableScissorTest = function ( enable ) {
  10811. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10812. };
  10813. // Clearing
  10814. this.setClearColorHex = function ( hex, alpha ) {
  10815. _clearColor.setHex( hex );
  10816. _clearAlpha = alpha;
  10817. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10818. };
  10819. this.setClearColor = function ( color, alpha ) {
  10820. _clearColor.copy( color );
  10821. _clearAlpha = alpha;
  10822. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10823. };
  10824. this.getClearColor = function () {
  10825. return _clearColor;
  10826. };
  10827. this.getClearAlpha = function () {
  10828. return _clearAlpha;
  10829. };
  10830. this.clear = function ( color, depth, stencil ) {
  10831. var bits = 0;
  10832. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10833. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10834. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10835. _gl.clear( bits );
  10836. };
  10837. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10838. this.setRenderTarget( renderTarget );
  10839. this.clear( color, depth, stencil );
  10840. };
  10841. // Plugins
  10842. this.addPostPlugin = function ( plugin ) {
  10843. plugin.init( this );
  10844. this.renderPluginsPost.push( plugin );
  10845. };
  10846. this.addPrePlugin = function ( plugin ) {
  10847. plugin.init( this );
  10848. this.renderPluginsPre.push( plugin );
  10849. };
  10850. // Rendering
  10851. this.updateShadowMap = function ( scene, camera ) {
  10852. _currentProgram = null;
  10853. _oldBlending = -1;
  10854. _oldDepthTest = -1;
  10855. _oldDepthWrite = -1;
  10856. _currentGeometryGroupHash = -1;
  10857. _currentMaterialId = -1;
  10858. _lightsNeedUpdate = true;
  10859. _oldDoubleSided = -1;
  10860. _oldFlipSided = -1;
  10861. this.shadowMapPlugin.update( scene, camera );
  10862. };
  10863. // Internal functions
  10864. // Buffer allocation
  10865. function createParticleBuffers ( geometry ) {
  10866. geometry.__webglVertexBuffer = _gl.createBuffer();
  10867. geometry.__webglColorBuffer = _gl.createBuffer();
  10868. _this.info.memory.geometries ++;
  10869. };
  10870. function createLineBuffers ( geometry ) {
  10871. geometry.__webglVertexBuffer = _gl.createBuffer();
  10872. geometry.__webglColorBuffer = _gl.createBuffer();
  10873. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10874. _this.info.memory.geometries ++;
  10875. };
  10876. function createRibbonBuffers ( geometry ) {
  10877. geometry.__webglVertexBuffer = _gl.createBuffer();
  10878. geometry.__webglColorBuffer = _gl.createBuffer();
  10879. geometry.__webglNormalBuffer = _gl.createBuffer();
  10880. _this.info.memory.geometries ++;
  10881. };
  10882. function createMeshBuffers ( geometryGroup ) {
  10883. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10884. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10885. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10886. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10887. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10888. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10889. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10890. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10891. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10892. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10893. var m, ml;
  10894. if ( geometryGroup.numMorphTargets ) {
  10895. geometryGroup.__webglMorphTargetsBuffers = [];
  10896. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10897. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10898. }
  10899. }
  10900. if ( geometryGroup.numMorphNormals ) {
  10901. geometryGroup.__webglMorphNormalsBuffers = [];
  10902. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10903. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10904. }
  10905. }
  10906. _this.info.memory.geometries ++;
  10907. };
  10908. // Events
  10909. var onGeometryDispose = function ( event ) {
  10910. var geometry = event.target;
  10911. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10912. deallocateGeometry( geometry );
  10913. _this.info.memory.geometries --;
  10914. };
  10915. var onTextureDispose = function ( event ) {
  10916. var texture = event.target;
  10917. texture.removeEventListener( 'dispose', onTextureDispose );
  10918. deallocateTexture( texture );
  10919. _this.info.memory.textures --;
  10920. };
  10921. var onRenderTargetDispose = function ( event ) {
  10922. var renderTarget = event.target;
  10923. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10924. deallocateRenderTarget( renderTarget );
  10925. _this.info.memory.textures --;
  10926. };
  10927. var onMaterialDispose = function ( event ) {
  10928. var material = event.target;
  10929. material.removeEventListener( 'dispose', onMaterialDispose );
  10930. deallocateMaterial( material );
  10931. };
  10932. // Buffer deallocation
  10933. var deallocateGeometry = function ( geometry ) {
  10934. geometry.__webglInit = undefined;
  10935. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10936. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10937. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  10938. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  10939. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  10940. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  10941. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10942. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10943. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  10944. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  10945. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10946. // geometry groups
  10947. if ( geometry.geometryGroups !== undefined ) {
  10948. for ( var g in geometry.geometryGroups ) {
  10949. var geometryGroup = geometry.geometryGroups[ g ];
  10950. if ( geometryGroup.numMorphTargets !== undefined ) {
  10951. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10952. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10953. }
  10954. }
  10955. if ( geometryGroup.numMorphNormals !== undefined ) {
  10956. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10957. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10958. }
  10959. }
  10960. deleteCustomAttributesBuffers( geometryGroup );
  10961. }
  10962. }
  10963. deleteCustomAttributesBuffers( geometry );
  10964. };
  10965. var deallocateTexture = function ( texture ) {
  10966. if ( texture.image && texture.image.__webglTextureCube ) {
  10967. // cube texture
  10968. _gl.deleteTexture( texture.image.__webglTextureCube );
  10969. } else {
  10970. // 2D texture
  10971. if ( ! texture.__webglInit ) return;
  10972. texture.__webglInit = false;
  10973. _gl.deleteTexture( texture.__webglTexture );
  10974. }
  10975. };
  10976. var deallocateRenderTarget = function ( renderTarget ) {
  10977. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10978. _gl.deleteTexture( renderTarget.__webglTexture );
  10979. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10980. for ( var i = 0; i < 6; i ++ ) {
  10981. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10982. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10983. }
  10984. } else {
  10985. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10986. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10987. }
  10988. };
  10989. var deallocateMaterial = function ( material ) {
  10990. var program = material.program;
  10991. if ( program === undefined ) return;
  10992. material.program = undefined;
  10993. // only deallocate GL program if this was the last use of shared program
  10994. // assumed there is only single copy of any program in the _programs list
  10995. // (that's how it's constructed)
  10996. var i, il, programInfo;
  10997. var deleteProgram = false;
  10998. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10999. programInfo = _programs[ i ];
  11000. if ( programInfo.program === program ) {
  11001. programInfo.usedTimes --;
  11002. if ( programInfo.usedTimes === 0 ) {
  11003. deleteProgram = true;
  11004. }
  11005. break;
  11006. }
  11007. }
  11008. if ( deleteProgram === true ) {
  11009. // avoid using array.splice, this is costlier than creating new array from scratch
  11010. var newPrograms = [];
  11011. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11012. programInfo = _programs[ i ];
  11013. if ( programInfo.program !== program ) {
  11014. newPrograms.push( programInfo );
  11015. }
  11016. }
  11017. _programs = newPrograms;
  11018. _gl.deleteProgram( program );
  11019. _this.info.memory.programs --;
  11020. }
  11021. };
  11022. //
  11023. /*
  11024. function deleteParticleBuffers ( geometry ) {
  11025. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11026. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11027. deleteCustomAttributesBuffers( geometry );
  11028. _this.info.memory.geometries --;
  11029. };
  11030. function deleteLineBuffers ( geometry ) {
  11031. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11032. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11033. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11034. deleteCustomAttributesBuffers( geometry );
  11035. _this.info.memory.geometries --;
  11036. };
  11037. function deleteRibbonBuffers ( geometry ) {
  11038. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11039. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11040. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11041. deleteCustomAttributesBuffers( geometry );
  11042. _this.info.memory.geometries --;
  11043. };
  11044. function deleteMeshBuffers ( geometryGroup ) {
  11045. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  11046. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  11047. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  11048. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  11049. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  11050. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  11051. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  11052. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  11053. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  11054. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  11055. var m, ml;
  11056. if ( geometryGroup.numMorphTargets ) {
  11057. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11058. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11059. }
  11060. }
  11061. if ( geometryGroup.numMorphNormals ) {
  11062. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11063. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11064. }
  11065. }
  11066. deleteCustomAttributesBuffers( geometryGroup );
  11067. _this.info.memory.geometries --;
  11068. };
  11069. */
  11070. function deleteCustomAttributesBuffers( geometry ) {
  11071. if ( geometry.__webglCustomAttributesList ) {
  11072. for ( var id in geometry.__webglCustomAttributesList ) {
  11073. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11074. }
  11075. }
  11076. };
  11077. // Buffer initialization
  11078. function initCustomAttributes ( geometry, object ) {
  11079. var nvertices = geometry.vertices.length;
  11080. var material = object.material;
  11081. if ( material.attributes ) {
  11082. if ( geometry.__webglCustomAttributesList === undefined ) {
  11083. geometry.__webglCustomAttributesList = [];
  11084. }
  11085. for ( var a in material.attributes ) {
  11086. var attribute = material.attributes[ a ];
  11087. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11088. attribute.__webglInitialized = true;
  11089. var size = 1; // "f" and "i"
  11090. if ( attribute.type === "v2" ) size = 2;
  11091. else if ( attribute.type === "v3" ) size = 3;
  11092. else if ( attribute.type === "v4" ) size = 4;
  11093. else if ( attribute.type === "c" ) size = 3;
  11094. attribute.size = size;
  11095. attribute.array = new Float32Array( nvertices * size );
  11096. attribute.buffer = _gl.createBuffer();
  11097. attribute.buffer.belongsToAttribute = a;
  11098. attribute.needsUpdate = true;
  11099. }
  11100. geometry.__webglCustomAttributesList.push( attribute );
  11101. }
  11102. }
  11103. };
  11104. function initParticleBuffers ( geometry, object ) {
  11105. var nvertices = geometry.vertices.length;
  11106. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11107. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11108. geometry.__sortArray = [];
  11109. geometry.__webglParticleCount = nvertices;
  11110. initCustomAttributes ( geometry, object );
  11111. };
  11112. function initLineBuffers ( geometry, object ) {
  11113. var nvertices = geometry.vertices.length;
  11114. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11115. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11116. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11117. geometry.__webglLineCount = nvertices;
  11118. initCustomAttributes ( geometry, object );
  11119. };
  11120. function initRibbonBuffers ( geometry, object ) {
  11121. var nvertices = geometry.vertices.length;
  11122. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11123. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11124. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11125. geometry.__webglVertexCount = nvertices;
  11126. initCustomAttributes ( geometry, object );
  11127. };
  11128. function initMeshBuffers ( geometryGroup, object ) {
  11129. var geometry = object.geometry,
  11130. faces3 = geometryGroup.faces3,
  11131. faces4 = geometryGroup.faces4,
  11132. nvertices = faces3.length * 3 + faces4.length * 4,
  11133. ntris = faces3.length * 1 + faces4.length * 2,
  11134. nlines = faces3.length * 3 + faces4.length * 4,
  11135. material = getBufferMaterial( object, geometryGroup ),
  11136. uvType = bufferGuessUVType( material ),
  11137. normalType = bufferGuessNormalType( material ),
  11138. vertexColorType = bufferGuessVertexColorType( material );
  11139. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11140. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11141. if ( normalType ) {
  11142. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11143. }
  11144. if ( geometry.hasTangents ) {
  11145. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11146. }
  11147. if ( vertexColorType ) {
  11148. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11149. }
  11150. if ( uvType ) {
  11151. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11152. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11153. }
  11154. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11155. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11156. }
  11157. }
  11158. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11159. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11160. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11161. }
  11162. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11163. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11164. var m, ml;
  11165. if ( geometryGroup.numMorphTargets ) {
  11166. geometryGroup.__morphTargetsArrays = [];
  11167. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11168. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11169. }
  11170. }
  11171. if ( geometryGroup.numMorphNormals ) {
  11172. geometryGroup.__morphNormalsArrays = [];
  11173. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11174. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11175. }
  11176. }
  11177. geometryGroup.__webglFaceCount = ntris * 3;
  11178. geometryGroup.__webglLineCount = nlines * 2;
  11179. // custom attributes
  11180. if ( material.attributes ) {
  11181. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11182. geometryGroup.__webglCustomAttributesList = [];
  11183. }
  11184. for ( var a in material.attributes ) {
  11185. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11186. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11187. var originalAttribute = material.attributes[ a ];
  11188. var attribute = {};
  11189. for ( var property in originalAttribute ) {
  11190. attribute[ property ] = originalAttribute[ property ];
  11191. }
  11192. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11193. attribute.__webglInitialized = true;
  11194. var size = 1; // "f" and "i"
  11195. if( attribute.type === "v2" ) size = 2;
  11196. else if( attribute.type === "v3" ) size = 3;
  11197. else if( attribute.type === "v4" ) size = 4;
  11198. else if( attribute.type === "c" ) size = 3;
  11199. attribute.size = size;
  11200. attribute.array = new Float32Array( nvertices * size );
  11201. attribute.buffer = _gl.createBuffer();
  11202. attribute.buffer.belongsToAttribute = a;
  11203. originalAttribute.needsUpdate = true;
  11204. attribute.__original = originalAttribute;
  11205. }
  11206. geometryGroup.__webglCustomAttributesList.push( attribute );
  11207. }
  11208. }
  11209. geometryGroup.__inittedArrays = true;
  11210. };
  11211. function getBufferMaterial( object, geometryGroup ) {
  11212. return object.material instanceof THREE.MeshFaceMaterial
  11213. ? object.material.materials[ geometryGroup.materialIndex ]
  11214. : object.material;
  11215. };
  11216. function materialNeedsSmoothNormals ( material ) {
  11217. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11218. };
  11219. function bufferGuessNormalType ( material ) {
  11220. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  11221. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  11222. return false;
  11223. }
  11224. if ( materialNeedsSmoothNormals( material ) ) {
  11225. return THREE.SmoothShading;
  11226. } else {
  11227. return THREE.FlatShading;
  11228. }
  11229. };
  11230. function bufferGuessVertexColorType ( material ) {
  11231. if ( material.vertexColors ) {
  11232. return material.vertexColors;
  11233. }
  11234. return false;
  11235. };
  11236. function bufferGuessUVType ( material ) {
  11237. // material must use some texture to require uvs
  11238. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  11239. return true;
  11240. }
  11241. return false;
  11242. };
  11243. //
  11244. function initDirectBuffers( geometry ) {
  11245. var a, attribute, type;
  11246. for ( a in geometry.attributes ) {
  11247. if ( a === "index" ) {
  11248. type = _gl.ELEMENT_ARRAY_BUFFER;
  11249. } else {
  11250. type = _gl.ARRAY_BUFFER;
  11251. }
  11252. attribute = geometry.attributes[ a ];
  11253. attribute.buffer = _gl.createBuffer();
  11254. _gl.bindBuffer( type, attribute.buffer );
  11255. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  11256. }
  11257. };
  11258. // Buffer setting
  11259. function setParticleBuffers ( geometry, hint, object ) {
  11260. var v, c, vertex, offset, index, color,
  11261. vertices = geometry.vertices,
  11262. vl = vertices.length,
  11263. colors = geometry.colors,
  11264. cl = colors.length,
  11265. vertexArray = geometry.__vertexArray,
  11266. colorArray = geometry.__colorArray,
  11267. sortArray = geometry.__sortArray,
  11268. dirtyVertices = geometry.verticesNeedUpdate,
  11269. dirtyElements = geometry.elementsNeedUpdate,
  11270. dirtyColors = geometry.colorsNeedUpdate,
  11271. customAttributes = geometry.__webglCustomAttributesList,
  11272. i, il,
  11273. a, ca, cal, value,
  11274. customAttribute;
  11275. if ( object.sortParticles ) {
  11276. _projScreenMatrixPS.copy( _projScreenMatrix );
  11277. _projScreenMatrixPS.multiply( object.matrixWorld );
  11278. for ( v = 0; v < vl; v ++ ) {
  11279. vertex = vertices[ v ];
  11280. _vector3.copy( vertex );
  11281. _vector3.applyProjection( _projScreenMatrixPS );
  11282. sortArray[ v ] = [ _vector3.z, v ];
  11283. }
  11284. sortArray.sort( numericalSort );
  11285. for ( v = 0; v < vl; v ++ ) {
  11286. vertex = vertices[ sortArray[v][1] ];
  11287. offset = v * 3;
  11288. vertexArray[ offset ] = vertex.x;
  11289. vertexArray[ offset + 1 ] = vertex.y;
  11290. vertexArray[ offset + 2 ] = vertex.z;
  11291. }
  11292. for ( c = 0; c < cl; c ++ ) {
  11293. offset = c * 3;
  11294. color = colors[ sortArray[c][1] ];
  11295. colorArray[ offset ] = color.r;
  11296. colorArray[ offset + 1 ] = color.g;
  11297. colorArray[ offset + 2 ] = color.b;
  11298. }
  11299. if ( customAttributes ) {
  11300. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11301. customAttribute = customAttributes[ i ];
  11302. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  11303. offset = 0;
  11304. cal = customAttribute.value.length;
  11305. if ( customAttribute.size === 1 ) {
  11306. for ( ca = 0; ca < cal; ca ++ ) {
  11307. index = sortArray[ ca ][ 1 ];
  11308. customAttribute.array[ ca ] = customAttribute.value[ index ];
  11309. }
  11310. } else if ( customAttribute.size === 2 ) {
  11311. for ( ca = 0; ca < cal; ca ++ ) {
  11312. index = sortArray[ ca ][ 1 ];
  11313. value = customAttribute.value[ index ];
  11314. customAttribute.array[ offset ] = value.x;
  11315. customAttribute.array[ offset + 1 ] = value.y;
  11316. offset += 2;
  11317. }
  11318. } else if ( customAttribute.size === 3 ) {
  11319. if ( customAttribute.type === "c" ) {
  11320. for ( ca = 0; ca < cal; ca ++ ) {
  11321. index = sortArray[ ca ][ 1 ];
  11322. value = customAttribute.value[ index ];
  11323. customAttribute.array[ offset ] = value.r;
  11324. customAttribute.array[ offset + 1 ] = value.g;
  11325. customAttribute.array[ offset + 2 ] = value.b;
  11326. offset += 3;
  11327. }
  11328. } else {
  11329. for ( ca = 0; ca < cal; ca ++ ) {
  11330. index = sortArray[ ca ][ 1 ];
  11331. value = customAttribute.value[ index ];
  11332. customAttribute.array[ offset ] = value.x;
  11333. customAttribute.array[ offset + 1 ] = value.y;
  11334. customAttribute.array[ offset + 2 ] = value.z;
  11335. offset += 3;
  11336. }
  11337. }
  11338. } else if ( customAttribute.size === 4 ) {
  11339. for ( ca = 0; ca < cal; ca ++ ) {
  11340. index = sortArray[ ca ][ 1 ];
  11341. value = customAttribute.value[ index ];
  11342. customAttribute.array[ offset ] = value.x;
  11343. customAttribute.array[ offset + 1 ] = value.y;
  11344. customAttribute.array[ offset + 2 ] = value.z;
  11345. customAttribute.array[ offset + 3 ] = value.w;
  11346. offset += 4;
  11347. }
  11348. }
  11349. }
  11350. }
  11351. } else {
  11352. if ( dirtyVertices ) {
  11353. for ( v = 0; v < vl; v ++ ) {
  11354. vertex = vertices[ v ];
  11355. offset = v * 3;
  11356. vertexArray[ offset ] = vertex.x;
  11357. vertexArray[ offset + 1 ] = vertex.y;
  11358. vertexArray[ offset + 2 ] = vertex.z;
  11359. }
  11360. }
  11361. if ( dirtyColors ) {
  11362. for ( c = 0; c < cl; c ++ ) {
  11363. color = colors[ c ];
  11364. offset = c * 3;
  11365. colorArray[ offset ] = color.r;
  11366. colorArray[ offset + 1 ] = color.g;
  11367. colorArray[ offset + 2 ] = color.b;
  11368. }
  11369. }
  11370. if ( customAttributes ) {
  11371. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11372. customAttribute = customAttributes[ i ];
  11373. if ( customAttribute.needsUpdate &&
  11374. ( customAttribute.boundTo === undefined ||
  11375. customAttribute.boundTo === "vertices") ) {
  11376. cal = customAttribute.value.length;
  11377. offset = 0;
  11378. if ( customAttribute.size === 1 ) {
  11379. for ( ca = 0; ca < cal; ca ++ ) {
  11380. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11381. }
  11382. } else if ( customAttribute.size === 2 ) {
  11383. for ( ca = 0; ca < cal; ca ++ ) {
  11384. value = customAttribute.value[ ca ];
  11385. customAttribute.array[ offset ] = value.x;
  11386. customAttribute.array[ offset + 1 ] = value.y;
  11387. offset += 2;
  11388. }
  11389. } else if ( customAttribute.size === 3 ) {
  11390. if ( customAttribute.type === "c" ) {
  11391. for ( ca = 0; ca < cal; ca ++ ) {
  11392. value = customAttribute.value[ ca ];
  11393. customAttribute.array[ offset ] = value.r;
  11394. customAttribute.array[ offset + 1 ] = value.g;
  11395. customAttribute.array[ offset + 2 ] = value.b;
  11396. offset += 3;
  11397. }
  11398. } else {
  11399. for ( ca = 0; ca < cal; ca ++ ) {
  11400. value = customAttribute.value[ ca ];
  11401. customAttribute.array[ offset ] = value.x;
  11402. customAttribute.array[ offset + 1 ] = value.y;
  11403. customAttribute.array[ offset + 2 ] = value.z;
  11404. offset += 3;
  11405. }
  11406. }
  11407. } else if ( customAttribute.size === 4 ) {
  11408. for ( ca = 0; ca < cal; ca ++ ) {
  11409. value = customAttribute.value[ ca ];
  11410. customAttribute.array[ offset ] = value.x;
  11411. customAttribute.array[ offset + 1 ] = value.y;
  11412. customAttribute.array[ offset + 2 ] = value.z;
  11413. customAttribute.array[ offset + 3 ] = value.w;
  11414. offset += 4;
  11415. }
  11416. }
  11417. }
  11418. }
  11419. }
  11420. }
  11421. if ( dirtyVertices || object.sortParticles ) {
  11422. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11423. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11424. }
  11425. if ( dirtyColors || object.sortParticles ) {
  11426. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11427. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11428. }
  11429. if ( customAttributes ) {
  11430. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11431. customAttribute = customAttributes[ i ];
  11432. if ( customAttribute.needsUpdate || object.sortParticles ) {
  11433. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11434. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11435. }
  11436. }
  11437. }
  11438. };
  11439. function setLineBuffers ( geometry, hint ) {
  11440. var v, c, d, vertex, offset, color,
  11441. vertices = geometry.vertices,
  11442. colors = geometry.colors,
  11443. lineDistances = geometry.lineDistances,
  11444. vl = vertices.length,
  11445. cl = colors.length,
  11446. dl = lineDistances.length,
  11447. vertexArray = geometry.__vertexArray,
  11448. colorArray = geometry.__colorArray,
  11449. lineDistanceArray = geometry.__lineDistanceArray,
  11450. dirtyVertices = geometry.verticesNeedUpdate,
  11451. dirtyColors = geometry.colorsNeedUpdate,
  11452. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11453. customAttributes = geometry.__webglCustomAttributesList,
  11454. i, il,
  11455. a, ca, cal, value,
  11456. customAttribute;
  11457. if ( dirtyVertices ) {
  11458. for ( v = 0; v < vl; v ++ ) {
  11459. vertex = vertices[ v ];
  11460. offset = v * 3;
  11461. vertexArray[ offset ] = vertex.x;
  11462. vertexArray[ offset + 1 ] = vertex.y;
  11463. vertexArray[ offset + 2 ] = vertex.z;
  11464. }
  11465. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11466. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11467. }
  11468. if ( dirtyColors ) {
  11469. for ( c = 0; c < cl; c ++ ) {
  11470. color = colors[ c ];
  11471. offset = c * 3;
  11472. colorArray[ offset ] = color.r;
  11473. colorArray[ offset + 1 ] = color.g;
  11474. colorArray[ offset + 2 ] = color.b;
  11475. }
  11476. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11477. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11478. }
  11479. if ( dirtyLineDistances ) {
  11480. for ( d = 0; d < dl; d ++ ) {
  11481. lineDistanceArray[ d ] = lineDistances[ d ];
  11482. }
  11483. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11484. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11485. }
  11486. if ( customAttributes ) {
  11487. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11488. customAttribute = customAttributes[ i ];
  11489. if ( customAttribute.needsUpdate &&
  11490. ( customAttribute.boundTo === undefined ||
  11491. customAttribute.boundTo === "vertices" ) ) {
  11492. offset = 0;
  11493. cal = customAttribute.value.length;
  11494. if ( customAttribute.size === 1 ) {
  11495. for ( ca = 0; ca < cal; ca ++ ) {
  11496. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11497. }
  11498. } else if ( customAttribute.size === 2 ) {
  11499. for ( ca = 0; ca < cal; ca ++ ) {
  11500. value = customAttribute.value[ ca ];
  11501. customAttribute.array[ offset ] = value.x;
  11502. customAttribute.array[ offset + 1 ] = value.y;
  11503. offset += 2;
  11504. }
  11505. } else if ( customAttribute.size === 3 ) {
  11506. if ( customAttribute.type === "c" ) {
  11507. for ( ca = 0; ca < cal; ca ++ ) {
  11508. value = customAttribute.value[ ca ];
  11509. customAttribute.array[ offset ] = value.r;
  11510. customAttribute.array[ offset + 1 ] = value.g;
  11511. customAttribute.array[ offset + 2 ] = value.b;
  11512. offset += 3;
  11513. }
  11514. } else {
  11515. for ( ca = 0; ca < cal; ca ++ ) {
  11516. value = customAttribute.value[ ca ];
  11517. customAttribute.array[ offset ] = value.x;
  11518. customAttribute.array[ offset + 1 ] = value.y;
  11519. customAttribute.array[ offset + 2 ] = value.z;
  11520. offset += 3;
  11521. }
  11522. }
  11523. } else if ( customAttribute.size === 4 ) {
  11524. for ( ca = 0; ca < cal; ca ++ ) {
  11525. value = customAttribute.value[ ca ];
  11526. customAttribute.array[ offset ] = value.x;
  11527. customAttribute.array[ offset + 1 ] = value.y;
  11528. customAttribute.array[ offset + 2 ] = value.z;
  11529. customAttribute.array[ offset + 3 ] = value.w;
  11530. offset += 4;
  11531. }
  11532. }
  11533. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11534. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11535. }
  11536. }
  11537. }
  11538. };
  11539. function setRibbonBuffers ( geometry, hint ) {
  11540. var v, c, n, vertex, offset, color, normal,
  11541. i, il, ca, cal, customAttribute, value,
  11542. vertices = geometry.vertices,
  11543. colors = geometry.colors,
  11544. normals = geometry.normals,
  11545. vl = vertices.length,
  11546. cl = colors.length,
  11547. nl = normals.length,
  11548. vertexArray = geometry.__vertexArray,
  11549. colorArray = geometry.__colorArray,
  11550. normalArray = geometry.__normalArray,
  11551. dirtyVertices = geometry.verticesNeedUpdate,
  11552. dirtyColors = geometry.colorsNeedUpdate,
  11553. dirtyNormals = geometry.normalsNeedUpdate,
  11554. customAttributes = geometry.__webglCustomAttributesList;
  11555. if ( dirtyVertices ) {
  11556. for ( v = 0; v < vl; v ++ ) {
  11557. vertex = vertices[ v ];
  11558. offset = v * 3;
  11559. vertexArray[ offset ] = vertex.x;
  11560. vertexArray[ offset + 1 ] = vertex.y;
  11561. vertexArray[ offset + 2 ] = vertex.z;
  11562. }
  11563. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11564. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11565. }
  11566. if ( dirtyColors ) {
  11567. for ( c = 0; c < cl; c ++ ) {
  11568. color = colors[ c ];
  11569. offset = c * 3;
  11570. colorArray[ offset ] = color.r;
  11571. colorArray[ offset + 1 ] = color.g;
  11572. colorArray[ offset + 2 ] = color.b;
  11573. }
  11574. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11575. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11576. }
  11577. if ( dirtyNormals ) {
  11578. for ( n = 0; n < nl; n ++ ) {
  11579. normal = normals[ n ];
  11580. offset = n * 3;
  11581. normalArray[ offset ] = normal.x;
  11582. normalArray[ offset + 1 ] = normal.y;
  11583. normalArray[ offset + 2 ] = normal.z;
  11584. }
  11585. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11586. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11587. }
  11588. if ( customAttributes ) {
  11589. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11590. customAttribute = customAttributes[ i ];
  11591. if ( customAttribute.needsUpdate &&
  11592. ( customAttribute.boundTo === undefined ||
  11593. customAttribute.boundTo === "vertices" ) ) {
  11594. offset = 0;
  11595. cal = customAttribute.value.length;
  11596. if ( customAttribute.size === 1 ) {
  11597. for ( ca = 0; ca < cal; ca ++ ) {
  11598. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11599. }
  11600. } else if ( customAttribute.size === 2 ) {
  11601. for ( ca = 0; ca < cal; ca ++ ) {
  11602. value = customAttribute.value[ ca ];
  11603. customAttribute.array[ offset ] = value.x;
  11604. customAttribute.array[ offset + 1 ] = value.y;
  11605. offset += 2;
  11606. }
  11607. } else if ( customAttribute.size === 3 ) {
  11608. if ( customAttribute.type === "c" ) {
  11609. for ( ca = 0; ca < cal; ca ++ ) {
  11610. value = customAttribute.value[ ca ];
  11611. customAttribute.array[ offset ] = value.r;
  11612. customAttribute.array[ offset + 1 ] = value.g;
  11613. customAttribute.array[ offset + 2 ] = value.b;
  11614. offset += 3;
  11615. }
  11616. } else {
  11617. for ( ca = 0; ca < cal; ca ++ ) {
  11618. value = customAttribute.value[ ca ];
  11619. customAttribute.array[ offset ] = value.x;
  11620. customAttribute.array[ offset + 1 ] = value.y;
  11621. customAttribute.array[ offset + 2 ] = value.z;
  11622. offset += 3;
  11623. }
  11624. }
  11625. } else if ( customAttribute.size === 4 ) {
  11626. for ( ca = 0; ca < cal; ca ++ ) {
  11627. value = customAttribute.value[ ca ];
  11628. customAttribute.array[ offset ] = value.x;
  11629. customAttribute.array[ offset + 1 ] = value.y;
  11630. customAttribute.array[ offset + 2 ] = value.z;
  11631. customAttribute.array[ offset + 3 ] = value.w;
  11632. offset += 4;
  11633. }
  11634. }
  11635. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11636. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11637. }
  11638. }
  11639. }
  11640. };
  11641. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11642. if ( ! geometryGroup.__inittedArrays ) {
  11643. return;
  11644. }
  11645. var normalType = bufferGuessNormalType( material ),
  11646. vertexColorType = bufferGuessVertexColorType( material ),
  11647. uvType = bufferGuessUVType( material ),
  11648. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11649. var f, fl, fi, face,
  11650. vertexNormals, faceNormal, normal,
  11651. vertexColors, faceColor,
  11652. vertexTangents,
  11653. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11654. c1, c2, c3, c4,
  11655. sw1, sw2, sw3, sw4,
  11656. si1, si2, si3, si4,
  11657. sa1, sa2, sa3, sa4,
  11658. sb1, sb2, sb3, sb4,
  11659. m, ml, i, il,
  11660. vn, uvi, uv2i,
  11661. vk, vkl, vka,
  11662. nka, chf, faceVertexNormals,
  11663. a,
  11664. vertexIndex = 0,
  11665. offset = 0,
  11666. offset_uv = 0,
  11667. offset_uv2 = 0,
  11668. offset_face = 0,
  11669. offset_normal = 0,
  11670. offset_tangent = 0,
  11671. offset_line = 0,
  11672. offset_color = 0,
  11673. offset_skin = 0,
  11674. offset_morphTarget = 0,
  11675. offset_custom = 0,
  11676. offset_customSrc = 0,
  11677. value,
  11678. vertexArray = geometryGroup.__vertexArray,
  11679. uvArray = geometryGroup.__uvArray,
  11680. uv2Array = geometryGroup.__uv2Array,
  11681. normalArray = geometryGroup.__normalArray,
  11682. tangentArray = geometryGroup.__tangentArray,
  11683. colorArray = geometryGroup.__colorArray,
  11684. skinIndexArray = geometryGroup.__skinIndexArray,
  11685. skinWeightArray = geometryGroup.__skinWeightArray,
  11686. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11687. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11688. customAttributes = geometryGroup.__webglCustomAttributesList,
  11689. customAttribute,
  11690. faceArray = geometryGroup.__faceArray,
  11691. lineArray = geometryGroup.__lineArray,
  11692. geometry = object.geometry, // this is shared for all chunks
  11693. dirtyVertices = geometry.verticesNeedUpdate,
  11694. dirtyElements = geometry.elementsNeedUpdate,
  11695. dirtyUvs = geometry.uvsNeedUpdate,
  11696. dirtyNormals = geometry.normalsNeedUpdate,
  11697. dirtyTangents = geometry.tangentsNeedUpdate,
  11698. dirtyColors = geometry.colorsNeedUpdate,
  11699. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11700. vertices = geometry.vertices,
  11701. chunk_faces3 = geometryGroup.faces3,
  11702. chunk_faces4 = geometryGroup.faces4,
  11703. obj_faces = geometry.faces,
  11704. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11705. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11706. obj_colors = geometry.colors,
  11707. obj_skinIndices = geometry.skinIndices,
  11708. obj_skinWeights = geometry.skinWeights,
  11709. morphTargets = geometry.morphTargets,
  11710. morphNormals = geometry.morphNormals;
  11711. if ( dirtyVertices ) {
  11712. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11713. face = obj_faces[ chunk_faces3[ f ] ];
  11714. v1 = vertices[ face.a ];
  11715. v2 = vertices[ face.b ];
  11716. v3 = vertices[ face.c ];
  11717. vertexArray[ offset ] = v1.x;
  11718. vertexArray[ offset + 1 ] = v1.y;
  11719. vertexArray[ offset + 2 ] = v1.z;
  11720. vertexArray[ offset + 3 ] = v2.x;
  11721. vertexArray[ offset + 4 ] = v2.y;
  11722. vertexArray[ offset + 5 ] = v2.z;
  11723. vertexArray[ offset + 6 ] = v3.x;
  11724. vertexArray[ offset + 7 ] = v3.y;
  11725. vertexArray[ offset + 8 ] = v3.z;
  11726. offset += 9;
  11727. }
  11728. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11729. face = obj_faces[ chunk_faces4[ f ] ];
  11730. v1 = vertices[ face.a ];
  11731. v2 = vertices[ face.b ];
  11732. v3 = vertices[ face.c ];
  11733. v4 = vertices[ face.d ];
  11734. vertexArray[ offset ] = v1.x;
  11735. vertexArray[ offset + 1 ] = v1.y;
  11736. vertexArray[ offset + 2 ] = v1.z;
  11737. vertexArray[ offset + 3 ] = v2.x;
  11738. vertexArray[ offset + 4 ] = v2.y;
  11739. vertexArray[ offset + 5 ] = v2.z;
  11740. vertexArray[ offset + 6 ] = v3.x;
  11741. vertexArray[ offset + 7 ] = v3.y;
  11742. vertexArray[ offset + 8 ] = v3.z;
  11743. vertexArray[ offset + 9 ] = v4.x;
  11744. vertexArray[ offset + 10 ] = v4.y;
  11745. vertexArray[ offset + 11 ] = v4.z;
  11746. offset += 12;
  11747. }
  11748. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11749. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11750. }
  11751. if ( dirtyMorphTargets ) {
  11752. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11753. offset_morphTarget = 0;
  11754. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11755. chf = chunk_faces3[ f ];
  11756. face = obj_faces[ chf ];
  11757. // morph positions
  11758. v1 = morphTargets[ vk ].vertices[ face.a ];
  11759. v2 = morphTargets[ vk ].vertices[ face.b ];
  11760. v3 = morphTargets[ vk ].vertices[ face.c ];
  11761. vka = morphTargetsArrays[ vk ];
  11762. vka[ offset_morphTarget ] = v1.x;
  11763. vka[ offset_morphTarget + 1 ] = v1.y;
  11764. vka[ offset_morphTarget + 2 ] = v1.z;
  11765. vka[ offset_morphTarget + 3 ] = v2.x;
  11766. vka[ offset_morphTarget + 4 ] = v2.y;
  11767. vka[ offset_morphTarget + 5 ] = v2.z;
  11768. vka[ offset_morphTarget + 6 ] = v3.x;
  11769. vka[ offset_morphTarget + 7 ] = v3.y;
  11770. vka[ offset_morphTarget + 8 ] = v3.z;
  11771. // morph normals
  11772. if ( material.morphNormals ) {
  11773. if ( needsSmoothNormals ) {
  11774. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11775. n1 = faceVertexNormals.a;
  11776. n2 = faceVertexNormals.b;
  11777. n3 = faceVertexNormals.c;
  11778. } else {
  11779. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11780. n2 = n1;
  11781. n3 = n1;
  11782. }
  11783. nka = morphNormalsArrays[ vk ];
  11784. nka[ offset_morphTarget ] = n1.x;
  11785. nka[ offset_morphTarget + 1 ] = n1.y;
  11786. nka[ offset_morphTarget + 2 ] = n1.z;
  11787. nka[ offset_morphTarget + 3 ] = n2.x;
  11788. nka[ offset_morphTarget + 4 ] = n2.y;
  11789. nka[ offset_morphTarget + 5 ] = n2.z;
  11790. nka[ offset_morphTarget + 6 ] = n3.x;
  11791. nka[ offset_morphTarget + 7 ] = n3.y;
  11792. nka[ offset_morphTarget + 8 ] = n3.z;
  11793. }
  11794. //
  11795. offset_morphTarget += 9;
  11796. }
  11797. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11798. chf = chunk_faces4[ f ];
  11799. face = obj_faces[ chf ];
  11800. // morph positions
  11801. v1 = morphTargets[ vk ].vertices[ face.a ];
  11802. v2 = morphTargets[ vk ].vertices[ face.b ];
  11803. v3 = morphTargets[ vk ].vertices[ face.c ];
  11804. v4 = morphTargets[ vk ].vertices[ face.d ];
  11805. vka = morphTargetsArrays[ vk ];
  11806. vka[ offset_morphTarget ] = v1.x;
  11807. vka[ offset_morphTarget + 1 ] = v1.y;
  11808. vka[ offset_morphTarget + 2 ] = v1.z;
  11809. vka[ offset_morphTarget + 3 ] = v2.x;
  11810. vka[ offset_morphTarget + 4 ] = v2.y;
  11811. vka[ offset_morphTarget + 5 ] = v2.z;
  11812. vka[ offset_morphTarget + 6 ] = v3.x;
  11813. vka[ offset_morphTarget + 7 ] = v3.y;
  11814. vka[ offset_morphTarget + 8 ] = v3.z;
  11815. vka[ offset_morphTarget + 9 ] = v4.x;
  11816. vka[ offset_morphTarget + 10 ] = v4.y;
  11817. vka[ offset_morphTarget + 11 ] = v4.z;
  11818. // morph normals
  11819. if ( material.morphNormals ) {
  11820. if ( needsSmoothNormals ) {
  11821. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11822. n1 = faceVertexNormals.a;
  11823. n2 = faceVertexNormals.b;
  11824. n3 = faceVertexNormals.c;
  11825. n4 = faceVertexNormals.d;
  11826. } else {
  11827. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11828. n2 = n1;
  11829. n3 = n1;
  11830. n4 = n1;
  11831. }
  11832. nka = morphNormalsArrays[ vk ];
  11833. nka[ offset_morphTarget ] = n1.x;
  11834. nka[ offset_morphTarget + 1 ] = n1.y;
  11835. nka[ offset_morphTarget + 2 ] = n1.z;
  11836. nka[ offset_morphTarget + 3 ] = n2.x;
  11837. nka[ offset_morphTarget + 4 ] = n2.y;
  11838. nka[ offset_morphTarget + 5 ] = n2.z;
  11839. nka[ offset_morphTarget + 6 ] = n3.x;
  11840. nka[ offset_morphTarget + 7 ] = n3.y;
  11841. nka[ offset_morphTarget + 8 ] = n3.z;
  11842. nka[ offset_morphTarget + 9 ] = n4.x;
  11843. nka[ offset_morphTarget + 10 ] = n4.y;
  11844. nka[ offset_morphTarget + 11 ] = n4.z;
  11845. }
  11846. //
  11847. offset_morphTarget += 12;
  11848. }
  11849. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11850. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11851. if ( material.morphNormals ) {
  11852. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11853. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11854. }
  11855. }
  11856. }
  11857. if ( obj_skinWeights.length ) {
  11858. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11859. face = obj_faces[ chunk_faces3[ f ] ];
  11860. // weights
  11861. sw1 = obj_skinWeights[ face.a ];
  11862. sw2 = obj_skinWeights[ face.b ];
  11863. sw3 = obj_skinWeights[ face.c ];
  11864. skinWeightArray[ offset_skin ] = sw1.x;
  11865. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11866. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11867. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11868. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11869. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11870. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11871. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11872. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11873. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11874. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11875. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11876. // indices
  11877. si1 = obj_skinIndices[ face.a ];
  11878. si2 = obj_skinIndices[ face.b ];
  11879. si3 = obj_skinIndices[ face.c ];
  11880. skinIndexArray[ offset_skin ] = si1.x;
  11881. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11882. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11883. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11884. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11885. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11886. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11887. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11888. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11889. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11890. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11891. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11892. offset_skin += 12;
  11893. }
  11894. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11895. face = obj_faces[ chunk_faces4[ f ] ];
  11896. // weights
  11897. sw1 = obj_skinWeights[ face.a ];
  11898. sw2 = obj_skinWeights[ face.b ];
  11899. sw3 = obj_skinWeights[ face.c ];
  11900. sw4 = obj_skinWeights[ face.d ];
  11901. skinWeightArray[ offset_skin ] = sw1.x;
  11902. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11903. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11904. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11905. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11906. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11907. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11908. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11909. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11910. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11911. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11912. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11913. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11914. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11915. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11916. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11917. // indices
  11918. si1 = obj_skinIndices[ face.a ];
  11919. si2 = obj_skinIndices[ face.b ];
  11920. si3 = obj_skinIndices[ face.c ];
  11921. si4 = obj_skinIndices[ face.d ];
  11922. skinIndexArray[ offset_skin ] = si1.x;
  11923. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11924. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11925. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11926. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11927. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11928. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11929. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11930. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11931. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11932. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11933. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11934. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11935. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11936. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11937. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11938. offset_skin += 16;
  11939. }
  11940. if ( offset_skin > 0 ) {
  11941. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11942. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11943. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11944. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11945. }
  11946. }
  11947. if ( dirtyColors && vertexColorType ) {
  11948. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11949. face = obj_faces[ chunk_faces3[ f ] ];
  11950. vertexColors = face.vertexColors;
  11951. faceColor = face.color;
  11952. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  11953. c1 = vertexColors[ 0 ];
  11954. c2 = vertexColors[ 1 ];
  11955. c3 = vertexColors[ 2 ];
  11956. } else {
  11957. c1 = faceColor;
  11958. c2 = faceColor;
  11959. c3 = faceColor;
  11960. }
  11961. colorArray[ offset_color ] = c1.r;
  11962. colorArray[ offset_color + 1 ] = c1.g;
  11963. colorArray[ offset_color + 2 ] = c1.b;
  11964. colorArray[ offset_color + 3 ] = c2.r;
  11965. colorArray[ offset_color + 4 ] = c2.g;
  11966. colorArray[ offset_color + 5 ] = c2.b;
  11967. colorArray[ offset_color + 6 ] = c3.r;
  11968. colorArray[ offset_color + 7 ] = c3.g;
  11969. colorArray[ offset_color + 8 ] = c3.b;
  11970. offset_color += 9;
  11971. }
  11972. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11973. face = obj_faces[ chunk_faces4[ f ] ];
  11974. vertexColors = face.vertexColors;
  11975. faceColor = face.color;
  11976. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  11977. c1 = vertexColors[ 0 ];
  11978. c2 = vertexColors[ 1 ];
  11979. c3 = vertexColors[ 2 ];
  11980. c4 = vertexColors[ 3 ];
  11981. } else {
  11982. c1 = faceColor;
  11983. c2 = faceColor;
  11984. c3 = faceColor;
  11985. c4 = faceColor;
  11986. }
  11987. colorArray[ offset_color ] = c1.r;
  11988. colorArray[ offset_color + 1 ] = c1.g;
  11989. colorArray[ offset_color + 2 ] = c1.b;
  11990. colorArray[ offset_color + 3 ] = c2.r;
  11991. colorArray[ offset_color + 4 ] = c2.g;
  11992. colorArray[ offset_color + 5 ] = c2.b;
  11993. colorArray[ offset_color + 6 ] = c3.r;
  11994. colorArray[ offset_color + 7 ] = c3.g;
  11995. colorArray[ offset_color + 8 ] = c3.b;
  11996. colorArray[ offset_color + 9 ] = c4.r;
  11997. colorArray[ offset_color + 10 ] = c4.g;
  11998. colorArray[ offset_color + 11 ] = c4.b;
  11999. offset_color += 12;
  12000. }
  12001. if ( offset_color > 0 ) {
  12002. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12003. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12004. }
  12005. }
  12006. if ( dirtyTangents && geometry.hasTangents ) {
  12007. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12008. face = obj_faces[ chunk_faces3[ f ] ];
  12009. vertexTangents = face.vertexTangents;
  12010. t1 = vertexTangents[ 0 ];
  12011. t2 = vertexTangents[ 1 ];
  12012. t3 = vertexTangents[ 2 ];
  12013. tangentArray[ offset_tangent ] = t1.x;
  12014. tangentArray[ offset_tangent + 1 ] = t1.y;
  12015. tangentArray[ offset_tangent + 2 ] = t1.z;
  12016. tangentArray[ offset_tangent + 3 ] = t1.w;
  12017. tangentArray[ offset_tangent + 4 ] = t2.x;
  12018. tangentArray[ offset_tangent + 5 ] = t2.y;
  12019. tangentArray[ offset_tangent + 6 ] = t2.z;
  12020. tangentArray[ offset_tangent + 7 ] = t2.w;
  12021. tangentArray[ offset_tangent + 8 ] = t3.x;
  12022. tangentArray[ offset_tangent + 9 ] = t3.y;
  12023. tangentArray[ offset_tangent + 10 ] = t3.z;
  12024. tangentArray[ offset_tangent + 11 ] = t3.w;
  12025. offset_tangent += 12;
  12026. }
  12027. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12028. face = obj_faces[ chunk_faces4[ f ] ];
  12029. vertexTangents = face.vertexTangents;
  12030. t1 = vertexTangents[ 0 ];
  12031. t2 = vertexTangents[ 1 ];
  12032. t3 = vertexTangents[ 2 ];
  12033. t4 = vertexTangents[ 3 ];
  12034. tangentArray[ offset_tangent ] = t1.x;
  12035. tangentArray[ offset_tangent + 1 ] = t1.y;
  12036. tangentArray[ offset_tangent + 2 ] = t1.z;
  12037. tangentArray[ offset_tangent + 3 ] = t1.w;
  12038. tangentArray[ offset_tangent + 4 ] = t2.x;
  12039. tangentArray[ offset_tangent + 5 ] = t2.y;
  12040. tangentArray[ offset_tangent + 6 ] = t2.z;
  12041. tangentArray[ offset_tangent + 7 ] = t2.w;
  12042. tangentArray[ offset_tangent + 8 ] = t3.x;
  12043. tangentArray[ offset_tangent + 9 ] = t3.y;
  12044. tangentArray[ offset_tangent + 10 ] = t3.z;
  12045. tangentArray[ offset_tangent + 11 ] = t3.w;
  12046. tangentArray[ offset_tangent + 12 ] = t4.x;
  12047. tangentArray[ offset_tangent + 13 ] = t4.y;
  12048. tangentArray[ offset_tangent + 14 ] = t4.z;
  12049. tangentArray[ offset_tangent + 15 ] = t4.w;
  12050. offset_tangent += 16;
  12051. }
  12052. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12053. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12054. }
  12055. if ( dirtyNormals && normalType ) {
  12056. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12057. face = obj_faces[ chunk_faces3[ f ] ];
  12058. vertexNormals = face.vertexNormals;
  12059. faceNormal = face.normal;
  12060. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12061. for ( i = 0; i < 3; i ++ ) {
  12062. vn = vertexNormals[ i ];
  12063. normalArray[ offset_normal ] = vn.x;
  12064. normalArray[ offset_normal + 1 ] = vn.y;
  12065. normalArray[ offset_normal + 2 ] = vn.z;
  12066. offset_normal += 3;
  12067. }
  12068. } else {
  12069. for ( i = 0; i < 3; i ++ ) {
  12070. normalArray[ offset_normal ] = faceNormal.x;
  12071. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12072. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12073. offset_normal += 3;
  12074. }
  12075. }
  12076. }
  12077. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12078. face = obj_faces[ chunk_faces4[ f ] ];
  12079. vertexNormals = face.vertexNormals;
  12080. faceNormal = face.normal;
  12081. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12082. for ( i = 0; i < 4; i ++ ) {
  12083. vn = vertexNormals[ i ];
  12084. normalArray[ offset_normal ] = vn.x;
  12085. normalArray[ offset_normal + 1 ] = vn.y;
  12086. normalArray[ offset_normal + 2 ] = vn.z;
  12087. offset_normal += 3;
  12088. }
  12089. } else {
  12090. for ( i = 0; i < 4; i ++ ) {
  12091. normalArray[ offset_normal ] = faceNormal.x;
  12092. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12093. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12094. offset_normal += 3;
  12095. }
  12096. }
  12097. }
  12098. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12099. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12100. }
  12101. if ( dirtyUvs && obj_uvs && uvType ) {
  12102. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12103. fi = chunk_faces3[ f ];
  12104. uv = obj_uvs[ fi ];
  12105. if ( uv === undefined ) continue;
  12106. for ( i = 0; i < 3; i ++ ) {
  12107. uvi = uv[ i ];
  12108. uvArray[ offset_uv ] = uvi.x;
  12109. uvArray[ offset_uv + 1 ] = uvi.y;
  12110. offset_uv += 2;
  12111. }
  12112. }
  12113. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12114. fi = chunk_faces4[ f ];
  12115. uv = obj_uvs[ fi ];
  12116. if ( uv === undefined ) continue;
  12117. for ( i = 0; i < 4; i ++ ) {
  12118. uvi = uv[ i ];
  12119. uvArray[ offset_uv ] = uvi.x;
  12120. uvArray[ offset_uv + 1 ] = uvi.y;
  12121. offset_uv += 2;
  12122. }
  12123. }
  12124. if ( offset_uv > 0 ) {
  12125. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12126. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12127. }
  12128. }
  12129. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12130. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12131. fi = chunk_faces3[ f ];
  12132. uv2 = obj_uvs2[ fi ];
  12133. if ( uv2 === undefined ) continue;
  12134. for ( i = 0; i < 3; i ++ ) {
  12135. uv2i = uv2[ i ];
  12136. uv2Array[ offset_uv2 ] = uv2i.x;
  12137. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12138. offset_uv2 += 2;
  12139. }
  12140. }
  12141. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12142. fi = chunk_faces4[ f ];
  12143. uv2 = obj_uvs2[ fi ];
  12144. if ( uv2 === undefined ) continue;
  12145. for ( i = 0; i < 4; i ++ ) {
  12146. uv2i = uv2[ i ];
  12147. uv2Array[ offset_uv2 ] = uv2i.x;
  12148. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12149. offset_uv2 += 2;
  12150. }
  12151. }
  12152. if ( offset_uv2 > 0 ) {
  12153. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12154. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12155. }
  12156. }
  12157. if ( dirtyElements ) {
  12158. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12159. faceArray[ offset_face ] = vertexIndex;
  12160. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12161. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12162. offset_face += 3;
  12163. lineArray[ offset_line ] = vertexIndex;
  12164. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12165. lineArray[ offset_line + 2 ] = vertexIndex;
  12166. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12167. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12168. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12169. offset_line += 6;
  12170. vertexIndex += 3;
  12171. }
  12172. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12173. faceArray[ offset_face ] = vertexIndex;
  12174. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12175. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12176. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12177. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12178. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12179. offset_face += 6;
  12180. lineArray[ offset_line ] = vertexIndex;
  12181. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12182. lineArray[ offset_line + 2 ] = vertexIndex;
  12183. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12184. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12185. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12186. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12187. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12188. offset_line += 8;
  12189. vertexIndex += 4;
  12190. }
  12191. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12192. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12193. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12194. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12195. }
  12196. if ( customAttributes ) {
  12197. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12198. customAttribute = customAttributes[ i ];
  12199. if ( ! customAttribute.__original.needsUpdate ) continue;
  12200. offset_custom = 0;
  12201. offset_customSrc = 0;
  12202. if ( customAttribute.size === 1 ) {
  12203. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12204. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12205. face = obj_faces[ chunk_faces3[ f ] ];
  12206. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12207. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12208. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12209. offset_custom += 3;
  12210. }
  12211. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12212. face = obj_faces[ chunk_faces4[ f ] ];
  12213. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12214. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12215. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12216. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  12217. offset_custom += 4;
  12218. }
  12219. } else if ( customAttribute.boundTo === "faces" ) {
  12220. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12221. value = customAttribute.value[ chunk_faces3[ f ] ];
  12222. customAttribute.array[ offset_custom ] = value;
  12223. customAttribute.array[ offset_custom + 1 ] = value;
  12224. customAttribute.array[ offset_custom + 2 ] = value;
  12225. offset_custom += 3;
  12226. }
  12227. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12228. value = customAttribute.value[ chunk_faces4[ f ] ];
  12229. customAttribute.array[ offset_custom ] = value;
  12230. customAttribute.array[ offset_custom + 1 ] = value;
  12231. customAttribute.array[ offset_custom + 2 ] = value;
  12232. customAttribute.array[ offset_custom + 3 ] = value;
  12233. offset_custom += 4;
  12234. }
  12235. }
  12236. } else if ( customAttribute.size === 2 ) {
  12237. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12238. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12239. face = obj_faces[ chunk_faces3[ f ] ];
  12240. v1 = customAttribute.value[ face.a ];
  12241. v2 = customAttribute.value[ face.b ];
  12242. v3 = customAttribute.value[ face.c ];
  12243. customAttribute.array[ offset_custom ] = v1.x;
  12244. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12245. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12246. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12247. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12248. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12249. offset_custom += 6;
  12250. }
  12251. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12252. face = obj_faces[ chunk_faces4[ f ] ];
  12253. v1 = customAttribute.value[ face.a ];
  12254. v2 = customAttribute.value[ face.b ];
  12255. v3 = customAttribute.value[ face.c ];
  12256. v4 = customAttribute.value[ face.d ];
  12257. customAttribute.array[ offset_custom ] = v1.x;
  12258. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12259. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12260. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12261. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12262. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12263. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12264. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12265. offset_custom += 8;
  12266. }
  12267. } else if ( customAttribute.boundTo === "faces" ) {
  12268. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12269. value = customAttribute.value[ chunk_faces3[ f ] ];
  12270. v1 = value;
  12271. v2 = value;
  12272. v3 = value;
  12273. customAttribute.array[ offset_custom ] = v1.x;
  12274. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12275. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12276. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12277. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12278. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12279. offset_custom += 6;
  12280. }
  12281. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12282. value = customAttribute.value[ chunk_faces4[ f ] ];
  12283. v1 = value;
  12284. v2 = value;
  12285. v3 = value;
  12286. v4 = value;
  12287. customAttribute.array[ offset_custom ] = v1.x;
  12288. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12289. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12290. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12291. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12292. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12293. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12294. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12295. offset_custom += 8;
  12296. }
  12297. }
  12298. } else if ( customAttribute.size === 3 ) {
  12299. var pp;
  12300. if ( customAttribute.type === "c" ) {
  12301. pp = [ "r", "g", "b" ];
  12302. } else {
  12303. pp = [ "x", "y", "z" ];
  12304. }
  12305. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12306. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12307. face = obj_faces[ chunk_faces3[ f ] ];
  12308. v1 = customAttribute.value[ face.a ];
  12309. v2 = customAttribute.value[ face.b ];
  12310. v3 = customAttribute.value[ face.c ];
  12311. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12312. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12313. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12314. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12315. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12316. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12317. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12318. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12319. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12320. offset_custom += 9;
  12321. }
  12322. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12323. face = obj_faces[ chunk_faces4[ f ] ];
  12324. v1 = customAttribute.value[ face.a ];
  12325. v2 = customAttribute.value[ face.b ];
  12326. v3 = customAttribute.value[ face.c ];
  12327. v4 = customAttribute.value[ face.d ];
  12328. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12329. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12330. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12331. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12332. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12333. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12334. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12335. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12336. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12337. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12338. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12339. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12340. offset_custom += 12;
  12341. }
  12342. } else if ( customAttribute.boundTo === "faces" ) {
  12343. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12344. value = customAttribute.value[ chunk_faces3[ f ] ];
  12345. v1 = value;
  12346. v2 = value;
  12347. v3 = value;
  12348. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12349. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12350. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12351. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12352. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12353. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12354. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12355. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12356. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12357. offset_custom += 9;
  12358. }
  12359. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12360. value = customAttribute.value[ chunk_faces4[ f ] ];
  12361. v1 = value;
  12362. v2 = value;
  12363. v3 = value;
  12364. v4 = value;
  12365. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12366. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12367. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12368. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12369. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12370. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12371. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12372. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12373. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12374. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12375. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12376. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12377. offset_custom += 12;
  12378. }
  12379. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12380. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12381. value = customAttribute.value[ chunk_faces3[ f ] ];
  12382. v1 = value[ 0 ];
  12383. v2 = value[ 1 ];
  12384. v3 = value[ 2 ];
  12385. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12386. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12387. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12388. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12389. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12390. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12391. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12392. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12393. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12394. offset_custom += 9;
  12395. }
  12396. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12397. value = customAttribute.value[ chunk_faces4[ f ] ];
  12398. v1 = value[ 0 ];
  12399. v2 = value[ 1 ];
  12400. v3 = value[ 2 ];
  12401. v4 = value[ 3 ];
  12402. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12403. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12404. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12405. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12406. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12407. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12408. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12409. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12410. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12411. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12412. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12413. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12414. offset_custom += 12;
  12415. }
  12416. }
  12417. } else if ( customAttribute.size === 4 ) {
  12418. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12419. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12420. face = obj_faces[ chunk_faces3[ f ] ];
  12421. v1 = customAttribute.value[ face.a ];
  12422. v2 = customAttribute.value[ face.b ];
  12423. v3 = customAttribute.value[ face.c ];
  12424. customAttribute.array[ offset_custom ] = v1.x;
  12425. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12426. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12427. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12428. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12429. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12430. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12431. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12432. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12433. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12434. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12435. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12436. offset_custom += 12;
  12437. }
  12438. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12439. face = obj_faces[ chunk_faces4[ f ] ];
  12440. v1 = customAttribute.value[ face.a ];
  12441. v2 = customAttribute.value[ face.b ];
  12442. v3 = customAttribute.value[ face.c ];
  12443. v4 = customAttribute.value[ face.d ];
  12444. customAttribute.array[ offset_custom ] = v1.x;
  12445. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12446. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12447. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12448. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12449. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12450. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12451. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12452. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12453. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12454. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12455. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12456. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12457. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12458. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12459. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12460. offset_custom += 16;
  12461. }
  12462. } else if ( customAttribute.boundTo === "faces" ) {
  12463. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12464. value = customAttribute.value[ chunk_faces3[ f ] ];
  12465. v1 = value;
  12466. v2 = value;
  12467. v3 = value;
  12468. customAttribute.array[ offset_custom ] = v1.x;
  12469. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12470. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12471. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12472. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12473. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12474. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12475. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12476. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12477. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12478. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12479. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12480. offset_custom += 12;
  12481. }
  12482. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12483. value = customAttribute.value[ chunk_faces4[ f ] ];
  12484. v1 = value;
  12485. v2 = value;
  12486. v3 = value;
  12487. v4 = value;
  12488. customAttribute.array[ offset_custom ] = v1.x;
  12489. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12490. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12491. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12492. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12493. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12494. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12495. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12496. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12497. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12498. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12499. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12500. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12501. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12502. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12503. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12504. offset_custom += 16;
  12505. }
  12506. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12507. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12508. value = customAttribute.value[ chunk_faces3[ f ] ];
  12509. v1 = value[ 0 ];
  12510. v2 = value[ 1 ];
  12511. v3 = value[ 2 ];
  12512. customAttribute.array[ offset_custom ] = v1.x;
  12513. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12514. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12515. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12516. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12517. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12518. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12519. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12520. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12521. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12522. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12523. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12524. offset_custom += 12;
  12525. }
  12526. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12527. value = customAttribute.value[ chunk_faces4[ f ] ];
  12528. v1 = value[ 0 ];
  12529. v2 = value[ 1 ];
  12530. v3 = value[ 2 ];
  12531. v4 = value[ 3 ];
  12532. customAttribute.array[ offset_custom ] = v1.x;
  12533. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12534. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12535. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12536. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12537. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12538. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12539. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12540. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12541. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12542. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12543. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12544. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12545. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12546. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12547. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12548. offset_custom += 16;
  12549. }
  12550. }
  12551. }
  12552. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12553. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12554. }
  12555. }
  12556. if ( dispose ) {
  12557. delete geometryGroup.__inittedArrays;
  12558. delete geometryGroup.__colorArray;
  12559. delete geometryGroup.__normalArray;
  12560. delete geometryGroup.__tangentArray;
  12561. delete geometryGroup.__uvArray;
  12562. delete geometryGroup.__uv2Array;
  12563. delete geometryGroup.__faceArray;
  12564. delete geometryGroup.__vertexArray;
  12565. delete geometryGroup.__lineArray;
  12566. delete geometryGroup.__skinIndexArray;
  12567. delete geometryGroup.__skinWeightArray;
  12568. }
  12569. };
  12570. function setDirectBuffers ( geometry, hint, dispose ) {
  12571. var attributes = geometry.attributes;
  12572. var index = attributes[ "index" ];
  12573. var position = attributes[ "position" ];
  12574. var normal = attributes[ "normal" ];
  12575. var uv = attributes[ "uv" ];
  12576. var color = attributes[ "color" ];
  12577. var tangent = attributes[ "tangent" ];
  12578. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  12579. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12580. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  12581. }
  12582. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  12583. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12584. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  12585. }
  12586. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  12587. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12588. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  12589. }
  12590. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  12591. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12592. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  12593. }
  12594. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  12595. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12596. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  12597. }
  12598. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  12599. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12600. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  12601. }
  12602. if ( dispose ) {
  12603. for ( var i in geometry.attributes ) {
  12604. delete geometry.attributes[ i ].array;
  12605. }
  12606. }
  12607. };
  12608. // Buffer rendering
  12609. this.renderBufferImmediate = function ( object, program, material ) {
  12610. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12611. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12612. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12613. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12614. if ( object.hasPositions ) {
  12615. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12616. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12617. _gl.enableVertexAttribArray( program.attributes.position );
  12618. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12619. }
  12620. if ( object.hasNormals ) {
  12621. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12622. if ( material.shading === THREE.FlatShading ) {
  12623. var nx, ny, nz,
  12624. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12625. normalArray,
  12626. i, il = object.count * 3;
  12627. for( i = 0; i < il; i += 9 ) {
  12628. normalArray = object.normalArray;
  12629. nax = normalArray[ i ];
  12630. nay = normalArray[ i + 1 ];
  12631. naz = normalArray[ i + 2 ];
  12632. nbx = normalArray[ i + 3 ];
  12633. nby = normalArray[ i + 4 ];
  12634. nbz = normalArray[ i + 5 ];
  12635. ncx = normalArray[ i + 6 ];
  12636. ncy = normalArray[ i + 7 ];
  12637. ncz = normalArray[ i + 8 ];
  12638. nx = ( nax + nbx + ncx ) / 3;
  12639. ny = ( nay + nby + ncy ) / 3;
  12640. nz = ( naz + nbz + ncz ) / 3;
  12641. normalArray[ i ] = nx;
  12642. normalArray[ i + 1 ] = ny;
  12643. normalArray[ i + 2 ] = nz;
  12644. normalArray[ i + 3 ] = nx;
  12645. normalArray[ i + 4 ] = ny;
  12646. normalArray[ i + 5 ] = nz;
  12647. normalArray[ i + 6 ] = nx;
  12648. normalArray[ i + 7 ] = ny;
  12649. normalArray[ i + 8 ] = nz;
  12650. }
  12651. }
  12652. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12653. _gl.enableVertexAttribArray( program.attributes.normal );
  12654. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12655. }
  12656. if ( object.hasUvs && material.map ) {
  12657. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12658. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12659. _gl.enableVertexAttribArray( program.attributes.uv );
  12660. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12661. }
  12662. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12663. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12664. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12665. _gl.enableVertexAttribArray( program.attributes.color );
  12666. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12667. }
  12668. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12669. object.count = 0;
  12670. };
  12671. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12672. if ( material.visible === false ) return;
  12673. var program, attributes, linewidth, primitives, a, attribute;
  12674. program = setProgram( camera, lights, fog, material, object );
  12675. attributes = program.attributes;
  12676. var updateBuffers = false,
  12677. wireframeBit = material.wireframe ? 1 : 0,
  12678. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12679. if ( geometryHash !== _currentGeometryGroupHash ) {
  12680. _currentGeometryGroupHash = geometryHash;
  12681. updateBuffers = true;
  12682. }
  12683. if ( updateBuffers ) {
  12684. disableAttributes();
  12685. }
  12686. // render mesh
  12687. if ( object instanceof THREE.Mesh ) {
  12688. var index = geometry.attributes[ "index" ];
  12689. // indexed triangles
  12690. if ( index ) {
  12691. var offsets = geometry.offsets;
  12692. // if there is more than 1 chunk
  12693. // must set attribute pointers to use new offsets for each chunk
  12694. // even if geometry and materials didn't change
  12695. if ( offsets.length > 1 ) updateBuffers = true;
  12696. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12697. var startIndex = offsets[ i ].index;
  12698. if ( updateBuffers ) {
  12699. // vertices
  12700. var position = geometry.attributes[ "position" ];
  12701. var positionSize = position.itemSize;
  12702. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12703. enableAttribute( attributes.position );
  12704. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12705. // normals
  12706. var normal = geometry.attributes[ "normal" ];
  12707. if ( attributes.normal >= 0 && normal ) {
  12708. var normalSize = normal.itemSize;
  12709. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12710. enableAttribute( attributes.normal );
  12711. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12712. }
  12713. // uvs
  12714. var uv = geometry.attributes[ "uv" ];
  12715. if ( attributes.uv >= 0 && uv ) {
  12716. var uvSize = uv.itemSize;
  12717. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12718. enableAttribute( attributes.uv );
  12719. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12720. }
  12721. // colors
  12722. var color = geometry.attributes[ "color" ];
  12723. if ( attributes.color >= 0 && color ) {
  12724. var colorSize = color.itemSize;
  12725. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12726. enableAttribute( attributes.color );
  12727. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12728. }
  12729. // tangents
  12730. var tangent = geometry.attributes[ "tangent" ];
  12731. if ( attributes.tangent >= 0 && tangent ) {
  12732. var tangentSize = tangent.itemSize;
  12733. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12734. enableAttribute( attributes.tangent );
  12735. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12736. }
  12737. // indices
  12738. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12739. }
  12740. // render indexed triangles
  12741. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12742. _this.info.render.calls ++;
  12743. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12744. _this.info.render.faces += offsets[ i ].count / 3;
  12745. }
  12746. // non-indexed triangles
  12747. } else {
  12748. if ( updateBuffers ) {
  12749. // vertices
  12750. var position = geometry.attributes[ "position" ];
  12751. var positionSize = position.itemSize;
  12752. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12753. enableAttribute( attributes.position );
  12754. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12755. // normals
  12756. var normal = geometry.attributes[ "normal" ];
  12757. if ( attributes.normal >= 0 && normal ) {
  12758. var normalSize = normal.itemSize;
  12759. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12760. enableAttribute( attributes.normal );
  12761. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12762. }
  12763. // uvs
  12764. var uv = geometry.attributes[ "uv" ];
  12765. if ( attributes.uv >= 0 && uv ) {
  12766. var uvSize = uv.itemSize;
  12767. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12768. enableAttribute( attributes.uv );
  12769. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12770. }
  12771. // colors
  12772. var color = geometry.attributes[ "color" ];
  12773. if ( attributes.color >= 0 && color ) {
  12774. var colorSize = color.itemSize;
  12775. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12776. enableAttribute( attributes.color );
  12777. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12778. }
  12779. // tangents
  12780. var tangent = geometry.attributes[ "tangent" ];
  12781. if ( attributes.tangent >= 0 && tangent ) {
  12782. var tangentSize = tangent.itemSize;
  12783. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12784. enableAttribute( attributes.tangent );
  12785. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12786. }
  12787. }
  12788. // render non-indexed triangles
  12789. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12790. _this.info.render.calls ++;
  12791. _this.info.render.vertices += position.numItems / 3;
  12792. _this.info.render.faces += position.numItems / 3 / 3;
  12793. }
  12794. // render particles
  12795. } else if ( object instanceof THREE.ParticleSystem ) {
  12796. if ( updateBuffers ) {
  12797. // vertices
  12798. var position = geometry.attributes[ "position" ];
  12799. var positionSize = position.itemSize;
  12800. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12801. enableAttribute( attributes.position );
  12802. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12803. // colors
  12804. var color = geometry.attributes[ "color" ];
  12805. if ( attributes.color >= 0 && color ) {
  12806. var colorSize = color.itemSize;
  12807. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12808. enableAttribute( attributes.color );
  12809. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12810. }
  12811. // render particles
  12812. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12813. _this.info.render.calls ++;
  12814. _this.info.render.points += position.numItems / 3;
  12815. }
  12816. } else if ( object instanceof THREE.Line ) {
  12817. if ( updateBuffers ) {
  12818. // vertices
  12819. var position = geometry.attributes[ "position" ];
  12820. var positionSize = position.itemSize;
  12821. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12822. enableAttribute( attributes.position );
  12823. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12824. // colors
  12825. var color = geometry.attributes[ "color" ];
  12826. if ( attributes.color >= 0 && color ) {
  12827. var colorSize = color.itemSize;
  12828. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12829. enableAttribute( attributes.color );
  12830. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12831. }
  12832. // render lines
  12833. _gl.drawArrays( _gl.LINE_STRIP, 0, position.numItems / 3 );
  12834. _this.info.render.calls ++;
  12835. _this.info.render.points += position.numItems;
  12836. }
  12837. }
  12838. };
  12839. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12840. if ( material.visible === false ) return;
  12841. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12842. program = setProgram( camera, lights, fog, material, object );
  12843. attributes = program.attributes;
  12844. var updateBuffers = false,
  12845. wireframeBit = material.wireframe ? 1 : 0,
  12846. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12847. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12848. _currentGeometryGroupHash = geometryGroupHash;
  12849. updateBuffers = true;
  12850. }
  12851. if ( updateBuffers ) {
  12852. disableAttributes();
  12853. }
  12854. // vertices
  12855. if ( !material.morphTargets && attributes.position >= 0 ) {
  12856. if ( updateBuffers ) {
  12857. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12858. enableAttribute( attributes.position );
  12859. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12860. }
  12861. } else {
  12862. if ( object.morphTargetBase ) {
  12863. setupMorphTargets( material, geometryGroup, object );
  12864. }
  12865. }
  12866. if ( updateBuffers ) {
  12867. // custom attributes
  12868. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12869. if ( geometryGroup.__webglCustomAttributesList ) {
  12870. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12871. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12872. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12873. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12874. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12875. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12876. }
  12877. }
  12878. }
  12879. // colors
  12880. if ( attributes.color >= 0 ) {
  12881. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12882. enableAttribute( attributes.color );
  12883. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12884. }
  12885. // normals
  12886. if ( attributes.normal >= 0 ) {
  12887. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12888. enableAttribute( attributes.normal );
  12889. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12890. }
  12891. // tangents
  12892. if ( attributes.tangent >= 0 ) {
  12893. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12894. enableAttribute( attributes.tangent );
  12895. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12896. }
  12897. // uvs
  12898. if ( attributes.uv >= 0 ) {
  12899. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12900. enableAttribute( attributes.uv );
  12901. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12902. }
  12903. if ( attributes.uv2 >= 0 ) {
  12904. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12905. enableAttribute( attributes.uv2 );
  12906. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12907. }
  12908. if ( material.skinning &&
  12909. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12910. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12911. enableAttribute( attributes.skinIndex );
  12912. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12913. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12914. enableAttribute( attributes.skinWeight );
  12915. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12916. }
  12917. // line distances
  12918. if ( attributes.lineDistance >= 0 ) {
  12919. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12920. enableAttribute( attributes.lineDistance );
  12921. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12922. }
  12923. }
  12924. // render mesh
  12925. if ( object instanceof THREE.Mesh ) {
  12926. // wireframe
  12927. if ( material.wireframe ) {
  12928. setLineWidth( material.wireframeLinewidth );
  12929. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12930. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12931. // triangles
  12932. } else {
  12933. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12934. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12935. }
  12936. _this.info.render.calls ++;
  12937. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12938. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12939. // render lines
  12940. } else if ( object instanceof THREE.Line ) {
  12941. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12942. setLineWidth( material.linewidth );
  12943. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12944. _this.info.render.calls ++;
  12945. // render particles
  12946. } else if ( object instanceof THREE.ParticleSystem ) {
  12947. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12948. _this.info.render.calls ++;
  12949. _this.info.render.points += geometryGroup.__webglParticleCount;
  12950. // render ribbon
  12951. } else if ( object instanceof THREE.Ribbon ) {
  12952. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  12953. _this.info.render.calls ++;
  12954. }
  12955. };
  12956. function enableAttribute( attribute ) {
  12957. if ( ! _enabledAttributes[ attribute ] ) {
  12958. _gl.enableVertexAttribArray( attribute );
  12959. _enabledAttributes[ attribute ] = true;
  12960. }
  12961. };
  12962. function disableAttributes() {
  12963. for ( var attribute in _enabledAttributes ) {
  12964. if ( _enabledAttributes[ attribute ] ) {
  12965. _gl.disableVertexAttribArray( attribute );
  12966. _enabledAttributes[ attribute ] = false;
  12967. }
  12968. }
  12969. };
  12970. function setupMorphTargets ( material, geometryGroup, object ) {
  12971. // set base
  12972. var attributes = material.program.attributes;
  12973. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  12974. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12975. enableAttribute( attributes.position );
  12976. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12977. } else if ( attributes.position >= 0 ) {
  12978. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12979. enableAttribute( attributes.position );
  12980. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12981. }
  12982. if ( object.morphTargetForcedOrder.length ) {
  12983. // set forced order
  12984. var m = 0;
  12985. var order = object.morphTargetForcedOrder;
  12986. var influences = object.morphTargetInfluences;
  12987. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12988. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12989. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12990. enableAttribute( attributes[ "morphTarget" + m ] );
  12991. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12992. }
  12993. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12994. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12995. enableAttribute( attributes[ "morphNormal" + m ] );
  12996. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12997. }
  12998. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12999. m ++;
  13000. }
  13001. } else {
  13002. // find the most influencing
  13003. var influence, activeInfluenceIndices = [];
  13004. var influences = object.morphTargetInfluences;
  13005. var i, il = influences.length;
  13006. for ( i = 0; i < il; i ++ ) {
  13007. influence = influences[ i ];
  13008. if ( influence > 0 ) {
  13009. activeInfluenceIndices.push( [ influence, i ] );
  13010. }
  13011. }
  13012. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13013. activeInfluenceIndices.sort( numericalSort );
  13014. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13015. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13016. activeInfluenceIndices.sort( numericalSort );
  13017. } else if ( activeInfluenceIndices.length === 0 ) {
  13018. activeInfluenceIndices.push( [ 0, 0 ] );
  13019. };
  13020. var influenceIndex, m = 0;
  13021. while ( m < material.numSupportedMorphTargets ) {
  13022. if ( activeInfluenceIndices[ m ] ) {
  13023. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13024. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13025. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13026. enableAttribute( attributes[ "morphTarget" + m ] );
  13027. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13028. }
  13029. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13030. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13031. enableAttribute( attributes[ "morphNormal" + m ] );
  13032. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13033. }
  13034. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13035. } else {
  13036. /*
  13037. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13038. if ( material.morphNormals ) {
  13039. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13040. }
  13041. */
  13042. object.__webglMorphTargetInfluences[ m ] = 0;
  13043. }
  13044. m ++;
  13045. }
  13046. }
  13047. // load updated influences uniform
  13048. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13049. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13050. }
  13051. };
  13052. // Sorting
  13053. function painterSortStable ( a, b ) {
  13054. if ( a.z !== b.z ) {
  13055. return b.z - a.z;
  13056. } else {
  13057. return b.id - a.id;
  13058. }
  13059. };
  13060. function numericalSort ( a, b ) {
  13061. return b[ 0 ] - a[ 0 ];
  13062. };
  13063. // Rendering
  13064. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13065. if ( camera instanceof THREE.Camera === false ) {
  13066. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13067. return;
  13068. }
  13069. var i, il,
  13070. webglObject, object,
  13071. renderList,
  13072. lights = scene.__lights,
  13073. fog = scene.fog;
  13074. // reset caching for this frame
  13075. _currentMaterialId = -1;
  13076. _lightsNeedUpdate = true;
  13077. // update scene graph
  13078. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  13079. // update camera matrices and frustum
  13080. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13081. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13082. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13083. _frustum.setFromMatrix( _projScreenMatrix );
  13084. // update WebGL objects
  13085. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13086. // custom render plugins (pre pass)
  13087. renderPlugins( this.renderPluginsPre, scene, camera );
  13088. //
  13089. _this.info.render.calls = 0;
  13090. _this.info.render.vertices = 0;
  13091. _this.info.render.faces = 0;
  13092. _this.info.render.points = 0;
  13093. this.setRenderTarget( renderTarget );
  13094. if ( this.autoClear || forceClear ) {
  13095. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13096. }
  13097. // set matrices for regular objects (frustum culled)
  13098. renderList = scene.__webglObjects;
  13099. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13100. webglObject = renderList[ i ];
  13101. object = webglObject.object;
  13102. webglObject.render = false;
  13103. if ( object.visible ) {
  13104. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13105. setupMatrices( object, camera );
  13106. unrollBufferMaterial( webglObject );
  13107. webglObject.render = true;
  13108. if ( this.sortObjects === true ) {
  13109. if ( object.renderDepth !== null ) {
  13110. webglObject.z = object.renderDepth;
  13111. } else {
  13112. _vector3.copy( object.matrixWorld.getPosition() );
  13113. _vector3.applyProjection( _projScreenMatrix );
  13114. webglObject.z = _vector3.z;
  13115. }
  13116. webglObject.id = object.id;
  13117. }
  13118. }
  13119. }
  13120. }
  13121. if ( this.sortObjects ) {
  13122. renderList.sort( painterSortStable );
  13123. }
  13124. // set matrices for immediate objects
  13125. renderList = scene.__webglObjectsImmediate;
  13126. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13127. webglObject = renderList[ i ];
  13128. object = webglObject.object;
  13129. if ( object.visible ) {
  13130. setupMatrices( object, camera );
  13131. unrollImmediateBufferMaterial( webglObject );
  13132. }
  13133. }
  13134. if ( scene.overrideMaterial ) {
  13135. var material = scene.overrideMaterial;
  13136. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13137. this.setDepthTest( material.depthTest );
  13138. this.setDepthWrite( material.depthWrite );
  13139. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13140. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13141. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13142. } else {
  13143. var material = null;
  13144. // opaque pass (front-to-back order)
  13145. this.setBlending( THREE.NoBlending );
  13146. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13147. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13148. // transparent pass (back-to-front order)
  13149. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13150. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13151. }
  13152. // custom render plugins (post pass)
  13153. renderPlugins( this.renderPluginsPost, scene, camera );
  13154. // Generate mipmap if we're using any kind of mipmap filtering
  13155. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13156. updateRenderTargetMipmap( renderTarget );
  13157. }
  13158. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13159. this.setDepthTest( true );
  13160. this.setDepthWrite( true );
  13161. // _gl.finish();
  13162. };
  13163. function renderPlugins( plugins, scene, camera ) {
  13164. if ( ! plugins.length ) return;
  13165. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13166. // reset state for plugin (to start from clean slate)
  13167. _currentProgram = null;
  13168. _currentCamera = null;
  13169. _oldBlending = -1;
  13170. _oldDepthTest = -1;
  13171. _oldDepthWrite = -1;
  13172. _oldDoubleSided = -1;
  13173. _oldFlipSided = -1;
  13174. _currentGeometryGroupHash = -1;
  13175. _currentMaterialId = -1;
  13176. _lightsNeedUpdate = true;
  13177. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13178. // reset state after plugin (anything could have changed)
  13179. _currentProgram = null;
  13180. _currentCamera = null;
  13181. _oldBlending = -1;
  13182. _oldDepthTest = -1;
  13183. _oldDepthWrite = -1;
  13184. _oldDoubleSided = -1;
  13185. _oldFlipSided = -1;
  13186. _currentGeometryGroupHash = -1;
  13187. _currentMaterialId = -1;
  13188. _lightsNeedUpdate = true;
  13189. }
  13190. };
  13191. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13192. var webglObject, object, buffer, material, start, end, delta;
  13193. if ( reverse ) {
  13194. start = renderList.length - 1;
  13195. end = -1;
  13196. delta = -1;
  13197. } else {
  13198. start = 0;
  13199. end = renderList.length;
  13200. delta = 1;
  13201. }
  13202. for ( var i = start; i !== end; i += delta ) {
  13203. webglObject = renderList[ i ];
  13204. if ( webglObject.render ) {
  13205. object = webglObject.object;
  13206. buffer = webglObject.buffer;
  13207. if ( overrideMaterial ) {
  13208. material = overrideMaterial;
  13209. } else {
  13210. material = webglObject[ materialType ];
  13211. if ( ! material ) continue;
  13212. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13213. _this.setDepthTest( material.depthTest );
  13214. _this.setDepthWrite( material.depthWrite );
  13215. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13216. }
  13217. _this.setMaterialFaces( material );
  13218. if ( buffer instanceof THREE.BufferGeometry ) {
  13219. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13220. } else {
  13221. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13222. }
  13223. }
  13224. }
  13225. };
  13226. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13227. var webglObject, object, material, program;
  13228. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13229. webglObject = renderList[ i ];
  13230. object = webglObject.object;
  13231. if ( object.visible ) {
  13232. if ( overrideMaterial ) {
  13233. material = overrideMaterial;
  13234. } else {
  13235. material = webglObject[ materialType ];
  13236. if ( ! material ) continue;
  13237. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13238. _this.setDepthTest( material.depthTest );
  13239. _this.setDepthWrite( material.depthWrite );
  13240. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13241. }
  13242. _this.renderImmediateObject( camera, lights, fog, material, object );
  13243. }
  13244. }
  13245. };
  13246. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13247. var program = setProgram( camera, lights, fog, material, object );
  13248. _currentGeometryGroupHash = -1;
  13249. _this.setMaterialFaces( material );
  13250. if ( object.immediateRenderCallback ) {
  13251. object.immediateRenderCallback( program, _gl, _frustum );
  13252. } else {
  13253. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13254. }
  13255. };
  13256. function unrollImmediateBufferMaterial ( globject ) {
  13257. var object = globject.object,
  13258. material = object.material;
  13259. if ( material.transparent ) {
  13260. globject.transparent = material;
  13261. globject.opaque = null;
  13262. } else {
  13263. globject.opaque = material;
  13264. globject.transparent = null;
  13265. }
  13266. };
  13267. function unrollBufferMaterial ( globject ) {
  13268. var object = globject.object,
  13269. buffer = globject.buffer,
  13270. material, materialIndex, meshMaterial;
  13271. meshMaterial = object.material;
  13272. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13273. materialIndex = buffer.materialIndex;
  13274. material = meshMaterial.materials[ materialIndex ];
  13275. if ( material.transparent ) {
  13276. globject.transparent = material;
  13277. globject.opaque = null;
  13278. } else {
  13279. globject.opaque = material;
  13280. globject.transparent = null;
  13281. }
  13282. } else {
  13283. material = meshMaterial;
  13284. if ( material ) {
  13285. if ( material.transparent ) {
  13286. globject.transparent = material;
  13287. globject.opaque = null;
  13288. } else {
  13289. globject.opaque = material;
  13290. globject.transparent = null;
  13291. }
  13292. }
  13293. }
  13294. };
  13295. // Geometry splitting
  13296. function sortFacesByMaterial ( geometry, material ) {
  13297. var f, fl, face, materialIndex, vertices,
  13298. groupHash, hash_map = {};
  13299. var numMorphTargets = geometry.morphTargets.length;
  13300. var numMorphNormals = geometry.morphNormals.length;
  13301. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13302. geometry.geometryGroups = {};
  13303. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13304. face = geometry.faces[ f ];
  13305. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13306. if ( hash_map[ materialIndex ] === undefined ) {
  13307. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13308. }
  13309. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13310. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13311. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13312. }
  13313. vertices = face instanceof THREE.Face3 ? 3 : 4;
  13314. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13315. hash_map[ materialIndex ].counter += 1;
  13316. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13317. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13318. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13319. }
  13320. }
  13321. if ( face instanceof THREE.Face3 ) {
  13322. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13323. } else {
  13324. geometry.geometryGroups[ groupHash ].faces4.push( f );
  13325. }
  13326. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13327. }
  13328. geometry.geometryGroupsList = [];
  13329. for ( var g in geometry.geometryGroups ) {
  13330. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13331. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13332. }
  13333. };
  13334. // Objects refresh
  13335. this.initWebGLObjects = function ( scene ) {
  13336. if ( !scene.__webglObjects ) {
  13337. scene.__webglObjects = [];
  13338. scene.__webglObjectsImmediate = [];
  13339. scene.__webglSprites = [];
  13340. scene.__webglFlares = [];
  13341. }
  13342. while ( scene.__objectsAdded.length ) {
  13343. addObject( scene.__objectsAdded[ 0 ], scene );
  13344. scene.__objectsAdded.splice( 0, 1 );
  13345. }
  13346. while ( scene.__objectsRemoved.length ) {
  13347. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13348. scene.__objectsRemoved.splice( 0, 1 );
  13349. }
  13350. // update must be called after objects adding / removal
  13351. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13352. updateObject( scene.__webglObjects[ o ].object );
  13353. }
  13354. };
  13355. // Objects adding
  13356. function addObject ( object, scene ) {
  13357. var g, geometry, material, geometryGroup;
  13358. if ( ! object.__webglInit ) {
  13359. object.__webglInit = true;
  13360. object._modelViewMatrix = new THREE.Matrix4();
  13361. object._normalMatrix = new THREE.Matrix3();
  13362. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13363. object.geometry.__webglInit = true;
  13364. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13365. }
  13366. if ( object instanceof THREE.Mesh ) {
  13367. geometry = object.geometry;
  13368. material = object.material;
  13369. if ( geometry instanceof THREE.Geometry ) {
  13370. if ( geometry.geometryGroups === undefined ) {
  13371. sortFacesByMaterial( geometry, material );
  13372. }
  13373. // create separate VBOs per geometry chunk
  13374. for ( g in geometry.geometryGroups ) {
  13375. geometryGroup = geometry.geometryGroups[ g ];
  13376. // initialise VBO on the first access
  13377. if ( ! geometryGroup.__webglVertexBuffer ) {
  13378. createMeshBuffers( geometryGroup );
  13379. initMeshBuffers( geometryGroup, object );
  13380. geometry.verticesNeedUpdate = true;
  13381. geometry.morphTargetsNeedUpdate = true;
  13382. geometry.elementsNeedUpdate = true;
  13383. geometry.uvsNeedUpdate = true;
  13384. geometry.normalsNeedUpdate = true;
  13385. geometry.tangentsNeedUpdate = true;
  13386. geometry.colorsNeedUpdate = true;
  13387. }
  13388. }
  13389. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13390. initDirectBuffers( geometry );
  13391. }
  13392. } else if ( object instanceof THREE.Ribbon ) {
  13393. geometry = object.geometry;
  13394. if ( ! geometry.__webglVertexBuffer ) {
  13395. createRibbonBuffers( geometry );
  13396. initRibbonBuffers( geometry, object );
  13397. geometry.verticesNeedUpdate = true;
  13398. geometry.colorsNeedUpdate = true;
  13399. geometry.normalsNeedUpdate = true;
  13400. }
  13401. } else if ( object instanceof THREE.Line ) {
  13402. geometry = object.geometry;
  13403. if ( ! geometry.__webglVertexBuffer ) {
  13404. if ( geometry instanceof THREE.Geometry ) {
  13405. createLineBuffers( geometry );
  13406. initLineBuffers( geometry, object );
  13407. geometry.verticesNeedUpdate = true;
  13408. geometry.colorsNeedUpdate = true;
  13409. geometry.lineDistancesNeedUpdate = true;
  13410. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13411. initDirectBuffers( geometry );
  13412. }
  13413. }
  13414. } else if ( object instanceof THREE.ParticleSystem ) {
  13415. geometry = object.geometry;
  13416. if ( ! geometry.__webglVertexBuffer ) {
  13417. if ( geometry instanceof THREE.Geometry ) {
  13418. createParticleBuffers( geometry );
  13419. initParticleBuffers( geometry, object );
  13420. geometry.verticesNeedUpdate = true;
  13421. geometry.colorsNeedUpdate = true;
  13422. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13423. initDirectBuffers( geometry );
  13424. }
  13425. }
  13426. }
  13427. }
  13428. if ( ! object.__webglActive ) {
  13429. if ( object instanceof THREE.Mesh ) {
  13430. geometry = object.geometry;
  13431. if ( geometry instanceof THREE.BufferGeometry ) {
  13432. addBuffer( scene.__webglObjects, geometry, object );
  13433. } else if ( geometry instanceof THREE.Geometry ) {
  13434. for ( g in geometry.geometryGroups ) {
  13435. geometryGroup = geometry.geometryGroups[ g ];
  13436. addBuffer( scene.__webglObjects, geometryGroup, object );
  13437. }
  13438. }
  13439. } else if ( object instanceof THREE.Ribbon ||
  13440. object instanceof THREE.Line ||
  13441. object instanceof THREE.ParticleSystem ) {
  13442. geometry = object.geometry;
  13443. addBuffer( scene.__webglObjects, geometry, object );
  13444. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13445. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13446. } else if ( object instanceof THREE.Sprite ) {
  13447. scene.__webglSprites.push( object );
  13448. } else if ( object instanceof THREE.LensFlare ) {
  13449. scene.__webglFlares.push( object );
  13450. }
  13451. object.__webglActive = true;
  13452. }
  13453. };
  13454. function addBuffer ( objlist, buffer, object ) {
  13455. objlist.push(
  13456. {
  13457. buffer: buffer,
  13458. object: object,
  13459. opaque: null,
  13460. transparent: null
  13461. }
  13462. );
  13463. };
  13464. function addBufferImmediate ( objlist, object ) {
  13465. objlist.push(
  13466. {
  13467. object: object,
  13468. opaque: null,
  13469. transparent: null
  13470. }
  13471. );
  13472. };
  13473. // Objects updates
  13474. function updateObject ( object ) {
  13475. var geometry = object.geometry,
  13476. geometryGroup, customAttributesDirty, material;
  13477. if ( object instanceof THREE.Mesh ) {
  13478. if ( geometry instanceof THREE.BufferGeometry ) {
  13479. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  13480. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13481. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  13482. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13483. }
  13484. geometry.verticesNeedUpdate = false;
  13485. geometry.elementsNeedUpdate = false;
  13486. geometry.uvsNeedUpdate = false;
  13487. geometry.normalsNeedUpdate = false;
  13488. geometry.colorsNeedUpdate = false;
  13489. geometry.tangentsNeedUpdate = false;
  13490. } else {
  13491. // check all geometry groups
  13492. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13493. geometryGroup = geometry.geometryGroupsList[ i ];
  13494. material = getBufferMaterial( object, geometryGroup );
  13495. if ( geometry.buffersNeedUpdate ) {
  13496. initMeshBuffers( geometryGroup, object );
  13497. }
  13498. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13499. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13500. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13501. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13502. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13503. }
  13504. }
  13505. geometry.verticesNeedUpdate = false;
  13506. geometry.morphTargetsNeedUpdate = false;
  13507. geometry.elementsNeedUpdate = false;
  13508. geometry.uvsNeedUpdate = false;
  13509. geometry.normalsNeedUpdate = false;
  13510. geometry.colorsNeedUpdate = false;
  13511. geometry.tangentsNeedUpdate = false;
  13512. geometry.buffersNeedUpdate = false;
  13513. material.attributes && clearCustomAttributes( material );
  13514. }
  13515. } else if ( object instanceof THREE.Ribbon ) {
  13516. material = getBufferMaterial( object, geometry );
  13517. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13518. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13519. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13520. }
  13521. geometry.verticesNeedUpdate = false;
  13522. geometry.colorsNeedUpdate = false;
  13523. geometry.normalsNeedUpdate = false;
  13524. material.attributes && clearCustomAttributes( material );
  13525. } else if ( object instanceof THREE.Line ) {
  13526. if ( geometry instanceof THREE.BufferGeometry ) {
  13527. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  13528. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13529. }
  13530. geometry.verticesNeedUpdate = false;
  13531. geometry.colorsNeedUpdate = false;
  13532. } else {
  13533. material = getBufferMaterial( object, geometry );
  13534. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13535. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13536. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13537. }
  13538. geometry.verticesNeedUpdate = false;
  13539. geometry.colorsNeedUpdate = false;
  13540. geometry.lineDistancesNeedUpdate = false;
  13541. material.attributes && clearCustomAttributes( material );
  13542. }
  13543. } else if ( object instanceof THREE.ParticleSystem ) {
  13544. if ( geometry instanceof THREE.BufferGeometry ) {
  13545. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  13546. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13547. }
  13548. geometry.verticesNeedUpdate = false;
  13549. geometry.colorsNeedUpdate = false;
  13550. } else {
  13551. material = getBufferMaterial( object, geometry );
  13552. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13553. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13554. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13555. }
  13556. geometry.verticesNeedUpdate = false;
  13557. geometry.colorsNeedUpdate = false;
  13558. material.attributes && clearCustomAttributes( material );
  13559. }
  13560. }
  13561. };
  13562. // Objects updates - custom attributes check
  13563. function areCustomAttributesDirty ( material ) {
  13564. for ( var a in material.attributes ) {
  13565. if ( material.attributes[ a ].needsUpdate ) return true;
  13566. }
  13567. return false;
  13568. };
  13569. function clearCustomAttributes ( material ) {
  13570. for ( var a in material.attributes ) {
  13571. material.attributes[ a ].needsUpdate = false;
  13572. }
  13573. };
  13574. // Objects removal
  13575. function removeObject ( object, scene ) {
  13576. if ( object instanceof THREE.Mesh ||
  13577. object instanceof THREE.ParticleSystem ||
  13578. object instanceof THREE.Ribbon ||
  13579. object instanceof THREE.Line ) {
  13580. removeInstances( scene.__webglObjects, object );
  13581. } else if ( object instanceof THREE.Sprite ) {
  13582. removeInstancesDirect( scene.__webglSprites, object );
  13583. } else if ( object instanceof THREE.LensFlare ) {
  13584. removeInstancesDirect( scene.__webglFlares, object );
  13585. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13586. removeInstances( scene.__webglObjectsImmediate, object );
  13587. }
  13588. object.__webglActive = false;
  13589. };
  13590. function removeInstances ( objlist, object ) {
  13591. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13592. if ( objlist[ o ].object === object ) {
  13593. objlist.splice( o, 1 );
  13594. }
  13595. }
  13596. };
  13597. function removeInstancesDirect ( objlist, object ) {
  13598. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13599. if ( objlist[ o ] === object ) {
  13600. objlist.splice( o, 1 );
  13601. }
  13602. }
  13603. };
  13604. // Materials
  13605. this.initMaterial = function ( material, lights, fog, object ) {
  13606. material.addEventListener( 'dispose', onMaterialDispose );
  13607. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13608. if ( material instanceof THREE.MeshDepthMaterial ) {
  13609. shaderID = 'depth';
  13610. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13611. shaderID = 'normal';
  13612. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13613. shaderID = 'basic';
  13614. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13615. shaderID = 'lambert';
  13616. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13617. shaderID = 'phong';
  13618. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13619. shaderID = 'basic';
  13620. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13621. shaderID = 'dashed';
  13622. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13623. shaderID = 'particle_basic';
  13624. }
  13625. if ( shaderID ) {
  13626. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13627. }
  13628. // heuristics to create shader parameters according to lights in the scene
  13629. // (not to blow over maxLights budget)
  13630. maxLightCount = allocateLights( lights );
  13631. maxShadows = allocateShadows( lights );
  13632. maxBones = allocateBones( object );
  13633. parameters = {
  13634. map: !!material.map,
  13635. envMap: !!material.envMap,
  13636. lightMap: !!material.lightMap,
  13637. bumpMap: !!material.bumpMap,
  13638. normalMap: !!material.normalMap,
  13639. specularMap: !!material.specularMap,
  13640. vertexColors: material.vertexColors,
  13641. fog: fog,
  13642. useFog: material.fog,
  13643. fogExp: fog instanceof THREE.FogExp2,
  13644. sizeAttenuation: material.sizeAttenuation,
  13645. skinning: material.skinning,
  13646. maxBones: maxBones,
  13647. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13648. boneTextureWidth: object && object.boneTextureWidth,
  13649. boneTextureHeight: object && object.boneTextureHeight,
  13650. morphTargets: material.morphTargets,
  13651. morphNormals: material.morphNormals,
  13652. maxMorphTargets: this.maxMorphTargets,
  13653. maxMorphNormals: this.maxMorphNormals,
  13654. maxDirLights: maxLightCount.directional,
  13655. maxPointLights: maxLightCount.point,
  13656. maxSpotLights: maxLightCount.spot,
  13657. maxHemiLights: maxLightCount.hemi,
  13658. maxShadows: maxShadows,
  13659. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13660. shadowMapType: this.shadowMapType,
  13661. shadowMapDebug: this.shadowMapDebug,
  13662. shadowMapCascade: this.shadowMapCascade,
  13663. alphaTest: material.alphaTest,
  13664. metal: material.metal,
  13665. perPixel: material.perPixel,
  13666. wrapAround: material.wrapAround,
  13667. doubleSided: material.side === THREE.DoubleSide,
  13668. flipSided: material.side === THREE.BackSide
  13669. };
  13670. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13671. var attributes = material.program.attributes;
  13672. if ( material.morphTargets ) {
  13673. material.numSupportedMorphTargets = 0;
  13674. var id, base = "morphTarget";
  13675. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13676. id = base + i;
  13677. if ( attributes[ id ] >= 0 ) {
  13678. material.numSupportedMorphTargets ++;
  13679. }
  13680. }
  13681. }
  13682. if ( material.morphNormals ) {
  13683. material.numSupportedMorphNormals = 0;
  13684. var id, base = "morphNormal";
  13685. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13686. id = base + i;
  13687. if ( attributes[ id ] >= 0 ) {
  13688. material.numSupportedMorphNormals ++;
  13689. }
  13690. }
  13691. }
  13692. material.uniformsList = [];
  13693. for ( u in material.uniforms ) {
  13694. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13695. }
  13696. };
  13697. function setMaterialShaders( material, shaders ) {
  13698. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13699. material.vertexShader = shaders.vertexShader;
  13700. material.fragmentShader = shaders.fragmentShader;
  13701. };
  13702. function setProgram( camera, lights, fog, material, object ) {
  13703. _usedTextureUnits = 0;
  13704. if ( material.needsUpdate ) {
  13705. if ( material.program ) deallocateMaterial( material );
  13706. _this.initMaterial( material, lights, fog, object );
  13707. material.needsUpdate = false;
  13708. }
  13709. if ( material.morphTargets ) {
  13710. if ( ! object.__webglMorphTargetInfluences ) {
  13711. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13712. }
  13713. }
  13714. var refreshMaterial = false;
  13715. var program = material.program,
  13716. p_uniforms = program.uniforms,
  13717. m_uniforms = material.uniforms;
  13718. if ( program !== _currentProgram ) {
  13719. _gl.useProgram( program );
  13720. _currentProgram = program;
  13721. refreshMaterial = true;
  13722. }
  13723. if ( material.id !== _currentMaterialId ) {
  13724. _currentMaterialId = material.id;
  13725. refreshMaterial = true;
  13726. }
  13727. if ( refreshMaterial || camera !== _currentCamera ) {
  13728. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13729. if ( camera !== _currentCamera ) _currentCamera = camera;
  13730. }
  13731. // skinning uniforms must be set even if material didn't change
  13732. // auto-setting of texture unit for bone texture must go before other textures
  13733. // not sure why, but otherwise weird things happen
  13734. if ( material.skinning ) {
  13735. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13736. if ( p_uniforms.boneTexture !== null ) {
  13737. var textureUnit = getTextureUnit();
  13738. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13739. _this.setTexture( object.boneTexture, textureUnit );
  13740. }
  13741. } else {
  13742. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13743. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13744. }
  13745. }
  13746. }
  13747. if ( refreshMaterial ) {
  13748. // refresh uniforms common to several materials
  13749. if ( fog && material.fog ) {
  13750. refreshUniformsFog( m_uniforms, fog );
  13751. }
  13752. if ( material instanceof THREE.MeshPhongMaterial ||
  13753. material instanceof THREE.MeshLambertMaterial ||
  13754. material.lights ) {
  13755. if ( _lightsNeedUpdate ) {
  13756. setupLights( program, lights );
  13757. _lightsNeedUpdate = false;
  13758. }
  13759. refreshUniformsLights( m_uniforms, _lights );
  13760. }
  13761. if ( material instanceof THREE.MeshBasicMaterial ||
  13762. material instanceof THREE.MeshLambertMaterial ||
  13763. material instanceof THREE.MeshPhongMaterial ) {
  13764. refreshUniformsCommon( m_uniforms, material );
  13765. }
  13766. // refresh single material specific uniforms
  13767. if ( material instanceof THREE.LineBasicMaterial ) {
  13768. refreshUniformsLine( m_uniforms, material );
  13769. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13770. refreshUniformsLine( m_uniforms, material );
  13771. refreshUniformsDash( m_uniforms, material );
  13772. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13773. refreshUniformsParticle( m_uniforms, material );
  13774. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13775. refreshUniformsPhong( m_uniforms, material );
  13776. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13777. refreshUniformsLambert( m_uniforms, material );
  13778. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13779. m_uniforms.mNear.value = camera.near;
  13780. m_uniforms.mFar.value = camera.far;
  13781. m_uniforms.opacity.value = material.opacity;
  13782. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13783. m_uniforms.opacity.value = material.opacity;
  13784. }
  13785. if ( object.receiveShadow && ! material._shadowPass ) {
  13786. refreshUniformsShadow( m_uniforms, lights );
  13787. }
  13788. // load common uniforms
  13789. loadUniformsGeneric( program, material.uniformsList );
  13790. // load material specific uniforms
  13791. // (shader material also gets them for the sake of genericity)
  13792. if ( material instanceof THREE.ShaderMaterial ||
  13793. material instanceof THREE.MeshPhongMaterial ||
  13794. material.envMap ) {
  13795. if ( p_uniforms.cameraPosition !== null ) {
  13796. var position = camera.matrixWorld.getPosition();
  13797. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  13798. }
  13799. }
  13800. if ( material instanceof THREE.MeshPhongMaterial ||
  13801. material instanceof THREE.MeshLambertMaterial ||
  13802. material instanceof THREE.ShaderMaterial ||
  13803. material.skinning ) {
  13804. if ( p_uniforms.viewMatrix !== null ) {
  13805. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13806. }
  13807. }
  13808. }
  13809. loadUniformsMatrices( p_uniforms, object );
  13810. if ( p_uniforms.modelMatrix !== null ) {
  13811. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13812. }
  13813. return program;
  13814. };
  13815. // Uniforms (refresh uniforms objects)
  13816. function refreshUniformsCommon ( uniforms, material ) {
  13817. uniforms.opacity.value = material.opacity;
  13818. if ( _this.gammaInput ) {
  13819. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13820. } else {
  13821. uniforms.diffuse.value = material.color;
  13822. }
  13823. uniforms.map.value = material.map;
  13824. uniforms.lightMap.value = material.lightMap;
  13825. uniforms.specularMap.value = material.specularMap;
  13826. if ( material.bumpMap ) {
  13827. uniforms.bumpMap.value = material.bumpMap;
  13828. uniforms.bumpScale.value = material.bumpScale;
  13829. }
  13830. if ( material.normalMap ) {
  13831. uniforms.normalMap.value = material.normalMap;
  13832. uniforms.normalScale.value.copy( material.normalScale );
  13833. }
  13834. // uv repeat and offset setting priorities
  13835. // 1. color map
  13836. // 2. specular map
  13837. // 3. normal map
  13838. // 4. bump map
  13839. var uvScaleMap;
  13840. if ( material.map ) {
  13841. uvScaleMap = material.map;
  13842. } else if ( material.specularMap ) {
  13843. uvScaleMap = material.specularMap;
  13844. } else if ( material.normalMap ) {
  13845. uvScaleMap = material.normalMap;
  13846. } else if ( material.bumpMap ) {
  13847. uvScaleMap = material.bumpMap;
  13848. }
  13849. if ( uvScaleMap !== undefined ) {
  13850. var offset = uvScaleMap.offset;
  13851. var repeat = uvScaleMap.repeat;
  13852. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13853. }
  13854. uniforms.envMap.value = material.envMap;
  13855. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13856. if ( _this.gammaInput ) {
  13857. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13858. uniforms.reflectivity.value = material.reflectivity;
  13859. } else {
  13860. uniforms.reflectivity.value = material.reflectivity;
  13861. }
  13862. uniforms.refractionRatio.value = material.refractionRatio;
  13863. uniforms.combine.value = material.combine;
  13864. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13865. };
  13866. function refreshUniformsLine ( uniforms, material ) {
  13867. uniforms.diffuse.value = material.color;
  13868. uniforms.opacity.value = material.opacity;
  13869. };
  13870. function refreshUniformsDash ( uniforms, material ) {
  13871. uniforms.dashSize.value = material.dashSize;
  13872. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13873. uniforms.scale.value = material.scale;
  13874. };
  13875. function refreshUniformsParticle ( uniforms, material ) {
  13876. uniforms.psColor.value = material.color;
  13877. uniforms.opacity.value = material.opacity;
  13878. uniforms.size.value = material.size;
  13879. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13880. uniforms.map.value = material.map;
  13881. };
  13882. function refreshUniformsFog ( uniforms, fog ) {
  13883. uniforms.fogColor.value = fog.color;
  13884. if ( fog instanceof THREE.Fog ) {
  13885. uniforms.fogNear.value = fog.near;
  13886. uniforms.fogFar.value = fog.far;
  13887. } else if ( fog instanceof THREE.FogExp2 ) {
  13888. uniforms.fogDensity.value = fog.density;
  13889. }
  13890. };
  13891. function refreshUniformsPhong ( uniforms, material ) {
  13892. uniforms.shininess.value = material.shininess;
  13893. if ( _this.gammaInput ) {
  13894. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13895. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13896. uniforms.specular.value.copyGammaToLinear( material.specular );
  13897. } else {
  13898. uniforms.ambient.value = material.ambient;
  13899. uniforms.emissive.value = material.emissive;
  13900. uniforms.specular.value = material.specular;
  13901. }
  13902. if ( material.wrapAround ) {
  13903. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13904. }
  13905. };
  13906. function refreshUniformsLambert ( uniforms, material ) {
  13907. if ( _this.gammaInput ) {
  13908. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13909. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13910. } else {
  13911. uniforms.ambient.value = material.ambient;
  13912. uniforms.emissive.value = material.emissive;
  13913. }
  13914. if ( material.wrapAround ) {
  13915. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13916. }
  13917. };
  13918. function refreshUniformsLights ( uniforms, lights ) {
  13919. uniforms.ambientLightColor.value = lights.ambient;
  13920. uniforms.directionalLightColor.value = lights.directional.colors;
  13921. uniforms.directionalLightDirection.value = lights.directional.positions;
  13922. uniforms.pointLightColor.value = lights.point.colors;
  13923. uniforms.pointLightPosition.value = lights.point.positions;
  13924. uniforms.pointLightDistance.value = lights.point.distances;
  13925. uniforms.spotLightColor.value = lights.spot.colors;
  13926. uniforms.spotLightPosition.value = lights.spot.positions;
  13927. uniforms.spotLightDistance.value = lights.spot.distances;
  13928. uniforms.spotLightDirection.value = lights.spot.directions;
  13929. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13930. uniforms.spotLightExponent.value = lights.spot.exponents;
  13931. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13932. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13933. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13934. };
  13935. function refreshUniformsShadow ( uniforms, lights ) {
  13936. if ( uniforms.shadowMatrix ) {
  13937. var j = 0;
  13938. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13939. var light = lights[ i ];
  13940. if ( ! light.castShadow ) continue;
  13941. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13942. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13943. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13944. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13945. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13946. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13947. j ++;
  13948. }
  13949. }
  13950. }
  13951. };
  13952. // Uniforms (load to GPU)
  13953. function loadUniformsMatrices ( uniforms, object ) {
  13954. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13955. if ( uniforms.normalMatrix ) {
  13956. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13957. }
  13958. };
  13959. function getTextureUnit() {
  13960. var textureUnit = _usedTextureUnits;
  13961. if ( textureUnit >= _maxTextures ) {
  13962. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  13963. }
  13964. _usedTextureUnits += 1;
  13965. return textureUnit;
  13966. };
  13967. function loadUniformsGeneric ( program, uniforms ) {
  13968. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  13969. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13970. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  13971. if ( !location ) continue;
  13972. uniform = uniforms[ j ][ 0 ];
  13973. type = uniform.type;
  13974. value = uniform.value;
  13975. if ( type === "i" ) { // single integer
  13976. _gl.uniform1i( location, value );
  13977. } else if ( type === "f" ) { // single float
  13978. _gl.uniform1f( location, value );
  13979. } else if ( type === "v2" ) { // single THREE.Vector2
  13980. _gl.uniform2f( location, value.x, value.y );
  13981. } else if ( type === "v3" ) { // single THREE.Vector3
  13982. _gl.uniform3f( location, value.x, value.y, value.z );
  13983. } else if ( type === "v4" ) { // single THREE.Vector4
  13984. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13985. } else if ( type === "c" ) { // single THREE.Color
  13986. _gl.uniform3f( location, value.r, value.g, value.b );
  13987. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  13988. _gl.uniform1iv( location, value );
  13989. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  13990. _gl.uniform3iv( location, value );
  13991. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  13992. _gl.uniform1fv( location, value );
  13993. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  13994. _gl.uniform3fv( location, value );
  13995. } else if ( type === "v2v" ) { // array of THREE.Vector2
  13996. if ( uniform._array === undefined ) {
  13997. uniform._array = new Float32Array( 2 * value.length );
  13998. }
  13999. for ( i = 0, il = value.length; i < il; i ++ ) {
  14000. offset = i * 2;
  14001. uniform._array[ offset ] = value[ i ].x;
  14002. uniform._array[ offset + 1 ] = value[ i ].y;
  14003. }
  14004. _gl.uniform2fv( location, uniform._array );
  14005. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14006. if ( uniform._array === undefined ) {
  14007. uniform._array = new Float32Array( 3 * value.length );
  14008. }
  14009. for ( i = 0, il = value.length; i < il; i ++ ) {
  14010. offset = i * 3;
  14011. uniform._array[ offset ] = value[ i ].x;
  14012. uniform._array[ offset + 1 ] = value[ i ].y;
  14013. uniform._array[ offset + 2 ] = value[ i ].z;
  14014. }
  14015. _gl.uniform3fv( location, uniform._array );
  14016. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14017. if ( uniform._array === undefined ) {
  14018. uniform._array = new Float32Array( 4 * value.length );
  14019. }
  14020. for ( i = 0, il = value.length; i < il; i ++ ) {
  14021. offset = i * 4;
  14022. uniform._array[ offset ] = value[ i ].x;
  14023. uniform._array[ offset + 1 ] = value[ i ].y;
  14024. uniform._array[ offset + 2 ] = value[ i ].z;
  14025. uniform._array[ offset + 3 ] = value[ i ].w;
  14026. }
  14027. _gl.uniform4fv( location, uniform._array );
  14028. } else if ( type === "m4") { // single THREE.Matrix4
  14029. if ( uniform._array === undefined ) {
  14030. uniform._array = new Float32Array( 16 );
  14031. }
  14032. value.flattenToArray( uniform._array );
  14033. _gl.uniformMatrix4fv( location, false, uniform._array );
  14034. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14035. if ( uniform._array === undefined ) {
  14036. uniform._array = new Float32Array( 16 * value.length );
  14037. }
  14038. for ( i = 0, il = value.length; i < il; i ++ ) {
  14039. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14040. }
  14041. _gl.uniformMatrix4fv( location, false, uniform._array );
  14042. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14043. texture = value;
  14044. textureUnit = getTextureUnit();
  14045. _gl.uniform1i( location, textureUnit );
  14046. if ( !texture ) continue;
  14047. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14048. setCubeTexture( texture, textureUnit );
  14049. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14050. setCubeTextureDynamic( texture, textureUnit );
  14051. } else {
  14052. _this.setTexture( texture, textureUnit );
  14053. }
  14054. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14055. if ( uniform._array === undefined ) {
  14056. uniform._array = [];
  14057. }
  14058. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14059. uniform._array[ i ] = getTextureUnit();
  14060. }
  14061. _gl.uniform1iv( location, uniform._array );
  14062. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14063. texture = uniform.value[ i ];
  14064. textureUnit = uniform._array[ i ];
  14065. if ( !texture ) continue;
  14066. _this.setTexture( texture, textureUnit );
  14067. }
  14068. }
  14069. }
  14070. };
  14071. function setupMatrices ( object, camera ) {
  14072. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14073. object._normalMatrix.getInverse( object._modelViewMatrix );
  14074. object._normalMatrix.transpose();
  14075. };
  14076. //
  14077. function setColorGamma( array, offset, color, intensitySq ) {
  14078. array[ offset ] = color.r * color.r * intensitySq;
  14079. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14080. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14081. };
  14082. function setColorLinear( array, offset, color, intensity ) {
  14083. array[ offset ] = color.r * intensity;
  14084. array[ offset + 1 ] = color.g * intensity;
  14085. array[ offset + 2 ] = color.b * intensity;
  14086. };
  14087. function setupLights ( program, lights ) {
  14088. var l, ll, light, n,
  14089. r = 0, g = 0, b = 0,
  14090. color, skyColor, groundColor,
  14091. intensity, intensitySq,
  14092. position,
  14093. distance,
  14094. zlights = _lights,
  14095. dirColors = zlights.directional.colors,
  14096. dirPositions = zlights.directional.positions,
  14097. pointColors = zlights.point.colors,
  14098. pointPositions = zlights.point.positions,
  14099. pointDistances = zlights.point.distances,
  14100. spotColors = zlights.spot.colors,
  14101. spotPositions = zlights.spot.positions,
  14102. spotDistances = zlights.spot.distances,
  14103. spotDirections = zlights.spot.directions,
  14104. spotAnglesCos = zlights.spot.anglesCos,
  14105. spotExponents = zlights.spot.exponents,
  14106. hemiSkyColors = zlights.hemi.skyColors,
  14107. hemiGroundColors = zlights.hemi.groundColors,
  14108. hemiPositions = zlights.hemi.positions,
  14109. dirLength = 0,
  14110. pointLength = 0,
  14111. spotLength = 0,
  14112. hemiLength = 0,
  14113. dirCount = 0,
  14114. pointCount = 0,
  14115. spotCount = 0,
  14116. hemiCount = 0,
  14117. dirOffset = 0,
  14118. pointOffset = 0,
  14119. spotOffset = 0,
  14120. hemiOffset = 0;
  14121. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14122. light = lights[ l ];
  14123. if ( light.onlyShadow ) continue;
  14124. color = light.color;
  14125. intensity = light.intensity;
  14126. distance = light.distance;
  14127. if ( light instanceof THREE.AmbientLight ) {
  14128. if ( ! light.visible ) continue;
  14129. if ( _this.gammaInput ) {
  14130. r += color.r * color.r;
  14131. g += color.g * color.g;
  14132. b += color.b * color.b;
  14133. } else {
  14134. r += color.r;
  14135. g += color.g;
  14136. b += color.b;
  14137. }
  14138. } else if ( light instanceof THREE.DirectionalLight ) {
  14139. dirCount += 1;
  14140. if ( ! light.visible ) continue;
  14141. _direction.copy( light.matrixWorld.getPosition() );
  14142. _direction.sub( light.target.matrixWorld.getPosition() );
  14143. _direction.normalize();
  14144. // skip lights with undefined direction
  14145. // these create troubles in OpenGL (making pixel black)
  14146. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14147. dirOffset = dirLength * 3;
  14148. dirPositions[ dirOffset ] = _direction.x;
  14149. dirPositions[ dirOffset + 1 ] = _direction.y;
  14150. dirPositions[ dirOffset + 2 ] = _direction.z;
  14151. if ( _this.gammaInput ) {
  14152. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14153. } else {
  14154. setColorLinear( dirColors, dirOffset, color, intensity );
  14155. }
  14156. dirLength += 1;
  14157. } else if ( light instanceof THREE.PointLight ) {
  14158. pointCount += 1;
  14159. if ( ! light.visible ) continue;
  14160. pointOffset = pointLength * 3;
  14161. if ( _this.gammaInput ) {
  14162. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14163. } else {
  14164. setColorLinear( pointColors, pointOffset, color, intensity );
  14165. }
  14166. position = light.matrixWorld.getPosition();
  14167. pointPositions[ pointOffset ] = position.x;
  14168. pointPositions[ pointOffset + 1 ] = position.y;
  14169. pointPositions[ pointOffset + 2 ] = position.z;
  14170. pointDistances[ pointLength ] = distance;
  14171. pointLength += 1;
  14172. } else if ( light instanceof THREE.SpotLight ) {
  14173. spotCount += 1;
  14174. if ( ! light.visible ) continue;
  14175. spotOffset = spotLength * 3;
  14176. if ( _this.gammaInput ) {
  14177. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14178. } else {
  14179. setColorLinear( spotColors, spotOffset, color, intensity );
  14180. }
  14181. position = light.matrixWorld.getPosition();
  14182. spotPositions[ spotOffset ] = position.x;
  14183. spotPositions[ spotOffset + 1 ] = position.y;
  14184. spotPositions[ spotOffset + 2 ] = position.z;
  14185. spotDistances[ spotLength ] = distance;
  14186. _direction.copy( position );
  14187. _direction.sub( light.target.matrixWorld.getPosition() );
  14188. _direction.normalize();
  14189. spotDirections[ spotOffset ] = _direction.x;
  14190. spotDirections[ spotOffset + 1 ] = _direction.y;
  14191. spotDirections[ spotOffset + 2 ] = _direction.z;
  14192. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14193. spotExponents[ spotLength ] = light.exponent;
  14194. spotLength += 1;
  14195. } else if ( light instanceof THREE.HemisphereLight ) {
  14196. hemiCount += 1;
  14197. if ( ! light.visible ) continue;
  14198. _direction.copy( light.matrixWorld.getPosition() );
  14199. _direction.normalize();
  14200. // skip lights with undefined direction
  14201. // these create troubles in OpenGL (making pixel black)
  14202. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14203. hemiOffset = hemiLength * 3;
  14204. hemiPositions[ hemiOffset ] = _direction.x;
  14205. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14206. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14207. skyColor = light.color;
  14208. groundColor = light.groundColor;
  14209. if ( _this.gammaInput ) {
  14210. intensitySq = intensity * intensity;
  14211. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14212. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14213. } else {
  14214. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14215. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14216. }
  14217. hemiLength += 1;
  14218. }
  14219. }
  14220. // null eventual remains from removed lights
  14221. // (this is to avoid if in shader)
  14222. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14223. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14224. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14225. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14226. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14227. zlights.directional.length = dirLength;
  14228. zlights.point.length = pointLength;
  14229. zlights.spot.length = spotLength;
  14230. zlights.hemi.length = hemiLength;
  14231. zlights.ambient[ 0 ] = r;
  14232. zlights.ambient[ 1 ] = g;
  14233. zlights.ambient[ 2 ] = b;
  14234. };
  14235. // GL state setting
  14236. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14237. if ( cullFace === THREE.CullFaceNone ) {
  14238. _gl.disable( _gl.CULL_FACE );
  14239. } else {
  14240. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14241. _gl.frontFace( _gl.CW );
  14242. } else {
  14243. _gl.frontFace( _gl.CCW );
  14244. }
  14245. if ( cullFace === THREE.CullFaceBack ) {
  14246. _gl.cullFace( _gl.BACK );
  14247. } else if ( cullFace === THREE.CullFaceFront ) {
  14248. _gl.cullFace( _gl.FRONT );
  14249. } else {
  14250. _gl.cullFace( _gl.FRONT_AND_BACK );
  14251. }
  14252. _gl.enable( _gl.CULL_FACE );
  14253. }
  14254. };
  14255. this.setMaterialFaces = function ( material ) {
  14256. var doubleSided = material.side === THREE.DoubleSide;
  14257. var flipSided = material.side === THREE.BackSide;
  14258. if ( _oldDoubleSided !== doubleSided ) {
  14259. if ( doubleSided ) {
  14260. _gl.disable( _gl.CULL_FACE );
  14261. } else {
  14262. _gl.enable( _gl.CULL_FACE );
  14263. }
  14264. _oldDoubleSided = doubleSided;
  14265. }
  14266. if ( _oldFlipSided !== flipSided ) {
  14267. if ( flipSided ) {
  14268. _gl.frontFace( _gl.CW );
  14269. } else {
  14270. _gl.frontFace( _gl.CCW );
  14271. }
  14272. _oldFlipSided = flipSided;
  14273. }
  14274. };
  14275. this.setDepthTest = function ( depthTest ) {
  14276. if ( _oldDepthTest !== depthTest ) {
  14277. if ( depthTest ) {
  14278. _gl.enable( _gl.DEPTH_TEST );
  14279. } else {
  14280. _gl.disable( _gl.DEPTH_TEST );
  14281. }
  14282. _oldDepthTest = depthTest;
  14283. }
  14284. };
  14285. this.setDepthWrite = function ( depthWrite ) {
  14286. if ( _oldDepthWrite !== depthWrite ) {
  14287. _gl.depthMask( depthWrite );
  14288. _oldDepthWrite = depthWrite;
  14289. }
  14290. };
  14291. function setLineWidth ( width ) {
  14292. if ( width !== _oldLineWidth ) {
  14293. _gl.lineWidth( width );
  14294. _oldLineWidth = width;
  14295. }
  14296. };
  14297. function setPolygonOffset ( polygonoffset, factor, units ) {
  14298. if ( _oldPolygonOffset !== polygonoffset ) {
  14299. if ( polygonoffset ) {
  14300. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14301. } else {
  14302. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14303. }
  14304. _oldPolygonOffset = polygonoffset;
  14305. }
  14306. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14307. _gl.polygonOffset( factor, units );
  14308. _oldPolygonOffsetFactor = factor;
  14309. _oldPolygonOffsetUnits = units;
  14310. }
  14311. };
  14312. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14313. if ( blending !== _oldBlending ) {
  14314. if ( blending === THREE.NoBlending ) {
  14315. _gl.disable( _gl.BLEND );
  14316. } else if ( blending === THREE.AdditiveBlending ) {
  14317. _gl.enable( _gl.BLEND );
  14318. _gl.blendEquation( _gl.FUNC_ADD );
  14319. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14320. } else if ( blending === THREE.SubtractiveBlending ) {
  14321. // TODO: Find blendFuncSeparate() combination
  14322. _gl.enable( _gl.BLEND );
  14323. _gl.blendEquation( _gl.FUNC_ADD );
  14324. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14325. } else if ( blending === THREE.MultiplyBlending ) {
  14326. // TODO: Find blendFuncSeparate() combination
  14327. _gl.enable( _gl.BLEND );
  14328. _gl.blendEquation( _gl.FUNC_ADD );
  14329. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14330. } else if ( blending === THREE.CustomBlending ) {
  14331. _gl.enable( _gl.BLEND );
  14332. } else {
  14333. _gl.enable( _gl.BLEND );
  14334. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14335. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14336. }
  14337. _oldBlending = blending;
  14338. }
  14339. if ( blending === THREE.CustomBlending ) {
  14340. if ( blendEquation !== _oldBlendEquation ) {
  14341. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14342. _oldBlendEquation = blendEquation;
  14343. }
  14344. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14345. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14346. _oldBlendSrc = blendSrc;
  14347. _oldBlendDst = blendDst;
  14348. }
  14349. } else {
  14350. _oldBlendEquation = null;
  14351. _oldBlendSrc = null;
  14352. _oldBlendDst = null;
  14353. }
  14354. };
  14355. // Defines
  14356. function generateDefines ( defines ) {
  14357. var value, chunk, chunks = [];
  14358. for ( var d in defines ) {
  14359. value = defines[ d ];
  14360. if ( value === false ) continue;
  14361. chunk = "#define " + d + " " + value;
  14362. chunks.push( chunk );
  14363. }
  14364. return chunks.join( "\n" );
  14365. };
  14366. // Shaders
  14367. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  14368. var p, pl, d, program, code;
  14369. var chunks = [];
  14370. // Generate code
  14371. if ( shaderID ) {
  14372. chunks.push( shaderID );
  14373. } else {
  14374. chunks.push( fragmentShader );
  14375. chunks.push( vertexShader );
  14376. }
  14377. for ( d in defines ) {
  14378. chunks.push( d );
  14379. chunks.push( defines[ d ] );
  14380. }
  14381. for ( p in parameters ) {
  14382. chunks.push( p );
  14383. chunks.push( parameters[ p ] );
  14384. }
  14385. code = chunks.join();
  14386. // Check if code has been already compiled
  14387. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14388. var programInfo = _programs[ p ];
  14389. if ( programInfo.code === code ) {
  14390. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  14391. programInfo.usedTimes ++;
  14392. return programInfo.program;
  14393. }
  14394. }
  14395. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14396. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14397. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14398. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14399. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14400. }
  14401. //console.log( "building new program " );
  14402. //
  14403. var customDefines = generateDefines( defines );
  14404. //
  14405. program = _gl.createProgram();
  14406. var prefix_vertex = [
  14407. "precision " + _precision + " float;",
  14408. customDefines,
  14409. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14410. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14411. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14412. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14413. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14414. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14415. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14416. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14417. "#define MAX_SHADOWS " + parameters.maxShadows,
  14418. "#define MAX_BONES " + parameters.maxBones,
  14419. parameters.map ? "#define USE_MAP" : "",
  14420. parameters.envMap ? "#define USE_ENVMAP" : "",
  14421. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14422. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14423. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14424. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14425. parameters.vertexColors ? "#define USE_COLOR" : "",
  14426. parameters.skinning ? "#define USE_SKINNING" : "",
  14427. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14428. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  14429. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  14430. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14431. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14432. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14433. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14434. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14435. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14436. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14437. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14438. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14439. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14440. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14441. "uniform mat4 modelMatrix;",
  14442. "uniform mat4 modelViewMatrix;",
  14443. "uniform mat4 projectionMatrix;",
  14444. "uniform mat4 viewMatrix;",
  14445. "uniform mat3 normalMatrix;",
  14446. "uniform vec3 cameraPosition;",
  14447. "attribute vec3 position;",
  14448. "attribute vec3 normal;",
  14449. "attribute vec2 uv;",
  14450. "attribute vec2 uv2;",
  14451. "#ifdef USE_COLOR",
  14452. "attribute vec3 color;",
  14453. "#endif",
  14454. "#ifdef USE_MORPHTARGETS",
  14455. "attribute vec3 morphTarget0;",
  14456. "attribute vec3 morphTarget1;",
  14457. "attribute vec3 morphTarget2;",
  14458. "attribute vec3 morphTarget3;",
  14459. "#ifdef USE_MORPHNORMALS",
  14460. "attribute vec3 morphNormal0;",
  14461. "attribute vec3 morphNormal1;",
  14462. "attribute vec3 morphNormal2;",
  14463. "attribute vec3 morphNormal3;",
  14464. "#else",
  14465. "attribute vec3 morphTarget4;",
  14466. "attribute vec3 morphTarget5;",
  14467. "attribute vec3 morphTarget6;",
  14468. "attribute vec3 morphTarget7;",
  14469. "#endif",
  14470. "#endif",
  14471. "#ifdef USE_SKINNING",
  14472. "attribute vec4 skinIndex;",
  14473. "attribute vec4 skinWeight;",
  14474. "#endif",
  14475. ""
  14476. ].join("\n");
  14477. var prefix_fragment = [
  14478. "precision " + _precision + " float;",
  14479. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14480. customDefines,
  14481. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14482. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14483. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14484. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14485. "#define MAX_SHADOWS " + parameters.maxShadows,
  14486. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14487. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14488. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14489. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14490. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14491. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14492. parameters.map ? "#define USE_MAP" : "",
  14493. parameters.envMap ? "#define USE_ENVMAP" : "",
  14494. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14495. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14496. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14497. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14498. parameters.vertexColors ? "#define USE_COLOR" : "",
  14499. parameters.metal ? "#define METAL" : "",
  14500. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14501. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14502. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14503. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14504. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14505. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14506. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14507. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14508. "uniform mat4 viewMatrix;",
  14509. "uniform vec3 cameraPosition;",
  14510. ""
  14511. ].join("\n");
  14512. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14513. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14514. _gl.attachShader( program, glVertexShader );
  14515. _gl.attachShader( program, glFragmentShader );
  14516. _gl.linkProgram( program );
  14517. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14518. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14519. }
  14520. // clean up
  14521. _gl.deleteShader( glFragmentShader );
  14522. _gl.deleteShader( glVertexShader );
  14523. //console.log( prefix_fragment + fragmentShader );
  14524. //console.log( prefix_vertex + vertexShader );
  14525. program.uniforms = {};
  14526. program.attributes = {};
  14527. var identifiers, u, a, i;
  14528. // cache uniform locations
  14529. identifiers = [
  14530. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14531. 'morphTargetInfluences'
  14532. ];
  14533. if ( parameters.useVertexTexture ) {
  14534. identifiers.push( 'boneTexture' );
  14535. } else {
  14536. identifiers.push( 'boneGlobalMatrices' );
  14537. }
  14538. for ( u in uniforms ) {
  14539. identifiers.push( u );
  14540. }
  14541. cacheUniformLocations( program, identifiers );
  14542. // cache attributes locations
  14543. identifiers = [
  14544. "position", "normal", "uv", "uv2", "tangent", "color",
  14545. "skinIndex", "skinWeight", "lineDistance"
  14546. ];
  14547. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14548. identifiers.push( "morphTarget" + i );
  14549. }
  14550. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14551. identifiers.push( "morphNormal" + i );
  14552. }
  14553. for ( a in attributes ) {
  14554. identifiers.push( a );
  14555. }
  14556. cacheAttributeLocations( program, identifiers );
  14557. program.id = _programs_counter ++;
  14558. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14559. _this.info.memory.programs = _programs.length;
  14560. return program;
  14561. };
  14562. // Shader parameters cache
  14563. function cacheUniformLocations ( program, identifiers ) {
  14564. var i, l, id;
  14565. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14566. id = identifiers[ i ];
  14567. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14568. }
  14569. };
  14570. function cacheAttributeLocations ( program, identifiers ) {
  14571. var i, l, id;
  14572. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14573. id = identifiers[ i ];
  14574. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14575. }
  14576. };
  14577. function addLineNumbers ( string ) {
  14578. var chunks = string.split( "\n" );
  14579. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14580. // Chrome reports shader errors on lines
  14581. // starting counting from 1
  14582. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14583. }
  14584. return chunks.join( "\n" );
  14585. };
  14586. function getShader ( type, string ) {
  14587. var shader;
  14588. if ( type === "fragment" ) {
  14589. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14590. } else if ( type === "vertex" ) {
  14591. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14592. }
  14593. _gl.shaderSource( shader, string );
  14594. _gl.compileShader( shader );
  14595. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14596. console.error( _gl.getShaderInfoLog( shader ) );
  14597. console.error( addLineNumbers( string ) );
  14598. return null;
  14599. }
  14600. return shader;
  14601. };
  14602. // Textures
  14603. function isPowerOfTwo ( value ) {
  14604. return ( value & ( value - 1 ) ) === 0;
  14605. };
  14606. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14607. if ( isImagePowerOfTwo ) {
  14608. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14609. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14610. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14611. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14612. } else {
  14613. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14614. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14615. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14616. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14617. }
  14618. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14619. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14620. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14621. texture.__oldAnisotropy = texture.anisotropy;
  14622. }
  14623. }
  14624. };
  14625. this.setTexture = function ( texture, slot ) {
  14626. if ( texture.needsUpdate ) {
  14627. if ( ! texture.__webglInit ) {
  14628. texture.__webglInit = true;
  14629. texture.addEventListener( 'dispose', onTextureDispose );
  14630. texture.__webglTexture = _gl.createTexture();
  14631. _this.info.memory.textures ++;
  14632. }
  14633. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14634. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14635. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14636. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14637. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14638. var image = texture.image,
  14639. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14640. glFormat = paramThreeToGL( texture.format ),
  14641. glType = paramThreeToGL( texture.type );
  14642. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14643. var mipmap, mipmaps = texture.mipmaps;
  14644. if ( texture instanceof THREE.DataTexture ) {
  14645. // use manually created mipmaps if available
  14646. // if there are no manual mipmaps
  14647. // set 0 level mipmap and then use GL to generate other mipmap levels
  14648. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14649. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14650. mipmap = mipmaps[ i ];
  14651. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14652. }
  14653. texture.generateMipmaps = false;
  14654. } else {
  14655. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14656. }
  14657. } else if ( texture instanceof THREE.CompressedTexture ) {
  14658. // compressed textures can only use manually created mipmaps
  14659. // WebGL can't generate mipmaps for DDS textures
  14660. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14661. mipmap = mipmaps[ i ];
  14662. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14663. }
  14664. } else { // regular Texture (image, video, canvas)
  14665. // use manually created mipmaps if available
  14666. // if there are no manual mipmaps
  14667. // set 0 level mipmap and then use GL to generate other mipmap levels
  14668. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14669. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14670. mipmap = mipmaps[ i ];
  14671. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14672. }
  14673. texture.generateMipmaps = false;
  14674. } else {
  14675. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14676. }
  14677. }
  14678. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14679. texture.needsUpdate = false;
  14680. if ( texture.onUpdate ) texture.onUpdate();
  14681. } else {
  14682. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14683. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14684. }
  14685. };
  14686. function clampToMaxSize ( image, maxSize ) {
  14687. if ( image.width <= maxSize && image.height <= maxSize ) {
  14688. return image;
  14689. }
  14690. // Warning: Scaling through the canvas will only work with images that use
  14691. // premultiplied alpha.
  14692. var maxDimension = Math.max( image.width, image.height );
  14693. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14694. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14695. var canvas = document.createElement( 'canvas' );
  14696. canvas.width = newWidth;
  14697. canvas.height = newHeight;
  14698. var ctx = canvas.getContext( "2d" );
  14699. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14700. return canvas;
  14701. }
  14702. function setCubeTexture ( texture, slot ) {
  14703. if ( texture.image.length === 6 ) {
  14704. if ( texture.needsUpdate ) {
  14705. if ( ! texture.image.__webglTextureCube ) {
  14706. texture.image.__webglTextureCube = _gl.createTexture();
  14707. _this.info.memory.textures ++;
  14708. }
  14709. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14710. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14711. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14712. var isCompressed = texture instanceof THREE.CompressedTexture;
  14713. var cubeImage = [];
  14714. for ( var i = 0; i < 6; i ++ ) {
  14715. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14716. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14717. } else {
  14718. cubeImage[ i ] = texture.image[ i ];
  14719. }
  14720. }
  14721. var image = cubeImage[ 0 ],
  14722. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14723. glFormat = paramThreeToGL( texture.format ),
  14724. glType = paramThreeToGL( texture.type );
  14725. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14726. for ( var i = 0; i < 6; i ++ ) {
  14727. if ( isCompressed ) {
  14728. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14729. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14730. mipmap = mipmaps[ j ];
  14731. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14732. }
  14733. } else {
  14734. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14735. }
  14736. }
  14737. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14738. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14739. }
  14740. texture.needsUpdate = false;
  14741. if ( texture.onUpdate ) texture.onUpdate();
  14742. } else {
  14743. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14744. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14745. }
  14746. }
  14747. };
  14748. function setCubeTextureDynamic ( texture, slot ) {
  14749. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14750. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14751. };
  14752. // Render targets
  14753. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14754. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14755. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14756. };
  14757. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14758. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14759. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14760. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14761. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14762. /* For some reason this is not working. Defaulting to RGBA4.
  14763. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14764. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14765. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14766. */
  14767. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14768. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14769. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14770. } else {
  14771. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14772. }
  14773. };
  14774. this.setRenderTarget = function ( renderTarget ) {
  14775. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14776. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14777. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14778. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14779. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14780. renderTarget.__webglTexture = _gl.createTexture();
  14781. _this.info.memory.textures ++;
  14782. // Setup texture, create render and frame buffers
  14783. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14784. glFormat = paramThreeToGL( renderTarget.format ),
  14785. glType = paramThreeToGL( renderTarget.type );
  14786. if ( isCube ) {
  14787. renderTarget.__webglFramebuffer = [];
  14788. renderTarget.__webglRenderbuffer = [];
  14789. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14790. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14791. for ( var i = 0; i < 6; i ++ ) {
  14792. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14793. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14794. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14795. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14796. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14797. }
  14798. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14799. } else {
  14800. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14801. if ( renderTarget.shareDepthFrom ) {
  14802. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14803. } else {
  14804. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14805. }
  14806. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14807. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14808. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14809. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14810. if ( renderTarget.shareDepthFrom ) {
  14811. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14812. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14813. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14814. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14815. }
  14816. } else {
  14817. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14818. }
  14819. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14820. }
  14821. // Release everything
  14822. if ( isCube ) {
  14823. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14824. } else {
  14825. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14826. }
  14827. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14828. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14829. }
  14830. var framebuffer, width, height, vx, vy;
  14831. if ( renderTarget ) {
  14832. if ( isCube ) {
  14833. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14834. } else {
  14835. framebuffer = renderTarget.__webglFramebuffer;
  14836. }
  14837. width = renderTarget.width;
  14838. height = renderTarget.height;
  14839. vx = 0;
  14840. vy = 0;
  14841. } else {
  14842. framebuffer = null;
  14843. width = _viewportWidth;
  14844. height = _viewportHeight;
  14845. vx = _viewportX;
  14846. vy = _viewportY;
  14847. }
  14848. if ( framebuffer !== _currentFramebuffer ) {
  14849. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14850. _gl.viewport( vx, vy, width, height );
  14851. _currentFramebuffer = framebuffer;
  14852. }
  14853. _currentWidth = width;
  14854. _currentHeight = height;
  14855. };
  14856. function updateRenderTargetMipmap ( renderTarget ) {
  14857. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14858. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14859. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14860. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14861. } else {
  14862. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14863. _gl.generateMipmap( _gl.TEXTURE_2D );
  14864. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14865. }
  14866. };
  14867. // Fallback filters for non-power-of-2 textures
  14868. function filterFallback ( f ) {
  14869. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14870. return _gl.NEAREST;
  14871. }
  14872. return _gl.LINEAR;
  14873. };
  14874. // Map three.js constants to WebGL constants
  14875. function paramThreeToGL ( p ) {
  14876. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14877. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14878. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14879. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14880. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14881. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14882. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14883. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14884. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14885. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14886. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14887. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14888. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14889. if ( p === THREE.ByteType ) return _gl.BYTE;
  14890. if ( p === THREE.ShortType ) return _gl.SHORT;
  14891. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14892. if ( p === THREE.IntType ) return _gl.INT;
  14893. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14894. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14895. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14896. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14897. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14898. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14899. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14900. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14901. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14902. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14903. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14904. if ( p === THREE.OneFactor ) return _gl.ONE;
  14905. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14906. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14907. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14908. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14909. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14910. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14911. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14912. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14913. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14914. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14915. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14916. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14917. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14918. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14919. }
  14920. return 0;
  14921. };
  14922. // Allocations
  14923. function allocateBones ( object ) {
  14924. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14925. return 1024;
  14926. } else {
  14927. // default for when object is not specified
  14928. // ( for example when prebuilding shader
  14929. // to be used with multiple objects )
  14930. //
  14931. // - leave some extra space for other uniforms
  14932. // - limit here is ANGLE's 254 max uniform vectors
  14933. // (up to 54 should be safe)
  14934. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14935. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14936. var maxBones = nVertexMatrices;
  14937. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14938. maxBones = Math.min( object.bones.length, maxBones );
  14939. if ( maxBones < object.bones.length ) {
  14940. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14941. }
  14942. }
  14943. return maxBones;
  14944. }
  14945. };
  14946. function allocateLights ( lights ) {
  14947. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  14948. dirLights = pointLights = spotLights = hemiLights = 0;
  14949. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14950. light = lights[ l ];
  14951. if ( light.onlyShadow ) continue;
  14952. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14953. if ( light instanceof THREE.PointLight ) pointLights ++;
  14954. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14955. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14956. }
  14957. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14958. };
  14959. function allocateShadows ( lights ) {
  14960. var l, ll, light, maxShadows = 0;
  14961. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  14962. light = lights[ l ];
  14963. if ( ! light.castShadow ) continue;
  14964. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14965. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14966. }
  14967. return maxShadows;
  14968. };
  14969. // Initialization
  14970. function initGL () {
  14971. try {
  14972. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  14973. throw 'Error creating WebGL context.';
  14974. }
  14975. } catch ( error ) {
  14976. console.error( error );
  14977. }
  14978. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  14979. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  14980. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  14981. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  14982. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14983. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  14984. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  14985. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14986. if ( ! _glExtensionTextureFloat ) {
  14987. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  14988. }
  14989. if ( ! _glExtensionStandardDerivatives ) {
  14990. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  14991. }
  14992. if ( ! _glExtensionTextureFilterAnisotropic ) {
  14993. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  14994. }
  14995. if ( ! _glExtensionCompressedTextureS3TC ) {
  14996. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  14997. }
  14998. };
  14999. function setDefaultGLState () {
  15000. _gl.clearColor( 0, 0, 0, 1 );
  15001. _gl.clearDepth( 1 );
  15002. _gl.clearStencil( 0 );
  15003. _gl.enable( _gl.DEPTH_TEST );
  15004. _gl.depthFunc( _gl.LEQUAL );
  15005. _gl.frontFace( _gl.CCW );
  15006. _gl.cullFace( _gl.BACK );
  15007. _gl.enable( _gl.CULL_FACE );
  15008. _gl.enable( _gl.BLEND );
  15009. _gl.blendEquation( _gl.FUNC_ADD );
  15010. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15011. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15012. };
  15013. // default plugins (order is important)
  15014. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15015. this.addPrePlugin( this.shadowMapPlugin );
  15016. this.addPostPlugin( new THREE.SpritePlugin() );
  15017. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15018. };
  15019. /**
  15020. * @author szimek / https://github.com/szimek/
  15021. * @author alteredq / http://alteredqualia.com/
  15022. */
  15023. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15024. THREE.EventDispatcher.call( this );
  15025. this.width = width;
  15026. this.height = height;
  15027. options = options || {};
  15028. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15029. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15030. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15031. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15032. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15033. this.offset = new THREE.Vector2( 0, 0 );
  15034. this.repeat = new THREE.Vector2( 1, 1 );
  15035. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15036. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15037. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15038. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15039. this.generateMipmaps = true;
  15040. this.shareDepthFrom = null;
  15041. };
  15042. THREE.WebGLRenderTarget.prototype.clone = function() {
  15043. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15044. tmp.wrapS = this.wrapS;
  15045. tmp.wrapT = this.wrapT;
  15046. tmp.magFilter = this.magFilter;
  15047. tmp.minFilter = this.minFilter;
  15048. tmp.anisotropy = this.anisotropy;
  15049. tmp.offset.copy( this.offset );
  15050. tmp.repeat.copy( this.repeat );
  15051. tmp.format = this.format;
  15052. tmp.type = this.type;
  15053. tmp.depthBuffer = this.depthBuffer;
  15054. tmp.stencilBuffer = this.stencilBuffer;
  15055. tmp.generateMipmaps = this.generateMipmaps;
  15056. tmp.shareDepthFrom = this.shareDepthFrom;
  15057. return tmp;
  15058. };
  15059. THREE.WebGLRenderTarget.prototype.dispose = function () {
  15060. this.dispatchEvent( { type: 'dispose' } );
  15061. };
  15062. /**
  15063. * @author alteredq / http://alteredqualia.com
  15064. */
  15065. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15066. THREE.WebGLRenderTarget.call( this, width, height, options );
  15067. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15068. };
  15069. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15070. /**
  15071. * @author mrdoob / http://mrdoob.com/
  15072. */
  15073. THREE.RenderableVertex = function () {
  15074. this.positionWorld = new THREE.Vector3();
  15075. this.positionScreen = new THREE.Vector4();
  15076. this.visible = true;
  15077. };
  15078. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15079. this.positionWorld.copy( vertex.positionWorld );
  15080. this.positionScreen.copy( vertex.positionScreen );
  15081. };
  15082. /**
  15083. * @author mrdoob / http://mrdoob.com/
  15084. */
  15085. THREE.RenderableFace3 = function () {
  15086. this.v1 = new THREE.RenderableVertex();
  15087. this.v2 = new THREE.RenderableVertex();
  15088. this.v3 = new THREE.RenderableVertex();
  15089. this.centroidModel = new THREE.Vector3();
  15090. this.normalModel = new THREE.Vector3();
  15091. this.normalModelView = new THREE.Vector3();
  15092. this.vertexNormalsLength = 0;
  15093. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15094. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15095. this.color = null;
  15096. this.material = null;
  15097. this.uvs = [[]];
  15098. this.z = null;
  15099. };
  15100. /**
  15101. * @author mrdoob / http://mrdoob.com/
  15102. */
  15103. THREE.RenderableFace4 = function () {
  15104. this.v1 = new THREE.RenderableVertex();
  15105. this.v2 = new THREE.RenderableVertex();
  15106. this.v3 = new THREE.RenderableVertex();
  15107. this.v4 = new THREE.RenderableVertex();
  15108. this.centroidModel = new THREE.Vector3();
  15109. this.normalModel = new THREE.Vector3();
  15110. this.normalModelView = new THREE.Vector3();
  15111. this.vertexNormalsLength = 0;
  15112. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15113. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15114. this.color = null;
  15115. this.material = null;
  15116. this.uvs = [[]];
  15117. this.z = null;
  15118. };
  15119. /**
  15120. * @author mrdoob / http://mrdoob.com/
  15121. */
  15122. THREE.RenderableObject = function () {
  15123. this.object = null;
  15124. this.z = null;
  15125. };
  15126. /**
  15127. * @author mrdoob / http://mrdoob.com/
  15128. */
  15129. THREE.RenderableParticle = function () {
  15130. this.object = null;
  15131. this.x = null;
  15132. this.y = null;
  15133. this.z = null;
  15134. this.rotation = null;
  15135. this.scale = new THREE.Vector2();
  15136. this.material = null;
  15137. };
  15138. /**
  15139. * @author mrdoob / http://mrdoob.com/
  15140. */
  15141. THREE.RenderableLine = function () {
  15142. this.z = null;
  15143. this.v1 = new THREE.RenderableVertex();
  15144. this.v2 = new THREE.RenderableVertex();
  15145. this.material = null;
  15146. };
  15147. /**
  15148. * @author alteredq / http://alteredqualia.com/
  15149. */
  15150. THREE.ColorUtils = {
  15151. adjustHSV : function ( color, h, s, v ) {
  15152. var hsv = THREE.ColorUtils.__hsv;
  15153. color.getHSV( hsv );
  15154. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  15155. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  15156. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  15157. color.setHSV( hsv.h, hsv.s, hsv.v );
  15158. }
  15159. };
  15160. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  15161. * @author mrdoob / http://mrdoob.com/
  15162. * @author alteredq / http://alteredqualia.com/
  15163. */
  15164. THREE.GeometryUtils = {
  15165. // Merge two geometries or geometry and geometry from object (using object's transform)
  15166. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  15167. var matrix, normalMatrix,
  15168. vertexOffset = geometry1.vertices.length,
  15169. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15170. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15171. vertices1 = geometry1.vertices,
  15172. vertices2 = geometry2.vertices,
  15173. faces1 = geometry1.faces,
  15174. faces2 = geometry2.faces,
  15175. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15176. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15177. if ( object2 instanceof THREE.Mesh ) {
  15178. object2.matrixAutoUpdate && object2.updateMatrix();
  15179. matrix = object2.matrix;
  15180. normalMatrix = new THREE.Matrix3();
  15181. normalMatrix.getInverse( matrix );
  15182. normalMatrix.transpose();
  15183. }
  15184. // vertices
  15185. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15186. var vertex = vertices2[ i ];
  15187. var vertexCopy = vertex.clone();
  15188. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15189. vertices1.push( vertexCopy );
  15190. }
  15191. // faces
  15192. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15193. var face = faces2[ i ], faceCopy, normal, color,
  15194. faceVertexNormals = face.vertexNormals,
  15195. faceVertexColors = face.vertexColors;
  15196. if ( face instanceof THREE.Face3 ) {
  15197. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15198. } else if ( face instanceof THREE.Face4 ) {
  15199. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15200. }
  15201. faceCopy.normal.copy( face.normal );
  15202. if ( normalMatrix ) {
  15203. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15204. }
  15205. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15206. normal = faceVertexNormals[ j ].clone();
  15207. if ( normalMatrix ) {
  15208. normal.applyMatrix3( normalMatrix ).normalize();
  15209. }
  15210. faceCopy.vertexNormals.push( normal );
  15211. }
  15212. faceCopy.color.copy( face.color );
  15213. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15214. color = faceVertexColors[ j ];
  15215. faceCopy.vertexColors.push( color.clone() );
  15216. }
  15217. faceCopy.materialIndex = face.materialIndex;
  15218. faceCopy.centroid.copy( face.centroid );
  15219. if ( matrix ) {
  15220. faceCopy.centroid.applyMatrix4( matrix );
  15221. }
  15222. faces1.push( faceCopy );
  15223. }
  15224. // uvs
  15225. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15226. var uv = uvs2[ i ], uvCopy = [];
  15227. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15228. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15229. }
  15230. uvs1.push( uvCopy );
  15231. }
  15232. },
  15233. removeMaterials: function ( geometry, materialIndexArray ) {
  15234. var materialIndexMap = {};
  15235. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15236. materialIndexMap[ materialIndexArray[i] ] = true;
  15237. }
  15238. var face, newFaces = [];
  15239. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15240. face = geometry.faces[ i ];
  15241. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15242. }
  15243. geometry.faces = newFaces;
  15244. },
  15245. // Get random point in triangle (via barycentric coordinates)
  15246. // (uniform distribution)
  15247. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15248. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15249. var a, b, c,
  15250. point = new THREE.Vector3(),
  15251. tmp = THREE.GeometryUtils.__v1;
  15252. a = THREE.GeometryUtils.random();
  15253. b = THREE.GeometryUtils.random();
  15254. if ( ( a + b ) > 1 ) {
  15255. a = 1 - a;
  15256. b = 1 - b;
  15257. }
  15258. c = 1 - a - b;
  15259. point.copy( vectorA );
  15260. point.multiplyScalar( a );
  15261. tmp.copy( vectorB );
  15262. tmp.multiplyScalar( b );
  15263. point.add( tmp );
  15264. tmp.copy( vectorC );
  15265. tmp.multiplyScalar( c );
  15266. point.add( tmp );
  15267. return point;
  15268. },
  15269. // Get random point in face (triangle / quad)
  15270. // (uniform distribution)
  15271. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15272. var vA, vB, vC, vD;
  15273. if ( face instanceof THREE.Face3 ) {
  15274. vA = geometry.vertices[ face.a ];
  15275. vB = geometry.vertices[ face.b ];
  15276. vC = geometry.vertices[ face.c ];
  15277. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15278. } else if ( face instanceof THREE.Face4 ) {
  15279. vA = geometry.vertices[ face.a ];
  15280. vB = geometry.vertices[ face.b ];
  15281. vC = geometry.vertices[ face.c ];
  15282. vD = geometry.vertices[ face.d ];
  15283. var area1, area2;
  15284. if ( useCachedAreas ) {
  15285. if ( face._area1 && face._area2 ) {
  15286. area1 = face._area1;
  15287. area2 = face._area2;
  15288. } else {
  15289. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15290. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15291. face._area1 = area1;
  15292. face._area2 = area2;
  15293. }
  15294. } else {
  15295. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15296. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15297. }
  15298. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15299. if ( r < area1 ) {
  15300. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15301. } else {
  15302. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15303. }
  15304. }
  15305. },
  15306. // Get uniformly distributed random points in mesh
  15307. // - create array with cumulative sums of face areas
  15308. // - pick random number from 0 to total area
  15309. // - find corresponding place in area array by binary search
  15310. // - get random point in face
  15311. randomPointsInGeometry: function ( geometry, n ) {
  15312. var face, i,
  15313. faces = geometry.faces,
  15314. vertices = geometry.vertices,
  15315. il = faces.length,
  15316. totalArea = 0,
  15317. cumulativeAreas = [],
  15318. vA, vB, vC, vD;
  15319. // precompute face areas
  15320. for ( i = 0; i < il; i ++ ) {
  15321. face = faces[ i ];
  15322. if ( face instanceof THREE.Face3 ) {
  15323. vA = vertices[ face.a ];
  15324. vB = vertices[ face.b ];
  15325. vC = vertices[ face.c ];
  15326. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15327. } else if ( face instanceof THREE.Face4 ) {
  15328. vA = vertices[ face.a ];
  15329. vB = vertices[ face.b ];
  15330. vC = vertices[ face.c ];
  15331. vD = vertices[ face.d ];
  15332. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15333. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15334. face._area = face._area1 + face._area2;
  15335. }
  15336. totalArea += face._area;
  15337. cumulativeAreas[ i ] = totalArea;
  15338. }
  15339. // binary search cumulative areas array
  15340. function binarySearchIndices( value ) {
  15341. function binarySearch( start, end ) {
  15342. // return closest larger index
  15343. // if exact number is not found
  15344. if ( end < start )
  15345. return start;
  15346. var mid = start + Math.floor( ( end - start ) / 2 );
  15347. if ( cumulativeAreas[ mid ] > value ) {
  15348. return binarySearch( start, mid - 1 );
  15349. } else if ( cumulativeAreas[ mid ] < value ) {
  15350. return binarySearch( mid + 1, end );
  15351. } else {
  15352. return mid;
  15353. }
  15354. }
  15355. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15356. return result;
  15357. }
  15358. // pick random face weighted by face area
  15359. var r, index,
  15360. result = [];
  15361. var stats = {};
  15362. for ( i = 0; i < n; i ++ ) {
  15363. r = THREE.GeometryUtils.random() * totalArea;
  15364. index = binarySearchIndices( r );
  15365. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15366. if ( ! stats[ index ] ) {
  15367. stats[ index ] = 1;
  15368. } else {
  15369. stats[ index ] += 1;
  15370. }
  15371. }
  15372. return result;
  15373. },
  15374. // Get triangle area (half of parallelogram)
  15375. // http://mathworld.wolfram.com/TriangleArea.html
  15376. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15377. var tmp1 = THREE.GeometryUtils.__v1,
  15378. tmp2 = THREE.GeometryUtils.__v2;
  15379. tmp1.subVectors( vectorB, vectorA );
  15380. tmp2.subVectors( vectorC, vectorA );
  15381. tmp1.cross( tmp2 );
  15382. return 0.5 * tmp1.length();
  15383. },
  15384. // Center geometry so that 0,0,0 is in center of bounding box
  15385. center: function ( geometry ) {
  15386. geometry.computeBoundingBox();
  15387. var bb = geometry.boundingBox;
  15388. var offset = new THREE.Vector3();
  15389. offset.addVectors( bb.min, bb.max );
  15390. offset.multiplyScalar( -0.5 );
  15391. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15392. geometry.computeBoundingBox();
  15393. return offset;
  15394. },
  15395. // Normalize UVs to be from <0,1>
  15396. // (for now just the first set of UVs)
  15397. normalizeUVs: function ( geometry ) {
  15398. var uvSet = geometry.faceVertexUvs[ 0 ];
  15399. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15400. var uvs = uvSet[ i ];
  15401. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15402. // texture repeat
  15403. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15404. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15405. }
  15406. }
  15407. },
  15408. triangulateQuads: function ( geometry ) {
  15409. var i, il, j, jl;
  15410. var faces = [];
  15411. var faceUvs = [];
  15412. var faceVertexUvs = [];
  15413. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15414. faceUvs[ i ] = [];
  15415. }
  15416. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15417. faceVertexUvs[ i ] = [];
  15418. }
  15419. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15420. var face = geometry.faces[ i ];
  15421. if ( face instanceof THREE.Face4 ) {
  15422. var a = face.a;
  15423. var b = face.b;
  15424. var c = face.c;
  15425. var d = face.d;
  15426. var triA = new THREE.Face3();
  15427. var triB = new THREE.Face3();
  15428. triA.color.copy( face.color );
  15429. triB.color.copy( face.color );
  15430. triA.materialIndex = face.materialIndex;
  15431. triB.materialIndex = face.materialIndex;
  15432. triA.a = a;
  15433. triA.b = b;
  15434. triA.c = d;
  15435. triB.a = b;
  15436. triB.b = c;
  15437. triB.c = d;
  15438. if ( face.vertexColors.length === 4 ) {
  15439. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  15440. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  15441. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15442. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  15443. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  15444. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15445. }
  15446. faces.push( triA, triB );
  15447. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15448. if ( geometry.faceVertexUvs[ j ].length ) {
  15449. var uvs = geometry.faceVertexUvs[ j ][ i ];
  15450. var uvA = uvs[ 0 ];
  15451. var uvB = uvs[ 1 ];
  15452. var uvC = uvs[ 2 ];
  15453. var uvD = uvs[ 3 ];
  15454. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  15455. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  15456. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15457. }
  15458. }
  15459. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15460. if ( geometry.faceUvs[ j ].length ) {
  15461. var faceUv = geometry.faceUvs[ j ][ i ];
  15462. faceUvs[ j ].push( faceUv, faceUv );
  15463. }
  15464. }
  15465. } else {
  15466. faces.push( face );
  15467. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15468. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15469. }
  15470. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15471. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15472. }
  15473. }
  15474. }
  15475. geometry.faces = faces;
  15476. geometry.faceUvs = faceUvs;
  15477. geometry.faceVertexUvs = faceVertexUvs;
  15478. geometry.computeCentroids();
  15479. geometry.computeFaceNormals();
  15480. geometry.computeVertexNormals();
  15481. if ( geometry.hasTangents ) geometry.computeTangents();
  15482. },
  15483. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15484. var faces = geometry.faces;
  15485. var start = startFace || 0;
  15486. var end = endFace || faces.length - 1;
  15487. for ( var i = start; i <= end; i ++ ) {
  15488. faces[i].materialIndex = index;
  15489. }
  15490. }
  15491. };
  15492. THREE.GeometryUtils.random = THREE.Math.random16;
  15493. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15494. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15495. /**
  15496. * @author alteredq / http://alteredqualia.com/
  15497. * @author mrdoob / http://mrdoob.com/
  15498. */
  15499. THREE.ImageUtils = {
  15500. crossOrigin: 'anonymous',
  15501. loadTexture: function ( url, mapping, onLoad, onError ) {
  15502. var image = new Image();
  15503. var texture = new THREE.Texture( image, mapping );
  15504. var loader = new THREE.ImageLoader();
  15505. loader.addEventListener( 'load', function ( event ) {
  15506. texture.image = event.content;
  15507. texture.needsUpdate = true;
  15508. if ( onLoad ) onLoad( texture );
  15509. } );
  15510. loader.addEventListener( 'error', function ( event ) {
  15511. if ( onError ) onError( event.message );
  15512. } );
  15513. loader.crossOrigin = this.crossOrigin;
  15514. loader.load( url, image );
  15515. texture.sourceFile = url;
  15516. return texture;
  15517. },
  15518. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15519. var texture = new THREE.CompressedTexture();
  15520. texture.mapping = mapping;
  15521. var request = new XMLHttpRequest();
  15522. request.onload = function () {
  15523. var buffer = request.response;
  15524. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15525. texture.format = dds.format;
  15526. texture.mipmaps = dds.mipmaps;
  15527. texture.image.width = dds.width;
  15528. texture.image.height = dds.height;
  15529. // gl.generateMipmap fails for compressed textures
  15530. // mipmaps must be embedded in the DDS file
  15531. // or texture filters must not use mipmapping
  15532. texture.generateMipmaps = false;
  15533. texture.needsUpdate = true;
  15534. if ( onLoad ) onLoad( texture );
  15535. }
  15536. request.onerror = onError;
  15537. request.open( 'GET', url, true );
  15538. request.responseType = "arraybuffer";
  15539. request.send( null );
  15540. return texture;
  15541. },
  15542. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15543. var images = [];
  15544. images.loadCount = 0;
  15545. var texture = new THREE.Texture();
  15546. texture.image = images;
  15547. if ( mapping !== undefined ) texture.mapping = mapping;
  15548. // no flipping needed for cube textures
  15549. texture.flipY = false;
  15550. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15551. var cubeImage = new Image();
  15552. images[ i ] = cubeImage;
  15553. cubeImage.onload = function () {
  15554. images.loadCount += 1;
  15555. if ( images.loadCount === 6 ) {
  15556. texture.needsUpdate = true;
  15557. if ( onLoad ) onLoad( texture );
  15558. }
  15559. };
  15560. cubeImage.onerror = onError;
  15561. cubeImage.crossOrigin = this.crossOrigin;
  15562. cubeImage.src = array[ i ];
  15563. }
  15564. return texture;
  15565. },
  15566. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15567. var images = [];
  15568. images.loadCount = 0;
  15569. var texture = new THREE.CompressedTexture();
  15570. texture.image = images;
  15571. if ( mapping !== undefined ) texture.mapping = mapping;
  15572. // no flipping for cube textures
  15573. // (also flipping doesn't work for compressed textures )
  15574. texture.flipY = false;
  15575. // can't generate mipmaps for compressed textures
  15576. // mips must be embedded in DDS files
  15577. texture.generateMipmaps = false;
  15578. var generateCubeFaceCallback = function ( rq, img ) {
  15579. return function () {
  15580. var buffer = rq.response;
  15581. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15582. img.format = dds.format;
  15583. img.mipmaps = dds.mipmaps;
  15584. img.width = dds.width;
  15585. img.height = dds.height;
  15586. images.loadCount += 1;
  15587. if ( images.loadCount === 6 ) {
  15588. texture.format = dds.format;
  15589. texture.needsUpdate = true;
  15590. if ( onLoad ) onLoad( texture );
  15591. }
  15592. }
  15593. }
  15594. // compressed cubemap textures as 6 separate DDS files
  15595. if ( array instanceof Array ) {
  15596. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15597. var cubeImage = {};
  15598. images[ i ] = cubeImage;
  15599. var request = new XMLHttpRequest();
  15600. request.onload = generateCubeFaceCallback( request, cubeImage );
  15601. request.onerror = onError;
  15602. var url = array[ i ];
  15603. request.open( 'GET', url, true );
  15604. request.responseType = "arraybuffer";
  15605. request.send( null );
  15606. }
  15607. // compressed cubemap texture stored in a single DDS file
  15608. } else {
  15609. var url = array;
  15610. var request = new XMLHttpRequest();
  15611. request.onload = function( ) {
  15612. var buffer = request.response;
  15613. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15614. if ( dds.isCubemap ) {
  15615. var faces = dds.mipmaps.length / dds.mipmapCount;
  15616. for ( var f = 0; f < faces; f ++ ) {
  15617. images[ f ] = { mipmaps : [] };
  15618. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15619. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15620. images[ f ].format = dds.format;
  15621. images[ f ].width = dds.width;
  15622. images[ f ].height = dds.height;
  15623. }
  15624. }
  15625. texture.format = dds.format;
  15626. texture.needsUpdate = true;
  15627. if ( onLoad ) onLoad( texture );
  15628. }
  15629. }
  15630. request.onerror = onError;
  15631. request.open( 'GET', url, true );
  15632. request.responseType = "arraybuffer";
  15633. request.send( null );
  15634. }
  15635. return texture;
  15636. },
  15637. parseDDS: function ( buffer, loadMipmaps ) {
  15638. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15639. // Adapted from @toji's DDS utils
  15640. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15641. // All values and structures referenced from:
  15642. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15643. var DDS_MAGIC = 0x20534444;
  15644. var DDSD_CAPS = 0x1,
  15645. DDSD_HEIGHT = 0x2,
  15646. DDSD_WIDTH = 0x4,
  15647. DDSD_PITCH = 0x8,
  15648. DDSD_PIXELFORMAT = 0x1000,
  15649. DDSD_MIPMAPCOUNT = 0x20000,
  15650. DDSD_LINEARSIZE = 0x80000,
  15651. DDSD_DEPTH = 0x800000;
  15652. var DDSCAPS_COMPLEX = 0x8,
  15653. DDSCAPS_MIPMAP = 0x400000,
  15654. DDSCAPS_TEXTURE = 0x1000;
  15655. var DDSCAPS2_CUBEMAP = 0x200,
  15656. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15657. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15658. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15659. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15660. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15661. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15662. DDSCAPS2_VOLUME = 0x200000;
  15663. var DDPF_ALPHAPIXELS = 0x1,
  15664. DDPF_ALPHA = 0x2,
  15665. DDPF_FOURCC = 0x4,
  15666. DDPF_RGB = 0x40,
  15667. DDPF_YUV = 0x200,
  15668. DDPF_LUMINANCE = 0x20000;
  15669. function fourCCToInt32( value ) {
  15670. return value.charCodeAt(0) +
  15671. (value.charCodeAt(1) << 8) +
  15672. (value.charCodeAt(2) << 16) +
  15673. (value.charCodeAt(3) << 24);
  15674. }
  15675. function int32ToFourCC( value ) {
  15676. return String.fromCharCode(
  15677. value & 0xff,
  15678. (value >> 8) & 0xff,
  15679. (value >> 16) & 0xff,
  15680. (value >> 24) & 0xff
  15681. );
  15682. }
  15683. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15684. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15685. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15686. var headerLengthInt = 31; // The header length in 32 bit ints
  15687. // Offsets into the header array
  15688. var off_magic = 0;
  15689. var off_size = 1;
  15690. var off_flags = 2;
  15691. var off_height = 3;
  15692. var off_width = 4;
  15693. var off_mipmapCount = 7;
  15694. var off_pfFlags = 20;
  15695. var off_pfFourCC = 21;
  15696. var off_caps = 27;
  15697. var off_caps2 = 28;
  15698. var off_caps3 = 29;
  15699. var off_caps4 = 30;
  15700. // Parse header
  15701. var header = new Int32Array( buffer, 0, headerLengthInt );
  15702. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15703. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15704. return dds;
  15705. }
  15706. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15707. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15708. return dds;
  15709. }
  15710. var blockBytes;
  15711. var fourCC = header[ off_pfFourCC ];
  15712. switch ( fourCC ) {
  15713. case FOURCC_DXT1:
  15714. blockBytes = 8;
  15715. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15716. break;
  15717. case FOURCC_DXT3:
  15718. blockBytes = 16;
  15719. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15720. break;
  15721. case FOURCC_DXT5:
  15722. blockBytes = 16;
  15723. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15724. break;
  15725. default:
  15726. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15727. return dds;
  15728. }
  15729. dds.mipmapCount = 1;
  15730. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15731. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15732. }
  15733. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15734. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15735. dds.width = header[ off_width ];
  15736. dds.height = header[ off_height ];
  15737. var dataOffset = header[ off_size ] + 4;
  15738. // Extract mipmaps buffers
  15739. var width = dds.width;
  15740. var height = dds.height;
  15741. var faces = dds.isCubemap ? 6 : 1;
  15742. for ( var face = 0; face < faces; face ++ ) {
  15743. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15744. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15745. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15746. var mipmap = { "data": byteArray, "width": width, "height": height };
  15747. dds.mipmaps.push( mipmap );
  15748. dataOffset += dataLength;
  15749. width = Math.max( width * 0.5, 1 );
  15750. height = Math.max( height * 0.5, 1 );
  15751. }
  15752. width = dds.width;
  15753. height = dds.height;
  15754. }
  15755. return dds;
  15756. },
  15757. getNormalMap: function ( image, depth ) {
  15758. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15759. var cross = function ( a, b ) {
  15760. 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 ] ];
  15761. }
  15762. var subtract = function ( a, b ) {
  15763. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15764. }
  15765. var normalize = function ( a ) {
  15766. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15767. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15768. }
  15769. depth = depth | 1;
  15770. var width = image.width;
  15771. var height = image.height;
  15772. var canvas = document.createElement( 'canvas' );
  15773. canvas.width = width;
  15774. canvas.height = height;
  15775. var context = canvas.getContext( '2d' );
  15776. context.drawImage( image, 0, 0 );
  15777. var data = context.getImageData( 0, 0, width, height ).data;
  15778. var imageData = context.createImageData( width, height );
  15779. var output = imageData.data;
  15780. for ( var x = 0; x < width; x ++ ) {
  15781. for ( var y = 0; y < height; y ++ ) {
  15782. var ly = y - 1 < 0 ? 0 : y - 1;
  15783. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15784. var lx = x - 1 < 0 ? 0 : x - 1;
  15785. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15786. var points = [];
  15787. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15788. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15789. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15790. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15791. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15792. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15793. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15794. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15795. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15796. var normals = [];
  15797. var num_points = points.length;
  15798. for ( var i = 0; i < num_points; i ++ ) {
  15799. var v1 = points[ i ];
  15800. var v2 = points[ ( i + 1 ) % num_points ];
  15801. v1 = subtract( v1, origin );
  15802. v2 = subtract( v2, origin );
  15803. normals.push( normalize( cross( v1, v2 ) ) );
  15804. }
  15805. var normal = [ 0, 0, 0 ];
  15806. for ( var i = 0; i < normals.length; i ++ ) {
  15807. normal[ 0 ] += normals[ i ][ 0 ];
  15808. normal[ 1 ] += normals[ i ][ 1 ];
  15809. normal[ 2 ] += normals[ i ][ 2 ];
  15810. }
  15811. normal[ 0 ] /= normals.length;
  15812. normal[ 1 ] /= normals.length;
  15813. normal[ 2 ] /= normals.length;
  15814. var idx = ( y * width + x ) * 4;
  15815. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15816. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15817. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15818. output[ idx + 3 ] = 255;
  15819. }
  15820. }
  15821. context.putImageData( imageData, 0, 0 );
  15822. return canvas;
  15823. },
  15824. generateDataTexture: function ( width, height, color ) {
  15825. var size = width * height;
  15826. var data = new Uint8Array( 3 * size );
  15827. var r = Math.floor( color.r * 255 );
  15828. var g = Math.floor( color.g * 255 );
  15829. var b = Math.floor( color.b * 255 );
  15830. for ( var i = 0; i < size; i ++ ) {
  15831. data[ i * 3 ] = r;
  15832. data[ i * 3 + 1 ] = g;
  15833. data[ i * 3 + 2 ] = b;
  15834. }
  15835. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15836. texture.needsUpdate = true;
  15837. return texture;
  15838. }
  15839. };
  15840. /**
  15841. * @author alteredq / http://alteredqualia.com/
  15842. */
  15843. THREE.SceneUtils = {
  15844. createMultiMaterialObject: function ( geometry, materials ) {
  15845. var group = new THREE.Object3D();
  15846. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15847. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15848. }
  15849. return group;
  15850. },
  15851. detach : function ( child, parent, scene ) {
  15852. child.applyMatrix( parent.matrixWorld );
  15853. parent.remove( child );
  15854. scene.add( child );
  15855. },
  15856. attach: function ( child, scene, parent ) {
  15857. var matrixWorldInverse = new THREE.Matrix4();
  15858. matrixWorldInverse.getInverse( parent.matrixWorld );
  15859. child.applyMatrix( matrixWorldInverse );
  15860. scene.remove( child );
  15861. parent.add( child );
  15862. }
  15863. };
  15864. /**
  15865. * @author zz85 / http://www.lab4games.net/zz85/blog
  15866. * @author alteredq / http://alteredqualia.com/
  15867. *
  15868. * For Text operations in three.js (See TextGeometry)
  15869. *
  15870. * It uses techniques used in:
  15871. *
  15872. * typeface.js and canvastext
  15873. * For converting fonts and rendering with javascript
  15874. * http://typeface.neocracy.org
  15875. *
  15876. * Triangulation ported from AS3
  15877. * Simple Polygon Triangulation
  15878. * http://actionsnippet.com/?p=1462
  15879. *
  15880. * A Method to triangulate shapes with holes
  15881. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15882. *
  15883. */
  15884. THREE.FontUtils = {
  15885. faces : {},
  15886. // Just for now. face[weight][style]
  15887. face : "helvetiker",
  15888. weight: "normal",
  15889. style : "normal",
  15890. size : 150,
  15891. divisions : 10,
  15892. getFace : function() {
  15893. return this.faces[ this.face ][ this.weight ][ this.style ];
  15894. },
  15895. loadFace : function( data ) {
  15896. var family = data.familyName.toLowerCase();
  15897. var ThreeFont = this;
  15898. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15899. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15900. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15901. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15902. return data;
  15903. },
  15904. drawText : function( text ) {
  15905. var characterPts = [], allPts = [];
  15906. // RenderText
  15907. var i, p,
  15908. face = this.getFace(),
  15909. scale = this.size / face.resolution,
  15910. offset = 0,
  15911. chars = String( text ).split( '' ),
  15912. length = chars.length;
  15913. var fontPaths = [];
  15914. for ( i = 0; i < length; i ++ ) {
  15915. var path = new THREE.Path();
  15916. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15917. offset += ret.offset;
  15918. fontPaths.push( ret.path );
  15919. }
  15920. // get the width
  15921. var width = offset / 2;
  15922. //
  15923. // for ( p = 0; p < allPts.length; p++ ) {
  15924. //
  15925. // allPts[ p ].x -= width;
  15926. //
  15927. // }
  15928. //var extract = this.extractPoints( allPts, characterPts );
  15929. //extract.contour = allPts;
  15930. //extract.paths = fontPaths;
  15931. //extract.offset = width;
  15932. return { paths : fontPaths, offset : width };
  15933. },
  15934. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15935. var pts = [];
  15936. var i, i2, divisions,
  15937. outline, action, length,
  15938. scaleX, scaleY,
  15939. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15940. laste,
  15941. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15942. if ( !glyph ) return;
  15943. if ( glyph.o ) {
  15944. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15945. length = outline.length;
  15946. scaleX = scale;
  15947. scaleY = scale;
  15948. for ( i = 0; i < length; ) {
  15949. action = outline[ i ++ ];
  15950. //console.log( action );
  15951. switch( action ) {
  15952. case 'm':
  15953. // Move To
  15954. x = outline[ i++ ] * scaleX + offset;
  15955. y = outline[ i++ ] * scaleY;
  15956. path.moveTo( x, y );
  15957. break;
  15958. case 'l':
  15959. // Line To
  15960. x = outline[ i++ ] * scaleX + offset;
  15961. y = outline[ i++ ] * scaleY;
  15962. path.lineTo(x,y);
  15963. break;
  15964. case 'q':
  15965. // QuadraticCurveTo
  15966. cpx = outline[ i++ ] * scaleX + offset;
  15967. cpy = outline[ i++ ] * scaleY;
  15968. cpx1 = outline[ i++ ] * scaleX + offset;
  15969. cpy1 = outline[ i++ ] * scaleY;
  15970. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15971. laste = pts[ pts.length - 1 ];
  15972. if ( laste ) {
  15973. cpx0 = laste.x;
  15974. cpy0 = laste.y;
  15975. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15976. var t = i2 / divisions;
  15977. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15978. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15979. }
  15980. }
  15981. break;
  15982. case 'b':
  15983. // Cubic Bezier Curve
  15984. cpx = outline[ i++ ] * scaleX + offset;
  15985. cpy = outline[ i++ ] * scaleY;
  15986. cpx1 = outline[ i++ ] * scaleX + offset;
  15987. cpy1 = outline[ i++ ] * -scaleY;
  15988. cpx2 = outline[ i++ ] * scaleX + offset;
  15989. cpy2 = outline[ i++ ] * -scaleY;
  15990. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15991. laste = pts[ pts.length - 1 ];
  15992. if ( laste ) {
  15993. cpx0 = laste.x;
  15994. cpy0 = laste.y;
  15995. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15996. var t = i2 / divisions;
  15997. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15998. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15999. }
  16000. }
  16001. break;
  16002. }
  16003. }
  16004. }
  16005. return { offset: glyph.ha*scale, path:path};
  16006. }
  16007. };
  16008. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16009. // Parameters
  16010. parameters = parameters || {};
  16011. var size = parameters.size !== undefined ? parameters.size : 100;
  16012. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16013. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16014. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16015. var style = parameters.style !== undefined ? parameters.style : "normal";
  16016. THREE.FontUtils.size = size;
  16017. THREE.FontUtils.divisions = curveSegments;
  16018. THREE.FontUtils.face = font;
  16019. THREE.FontUtils.weight = weight;
  16020. THREE.FontUtils.style = style;
  16021. // Get a Font data json object
  16022. var data = THREE.FontUtils.drawText( text );
  16023. var paths = data.paths;
  16024. var shapes = [];
  16025. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16026. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16027. }
  16028. return shapes;
  16029. };
  16030. /**
  16031. * This code is a quick port of code written in C++ which was submitted to
  16032. * flipcode.com by John W. Ratcliff // July 22, 2000
  16033. * See original code and more information here:
  16034. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16035. *
  16036. * ported to actionscript by Zevan Rosser
  16037. * www.actionsnippet.com
  16038. *
  16039. * ported to javascript by Joshua Koo
  16040. * http://www.lab4games.net/zz85/blog
  16041. *
  16042. */
  16043. ( function( namespace ) {
  16044. var EPSILON = 0.0000000001;
  16045. // takes in an contour array and returns
  16046. var process = function( contour, indices ) {
  16047. var n = contour.length;
  16048. if ( n < 3 ) return null;
  16049. var result = [],
  16050. verts = [],
  16051. vertIndices = [];
  16052. /* we want a counter-clockwise polygon in verts */
  16053. var u, v, w;
  16054. if ( area( contour ) > 0.0 ) {
  16055. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16056. } else {
  16057. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16058. }
  16059. var nv = n;
  16060. /* remove nv - 2 vertices, creating 1 triangle every time */
  16061. var count = 2 * nv; /* error detection */
  16062. for( v = nv - 1; nv > 2; ) {
  16063. /* if we loop, it is probably a non-simple polygon */
  16064. if ( ( count-- ) <= 0 ) {
  16065. //** Triangulate: ERROR - probable bad polygon!
  16066. //throw ( "Warning, unable to triangulate polygon!" );
  16067. //return null;
  16068. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16069. console.log( "Warning, unable to triangulate polygon!" );
  16070. if ( indices ) return vertIndices;
  16071. return result;
  16072. }
  16073. /* three consecutive vertices in current polygon, <u,v,w> */
  16074. u = v; if ( nv <= u ) u = 0; /* previous */
  16075. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16076. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16077. if ( snip( contour, u, v, w, nv, verts ) ) {
  16078. var a, b, c, s, t;
  16079. /* true names of the vertices */
  16080. a = verts[ u ];
  16081. b = verts[ v ];
  16082. c = verts[ w ];
  16083. /* output Triangle */
  16084. result.push( [ contour[ a ],
  16085. contour[ b ],
  16086. contour[ c ] ] );
  16087. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16088. /* remove v from the remaining polygon */
  16089. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16090. verts[ s ] = verts[ t ];
  16091. }
  16092. nv--;
  16093. /* reset error detection counter */
  16094. count = 2 * nv;
  16095. }
  16096. }
  16097. if ( indices ) return vertIndices;
  16098. return result;
  16099. };
  16100. // calculate area of the contour polygon
  16101. var area = function ( contour ) {
  16102. var n = contour.length;
  16103. var a = 0.0;
  16104. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16105. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16106. }
  16107. return a * 0.5;
  16108. };
  16109. var snip = function ( contour, u, v, w, n, verts ) {
  16110. var p;
  16111. var ax, ay, bx, by;
  16112. var cx, cy, px, py;
  16113. ax = contour[ verts[ u ] ].x;
  16114. ay = contour[ verts[ u ] ].y;
  16115. bx = contour[ verts[ v ] ].x;
  16116. by = contour[ verts[ v ] ].y;
  16117. cx = contour[ verts[ w ] ].x;
  16118. cy = contour[ verts[ w ] ].y;
  16119. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16120. var aX, aY, bX, bY, cX, cY;
  16121. var apx, apy, bpx, bpy, cpx, cpy;
  16122. var cCROSSap, bCROSScp, aCROSSbp;
  16123. aX = cx - bx; aY = cy - by;
  16124. bX = ax - cx; bY = ay - cy;
  16125. cX = bx - ax; cY = by - ay;
  16126. for ( p = 0; p < n; p++ ) {
  16127. if( (p === u) || (p === v) || (p === w) ) continue;
  16128. px = contour[ verts[ p ] ].x
  16129. py = contour[ verts[ p ] ].y
  16130. apx = px - ax; apy = py - ay;
  16131. bpx = px - bx; bpy = py - by;
  16132. cpx = px - cx; cpy = py - cy;
  16133. // see if p is inside triangle abc
  16134. aCROSSbp = aX*bpy - aY*bpx;
  16135. cCROSSap = cX*apy - cY*apx;
  16136. bCROSScp = bX*cpy - bY*cpx;
  16137. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16138. }
  16139. return true;
  16140. };
  16141. namespace.Triangulate = process;
  16142. namespace.Triangulate.area = area;
  16143. return namespace;
  16144. })(THREE.FontUtils);
  16145. // To use the typeface.js face files, hook up the API
  16146. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16147. * @author zz85 / http://www.lab4games.net/zz85/blog
  16148. * Extensible curve object
  16149. *
  16150. * Some common of Curve methods
  16151. * .getPoint(t), getTangent(t)
  16152. * .getPointAt(u), getTagentAt(u)
  16153. * .getPoints(), .getSpacedPoints()
  16154. * .getLength()
  16155. * .updateArcLengths()
  16156. *
  16157. * This file contains following classes:
  16158. *
  16159. * -- 2d classes --
  16160. * THREE.Curve
  16161. * THREE.LineCurve
  16162. * THREE.QuadraticBezierCurve
  16163. * THREE.CubicBezierCurve
  16164. * THREE.SplineCurve
  16165. * THREE.ArcCurve
  16166. * THREE.EllipseCurve
  16167. *
  16168. * -- 3d classes --
  16169. * THREE.LineCurve3
  16170. * THREE.QuadraticBezierCurve3
  16171. * THREE.CubicBezierCurve3
  16172. * THREE.SplineCurve3
  16173. * THREE.ClosedSplineCurve3
  16174. *
  16175. * A series of curves can be represented as a THREE.CurvePath
  16176. *
  16177. **/
  16178. /**************************************************************
  16179. * Abstract Curve base class
  16180. **************************************************************/
  16181. THREE.Curve = function () {
  16182. };
  16183. // Virtual base class method to overwrite and implement in subclasses
  16184. // - t [0 .. 1]
  16185. THREE.Curve.prototype.getPoint = function ( t ) {
  16186. console.log( "Warning, getPoint() not implemented!" );
  16187. return null;
  16188. };
  16189. // Get point at relative position in curve according to arc length
  16190. // - u [0 .. 1]
  16191. THREE.Curve.prototype.getPointAt = function ( u ) {
  16192. var t = this.getUtoTmapping( u );
  16193. return this.getPoint( t );
  16194. };
  16195. // Get sequence of points using getPoint( t )
  16196. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16197. if ( !divisions ) divisions = 5;
  16198. var d, pts = [];
  16199. for ( d = 0; d <= divisions; d ++ ) {
  16200. pts.push( this.getPoint( d / divisions ) );
  16201. }
  16202. return pts;
  16203. };
  16204. // Get sequence of points using getPointAt( u )
  16205. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16206. if ( !divisions ) divisions = 5;
  16207. var d, pts = [];
  16208. for ( d = 0; d <= divisions; d ++ ) {
  16209. pts.push( this.getPointAt( d / divisions ) );
  16210. }
  16211. return pts;
  16212. };
  16213. // Get total curve arc length
  16214. THREE.Curve.prototype.getLength = function () {
  16215. var lengths = this.getLengths();
  16216. return lengths[ lengths.length - 1 ];
  16217. };
  16218. // Get list of cumulative segment lengths
  16219. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16220. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16221. if ( this.cacheArcLengths
  16222. && ( this.cacheArcLengths.length == divisions + 1 )
  16223. && !this.needsUpdate) {
  16224. //console.log( "cached", this.cacheArcLengths );
  16225. return this.cacheArcLengths;
  16226. }
  16227. this.needsUpdate = false;
  16228. var cache = [];
  16229. var current, last = this.getPoint( 0 );
  16230. var p, sum = 0;
  16231. cache.push( 0 );
  16232. for ( p = 1; p <= divisions; p ++ ) {
  16233. current = this.getPoint ( p / divisions );
  16234. sum += current.distanceTo( last );
  16235. cache.push( sum );
  16236. last = current;
  16237. }
  16238. this.cacheArcLengths = cache;
  16239. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16240. };
  16241. THREE.Curve.prototype.updateArcLengths = function() {
  16242. this.needsUpdate = true;
  16243. this.getLengths();
  16244. };
  16245. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16246. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16247. var arcLengths = this.getLengths();
  16248. var i = 0, il = arcLengths.length;
  16249. var targetArcLength; // The targeted u distance value to get
  16250. if ( distance ) {
  16251. targetArcLength = distance;
  16252. } else {
  16253. targetArcLength = u * arcLengths[ il - 1 ];
  16254. }
  16255. //var time = Date.now();
  16256. // binary search for the index with largest value smaller than target u distance
  16257. var low = 0, high = il - 1, comparison;
  16258. while ( low <= high ) {
  16259. 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
  16260. comparison = arcLengths[ i ] - targetArcLength;
  16261. if ( comparison < 0 ) {
  16262. low = i + 1;
  16263. continue;
  16264. } else if ( comparison > 0 ) {
  16265. high = i - 1;
  16266. continue;
  16267. } else {
  16268. high = i;
  16269. break;
  16270. // DONE
  16271. }
  16272. }
  16273. i = high;
  16274. //console.log('b' , i, low, high, Date.now()- time);
  16275. if ( arcLengths[ i ] == targetArcLength ) {
  16276. var t = i / ( il - 1 );
  16277. return t;
  16278. }
  16279. // we could get finer grain at lengths, or use simple interpolatation between two points
  16280. var lengthBefore = arcLengths[ i ];
  16281. var lengthAfter = arcLengths[ i + 1 ];
  16282. var segmentLength = lengthAfter - lengthBefore;
  16283. // determine where we are between the 'before' and 'after' points
  16284. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16285. // add that fractional amount to t
  16286. var t = ( i + segmentFraction ) / ( il -1 );
  16287. return t;
  16288. };
  16289. // Returns a unit vector tangent at t
  16290. // In case any sub curve does not implement its tangent derivation,
  16291. // 2 points a small delta apart will be used to find its gradient
  16292. // which seems to give a reasonable approximation
  16293. THREE.Curve.prototype.getTangent = function( t ) {
  16294. var delta = 0.0001;
  16295. var t1 = t - delta;
  16296. var t2 = t + delta;
  16297. // Capping in case of danger
  16298. if ( t1 < 0 ) t1 = 0;
  16299. if ( t2 > 1 ) t2 = 1;
  16300. var pt1 = this.getPoint( t1 );
  16301. var pt2 = this.getPoint( t2 );
  16302. var vec = pt2.clone().sub(pt1);
  16303. return vec.normalize();
  16304. };
  16305. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16306. var t = this.getUtoTmapping( u );
  16307. return this.getTangent( t );
  16308. };
  16309. /**************************************************************
  16310. * Line
  16311. **************************************************************/
  16312. THREE.LineCurve = function ( v1, v2 ) {
  16313. this.v1 = v1;
  16314. this.v2 = v2;
  16315. };
  16316. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16317. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16318. var point = this.v2.clone().sub(this.v1);
  16319. point.multiplyScalar( t ).add( this.v1 );
  16320. return point;
  16321. };
  16322. // Line curve is linear, so we can overwrite default getPointAt
  16323. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16324. return this.getPoint( u );
  16325. };
  16326. THREE.LineCurve.prototype.getTangent = function( t ) {
  16327. var tangent = this.v2.clone().sub(this.v1);
  16328. return tangent.normalize();
  16329. };
  16330. /**************************************************************
  16331. * Quadratic Bezier curve
  16332. **************************************************************/
  16333. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16334. this.v0 = v0;
  16335. this.v1 = v1;
  16336. this.v2 = v2;
  16337. };
  16338. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16339. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16340. var tx, ty;
  16341. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16342. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16343. return new THREE.Vector2( tx, ty );
  16344. };
  16345. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16346. var tx, ty;
  16347. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16348. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16349. // returns unit vector
  16350. var tangent = new THREE.Vector2( tx, ty );
  16351. tangent.normalize();
  16352. return tangent;
  16353. };
  16354. /**************************************************************
  16355. * Cubic Bezier curve
  16356. **************************************************************/
  16357. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16358. this.v0 = v0;
  16359. this.v1 = v1;
  16360. this.v2 = v2;
  16361. this.v3 = v3;
  16362. };
  16363. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16364. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16365. var tx, ty;
  16366. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16367. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16368. return new THREE.Vector2( tx, ty );
  16369. };
  16370. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16371. var tx, ty;
  16372. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16373. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16374. var tangent = new THREE.Vector2( tx, ty );
  16375. tangent.normalize();
  16376. return tangent;
  16377. };
  16378. /**************************************************************
  16379. * Spline curve
  16380. **************************************************************/
  16381. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16382. this.points = (points == undefined) ? [] : points;
  16383. };
  16384. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16385. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16386. var v = new THREE.Vector2();
  16387. var c = [];
  16388. var points = this.points, point, intPoint, weight;
  16389. point = ( points.length - 1 ) * t;
  16390. intPoint = Math.floor( point );
  16391. weight = point - intPoint;
  16392. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16393. c[ 1 ] = intPoint;
  16394. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16395. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16396. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16397. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16398. return v;
  16399. };
  16400. /**************************************************************
  16401. * Ellipse curve
  16402. **************************************************************/
  16403. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16404. aStartAngle, aEndAngle,
  16405. aClockwise ) {
  16406. this.aX = aX;
  16407. this.aY = aY;
  16408. this.xRadius = xRadius;
  16409. this.yRadius = yRadius;
  16410. this.aStartAngle = aStartAngle;
  16411. this.aEndAngle = aEndAngle;
  16412. this.aClockwise = aClockwise;
  16413. };
  16414. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16415. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16416. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16417. if ( !this.aClockwise ) {
  16418. t = 1 - t;
  16419. }
  16420. var angle = this.aStartAngle + t * deltaAngle;
  16421. var tx = this.aX + this.xRadius * Math.cos( angle );
  16422. var ty = this.aY + this.yRadius * Math.sin( angle );
  16423. return new THREE.Vector2( tx, ty );
  16424. };
  16425. /**************************************************************
  16426. * Arc curve
  16427. **************************************************************/
  16428. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16429. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16430. };
  16431. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16432. /**************************************************************
  16433. * Utils
  16434. **************************************************************/
  16435. THREE.Curve.Utils = {
  16436. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16437. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16438. },
  16439. // Puay Bing, thanks for helping with this derivative!
  16440. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16441. return -3 * p0 * (1 - t) * (1 - t) +
  16442. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16443. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16444. 3 * t * t * p3;
  16445. },
  16446. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16447. // To check if my formulas are correct
  16448. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16449. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16450. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16451. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16452. return h00 + h10 + h01 + h11;
  16453. },
  16454. // Catmull-Rom
  16455. interpolate: function( p0, p1, p2, p3, t ) {
  16456. var v0 = ( p2 - p0 ) * 0.5;
  16457. var v1 = ( p3 - p1 ) * 0.5;
  16458. var t2 = t * t;
  16459. var t3 = t * t2;
  16460. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16461. }
  16462. };
  16463. // TODO: Transformation for Curves?
  16464. /**************************************************************
  16465. * 3D Curves
  16466. **************************************************************/
  16467. // A Factory method for creating new curve subclasses
  16468. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16469. constructor.prototype = Object.create( THREE.Curve.prototype );
  16470. constructor.prototype.getPoint = getPointFunc;
  16471. return constructor;
  16472. };
  16473. /**************************************************************
  16474. * Line3D
  16475. **************************************************************/
  16476. THREE.LineCurve3 = THREE.Curve.create(
  16477. function ( v1, v2 ) {
  16478. this.v1 = v1;
  16479. this.v2 = v2;
  16480. },
  16481. function ( t ) {
  16482. var r = new THREE.Vector3();
  16483. r.subVectors( this.v2, this.v1 ); // diff
  16484. r.multiplyScalar( t );
  16485. r.add( this.v1 );
  16486. return r;
  16487. }
  16488. );
  16489. /**************************************************************
  16490. * Quadratic Bezier 3D curve
  16491. **************************************************************/
  16492. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16493. function ( v0, v1, v2 ) {
  16494. this.v0 = v0;
  16495. this.v1 = v1;
  16496. this.v2 = v2;
  16497. },
  16498. function ( t ) {
  16499. var tx, ty, tz;
  16500. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16501. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16502. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16503. return new THREE.Vector3( tx, ty, tz );
  16504. }
  16505. );
  16506. /**************************************************************
  16507. * Cubic Bezier 3D curve
  16508. **************************************************************/
  16509. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16510. function ( v0, v1, v2, v3 ) {
  16511. this.v0 = v0;
  16512. this.v1 = v1;
  16513. this.v2 = v2;
  16514. this.v3 = v3;
  16515. },
  16516. function ( t ) {
  16517. var tx, ty, tz;
  16518. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16519. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16520. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16521. return new THREE.Vector3( tx, ty, tz );
  16522. }
  16523. );
  16524. /**************************************************************
  16525. * Spline 3D curve
  16526. **************************************************************/
  16527. THREE.SplineCurve3 = THREE.Curve.create(
  16528. function ( points /* array of Vector3 */) {
  16529. this.points = (points == undefined) ? [] : points;
  16530. },
  16531. function ( t ) {
  16532. var v = new THREE.Vector3();
  16533. var c = [];
  16534. var points = this.points, point, intPoint, weight;
  16535. point = ( points.length - 1 ) * t;
  16536. intPoint = Math.floor( point );
  16537. weight = point - intPoint;
  16538. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16539. c[ 1 ] = intPoint;
  16540. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16541. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16542. var pt0 = points[ c[0] ],
  16543. pt1 = points[ c[1] ],
  16544. pt2 = points[ c[2] ],
  16545. pt3 = points[ c[3] ];
  16546. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16547. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16548. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16549. return v;
  16550. }
  16551. );
  16552. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16553. // var v = new THREE.Vector3();
  16554. // var c = [];
  16555. // var points = this.points, point, intPoint, weight;
  16556. // point = ( points.length - 1 ) * t;
  16557. // intPoint = Math.floor( point );
  16558. // weight = point - intPoint;
  16559. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16560. // c[ 1 ] = intPoint;
  16561. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16562. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16563. // var pt0 = points[ c[0] ],
  16564. // pt1 = points[ c[1] ],
  16565. // pt2 = points[ c[2] ],
  16566. // pt3 = points[ c[3] ];
  16567. // // t = weight;
  16568. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16569. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16570. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16571. // return v;
  16572. // }
  16573. /**************************************************************
  16574. * Closed Spline 3D curve
  16575. **************************************************************/
  16576. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16577. function ( points /* array of Vector3 */) {
  16578. this.points = (points == undefined) ? [] : points;
  16579. },
  16580. function ( t ) {
  16581. var v = new THREE.Vector3();
  16582. var c = [];
  16583. var points = this.points, point, intPoint, weight;
  16584. point = ( points.length - 0 ) * t;
  16585. // This needs to be from 0-length +1
  16586. intPoint = Math.floor( point );
  16587. weight = point - intPoint;
  16588. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16589. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16590. c[ 1 ] = ( intPoint ) % points.length;
  16591. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16592. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16593. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16594. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16595. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16596. return v;
  16597. }
  16598. );
  16599. /**
  16600. * @author zz85 / http://www.lab4games.net/zz85/blog
  16601. *
  16602. **/
  16603. /**************************************************************
  16604. * Curved Path - a curve path is simply a array of connected
  16605. * curves, but retains the api of a curve
  16606. **************************************************************/
  16607. THREE.CurvePath = function () {
  16608. this.curves = [];
  16609. this.bends = [];
  16610. this.autoClose = false; // Automatically closes the path
  16611. };
  16612. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16613. THREE.CurvePath.prototype.add = function ( curve ) {
  16614. this.curves.push( curve );
  16615. };
  16616. THREE.CurvePath.prototype.checkConnection = function() {
  16617. // TODO
  16618. // If the ending of curve is not connected to the starting
  16619. // or the next curve, then, this is not a real path
  16620. };
  16621. THREE.CurvePath.prototype.closePath = function() {
  16622. // TODO Test
  16623. // and verify for vector3 (needs to implement equals)
  16624. // Add a line curve if start and end of lines are not connected
  16625. var startPoint = this.curves[0].getPoint(0);
  16626. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16627. if (!startPoint.equals(endPoint)) {
  16628. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16629. }
  16630. };
  16631. // To get accurate point with reference to
  16632. // entire path distance at time t,
  16633. // following has to be done:
  16634. // 1. Length of each sub path have to be known
  16635. // 2. Locate and identify type of curve
  16636. // 3. Get t for the curve
  16637. // 4. Return curve.getPointAt(t')
  16638. THREE.CurvePath.prototype.getPoint = function( t ) {
  16639. var d = t * this.getLength();
  16640. var curveLengths = this.getCurveLengths();
  16641. var i = 0, diff, curve;
  16642. // To think about boundaries points.
  16643. while ( i < curveLengths.length ) {
  16644. if ( curveLengths[ i ] >= d ) {
  16645. diff = curveLengths[ i ] - d;
  16646. curve = this.curves[ i ];
  16647. var u = 1 - diff / curve.getLength();
  16648. return curve.getPointAt( u );
  16649. break;
  16650. }
  16651. i ++;
  16652. }
  16653. return null;
  16654. // loop where sum != 0, sum > d , sum+1 <d
  16655. };
  16656. /*
  16657. THREE.CurvePath.prototype.getTangent = function( t ) {
  16658. };*/
  16659. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16660. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16661. // getPoint() depends on getLength
  16662. THREE.CurvePath.prototype.getLength = function() {
  16663. var lens = this.getCurveLengths();
  16664. return lens[ lens.length - 1 ];
  16665. };
  16666. // Compute lengths and cache them
  16667. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16668. THREE.CurvePath.prototype.getCurveLengths = function() {
  16669. // We use cache values if curves and cache array are same length
  16670. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16671. return this.cacheLengths;
  16672. };
  16673. // Get length of subsurve
  16674. // Push sums into cached array
  16675. var lengths = [], sums = 0;
  16676. var i, il = this.curves.length;
  16677. for ( i = 0; i < il; i ++ ) {
  16678. sums += this.curves[ i ].getLength();
  16679. lengths.push( sums );
  16680. }
  16681. this.cacheLengths = lengths;
  16682. return lengths;
  16683. };
  16684. // Returns min and max coordinates, as well as centroid
  16685. THREE.CurvePath.prototype.getBoundingBox = function () {
  16686. var points = this.getPoints();
  16687. var maxX, maxY, maxZ;
  16688. var minX, minY, minZ;
  16689. maxX = maxY = Number.NEGATIVE_INFINITY;
  16690. minX = minY = Number.POSITIVE_INFINITY;
  16691. var p, i, il, sum;
  16692. var v3 = points[0] instanceof THREE.Vector3;
  16693. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16694. for ( i = 0, il = points.length; i < il; i ++ ) {
  16695. p = points[ i ];
  16696. if ( p.x > maxX ) maxX = p.x;
  16697. else if ( p.x < minX ) minX = p.x;
  16698. if ( p.y > maxY ) maxY = p.y;
  16699. else if ( p.y < minY ) minY = p.y;
  16700. if ( v3 ) {
  16701. if ( p.z > maxZ ) maxZ = p.z;
  16702. else if ( p.z < minZ ) minZ = p.z;
  16703. }
  16704. sum.add( p );
  16705. }
  16706. var ret = {
  16707. minX: minX,
  16708. minY: minY,
  16709. maxX: maxX,
  16710. maxY: maxY,
  16711. centroid: sum.divideScalar( il )
  16712. };
  16713. if ( v3 ) {
  16714. ret.maxZ = maxZ;
  16715. ret.minZ = minZ;
  16716. }
  16717. return ret;
  16718. };
  16719. /**************************************************************
  16720. * Create Geometries Helpers
  16721. **************************************************************/
  16722. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16723. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16724. var pts = this.getPoints( divisions, true );
  16725. return this.createGeometry( pts );
  16726. };
  16727. // Generate geometry from equidistance sampling along the path
  16728. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16729. var pts = this.getSpacedPoints( divisions, true );
  16730. return this.createGeometry( pts );
  16731. };
  16732. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16733. var geometry = new THREE.Geometry();
  16734. for ( var i = 0; i < points.length; i ++ ) {
  16735. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16736. }
  16737. return geometry;
  16738. };
  16739. /**************************************************************
  16740. * Bend / Wrap Helper Methods
  16741. **************************************************************/
  16742. // Wrap path / Bend modifiers?
  16743. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16744. this.bends.push( bendpath );
  16745. };
  16746. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16747. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16748. var i, il;
  16749. if ( !bends ) {
  16750. bends = this.bends;
  16751. }
  16752. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16753. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16754. }
  16755. return oldPts;
  16756. };
  16757. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16758. var oldPts = this.getSpacedPoints( segments );
  16759. var i, il;
  16760. if ( !bends ) {
  16761. bends = this.bends;
  16762. }
  16763. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16764. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16765. }
  16766. return oldPts;
  16767. };
  16768. // This returns getPoints() bend/wrapped around the contour of a path.
  16769. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16770. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16771. var bounds = this.getBoundingBox();
  16772. var i, il, p, oldX, oldY, xNorm;
  16773. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16774. p = oldPts[ i ];
  16775. oldX = p.x;
  16776. oldY = p.y;
  16777. xNorm = oldX / bounds.maxX;
  16778. // If using actual distance, for length > path, requires line extrusions
  16779. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16780. xNorm = path.getUtoTmapping( xNorm, oldX );
  16781. // check for out of bounds?
  16782. var pathPt = path.getPoint( xNorm );
  16783. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16784. p.x = pathPt.x + normal.x;
  16785. p.y = pathPt.y + normal.y;
  16786. }
  16787. return oldPts;
  16788. };
  16789. /**
  16790. * @author alteredq / http://alteredqualia.com/
  16791. */
  16792. THREE.Gyroscope = function () {
  16793. THREE.Object3D.call( this );
  16794. };
  16795. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16796. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16797. this.matrixAutoUpdate && this.updateMatrix();
  16798. // update matrixWorld
  16799. if ( this.matrixWorldNeedsUpdate || force ) {
  16800. if ( this.parent ) {
  16801. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16802. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16803. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16804. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16805. } else {
  16806. this.matrixWorld.copy( this.matrix );
  16807. }
  16808. this.matrixWorldNeedsUpdate = false;
  16809. force = true;
  16810. }
  16811. // update children
  16812. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16813. this.children[ i ].updateMatrixWorld( force );
  16814. }
  16815. };
  16816. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16817. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16818. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16819. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16820. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16821. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16822. /**
  16823. * @author zz85 / http://www.lab4games.net/zz85/blog
  16824. * Creates free form 2d path using series of points, lines or curves.
  16825. *
  16826. **/
  16827. THREE.Path = function ( points ) {
  16828. THREE.CurvePath.call(this);
  16829. this.actions = [];
  16830. if ( points ) {
  16831. this.fromPoints( points );
  16832. }
  16833. };
  16834. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16835. THREE.PathActions = {
  16836. MOVE_TO: 'moveTo',
  16837. LINE_TO: 'lineTo',
  16838. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16839. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16840. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16841. ARC: 'arc', // Circle
  16842. ELLIPSE: 'ellipse'
  16843. };
  16844. // TODO Clean up PATH API
  16845. // Create path using straight lines to connect all points
  16846. // - vectors: array of Vector2
  16847. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16848. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16849. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16850. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16851. };
  16852. };
  16853. // startPath() endPath()?
  16854. THREE.Path.prototype.moveTo = function ( x, y ) {
  16855. var args = Array.prototype.slice.call( arguments );
  16856. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16857. };
  16858. THREE.Path.prototype.lineTo = function ( x, y ) {
  16859. var args = Array.prototype.slice.call( arguments );
  16860. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16861. var x0 = lastargs[ lastargs.length - 2 ];
  16862. var y0 = lastargs[ lastargs.length - 1 ];
  16863. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16864. this.curves.push( curve );
  16865. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16866. };
  16867. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16868. var args = Array.prototype.slice.call( arguments );
  16869. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16870. var x0 = lastargs[ lastargs.length - 2 ];
  16871. var y0 = lastargs[ lastargs.length - 1 ];
  16872. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16873. new THREE.Vector2( aCPx, aCPy ),
  16874. new THREE.Vector2( aX, aY ) );
  16875. this.curves.push( curve );
  16876. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16877. };
  16878. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16879. aCP2x, aCP2y,
  16880. aX, aY ) {
  16881. var args = Array.prototype.slice.call( arguments );
  16882. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16883. var x0 = lastargs[ lastargs.length - 2 ];
  16884. var y0 = lastargs[ lastargs.length - 1 ];
  16885. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16886. new THREE.Vector2( aCP1x, aCP1y ),
  16887. new THREE.Vector2( aCP2x, aCP2y ),
  16888. new THREE.Vector2( aX, aY ) );
  16889. this.curves.push( curve );
  16890. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16891. };
  16892. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16893. var args = Array.prototype.slice.call( arguments );
  16894. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16895. var x0 = lastargs[ lastargs.length - 2 ];
  16896. var y0 = lastargs[ lastargs.length - 1 ];
  16897. //---
  16898. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16899. Array.prototype.push.apply( npts, pts );
  16900. var curve = new THREE.SplineCurve( npts );
  16901. this.curves.push( curve );
  16902. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16903. };
  16904. // FUTURE: Change the API or follow canvas API?
  16905. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16906. aStartAngle, aEndAngle, aClockwise ) {
  16907. var lastargs = this.actions[ this.actions.length - 1].args;
  16908. var x0 = lastargs[ lastargs.length - 2 ];
  16909. var y0 = lastargs[ lastargs.length - 1 ];
  16910. this.absarc(aX + x0, aY + y0, aRadius,
  16911. aStartAngle, aEndAngle, aClockwise );
  16912. };
  16913. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16914. aStartAngle, aEndAngle, aClockwise ) {
  16915. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16916. };
  16917. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16918. aStartAngle, aEndAngle, aClockwise ) {
  16919. var lastargs = this.actions[ this.actions.length - 1].args;
  16920. var x0 = lastargs[ lastargs.length - 2 ];
  16921. var y0 = lastargs[ lastargs.length - 1 ];
  16922. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16923. aStartAngle, aEndAngle, aClockwise );
  16924. };
  16925. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16926. aStartAngle, aEndAngle, aClockwise ) {
  16927. var args = Array.prototype.slice.call( arguments );
  16928. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16929. aStartAngle, aEndAngle, aClockwise );
  16930. this.curves.push( curve );
  16931. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16932. args.push(lastPoint.x);
  16933. args.push(lastPoint.y);
  16934. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16935. };
  16936. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16937. if ( ! divisions ) divisions = 40;
  16938. var points = [];
  16939. for ( var i = 0; i < divisions; i ++ ) {
  16940. points.push( this.getPoint( i / divisions ) );
  16941. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16942. }
  16943. // if ( closedPath ) {
  16944. //
  16945. // points.push( points[ 0 ] );
  16946. //
  16947. // }
  16948. return points;
  16949. };
  16950. /* Return an array of vectors based on contour of the path */
  16951. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16952. if (this.useSpacedPoints) {
  16953. console.log('tata');
  16954. return this.getSpacedPoints( divisions, closedPath );
  16955. }
  16956. divisions = divisions || 12;
  16957. var points = [];
  16958. var i, il, item, action, args;
  16959. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16960. laste, j,
  16961. t, tx, ty;
  16962. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16963. item = this.actions[ i ];
  16964. action = item.action;
  16965. args = item.args;
  16966. switch( action ) {
  16967. case THREE.PathActions.MOVE_TO:
  16968. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16969. break;
  16970. case THREE.PathActions.LINE_TO:
  16971. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16972. break;
  16973. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16974. cpx = args[ 2 ];
  16975. cpy = args[ 3 ];
  16976. cpx1 = args[ 0 ];
  16977. cpy1 = args[ 1 ];
  16978. if ( points.length > 0 ) {
  16979. laste = points[ points.length - 1 ];
  16980. cpx0 = laste.x;
  16981. cpy0 = laste.y;
  16982. } else {
  16983. laste = this.actions[ i - 1 ].args;
  16984. cpx0 = laste[ laste.length - 2 ];
  16985. cpy0 = laste[ laste.length - 1 ];
  16986. }
  16987. for ( j = 1; j <= divisions; j ++ ) {
  16988. t = j / divisions;
  16989. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16990. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16991. points.push( new THREE.Vector2( tx, ty ) );
  16992. }
  16993. break;
  16994. case THREE.PathActions.BEZIER_CURVE_TO:
  16995. cpx = args[ 4 ];
  16996. cpy = args[ 5 ];
  16997. cpx1 = args[ 0 ];
  16998. cpy1 = args[ 1 ];
  16999. cpx2 = args[ 2 ];
  17000. cpy2 = args[ 3 ];
  17001. if ( points.length > 0 ) {
  17002. laste = points[ points.length - 1 ];
  17003. cpx0 = laste.x;
  17004. cpy0 = laste.y;
  17005. } else {
  17006. laste = this.actions[ i - 1 ].args;
  17007. cpx0 = laste[ laste.length - 2 ];
  17008. cpy0 = laste[ laste.length - 1 ];
  17009. }
  17010. for ( j = 1; j <= divisions; j ++ ) {
  17011. t = j / divisions;
  17012. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17013. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17014. points.push( new THREE.Vector2( tx, ty ) );
  17015. }
  17016. break;
  17017. case THREE.PathActions.CSPLINE_THRU:
  17018. laste = this.actions[ i - 1 ].args;
  17019. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17020. var spts = [ last ];
  17021. var n = divisions * args[ 0 ].length;
  17022. spts = spts.concat( args[ 0 ] );
  17023. var spline = new THREE.SplineCurve( spts );
  17024. for ( j = 1; j <= n; j ++ ) {
  17025. points.push( spline.getPointAt( j / n ) ) ;
  17026. }
  17027. break;
  17028. case THREE.PathActions.ARC:
  17029. var aX = args[ 0 ], aY = args[ 1 ],
  17030. aRadius = args[ 2 ],
  17031. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17032. aClockwise = !!args[ 5 ];
  17033. var deltaAngle = aEndAngle - aStartAngle;
  17034. var angle;
  17035. var tdivisions = divisions * 2;
  17036. for ( j = 1; j <= tdivisions; j ++ ) {
  17037. t = j / tdivisions;
  17038. if ( ! aClockwise ) {
  17039. t = 1 - t;
  17040. }
  17041. angle = aStartAngle + t * deltaAngle;
  17042. tx = aX + aRadius * Math.cos( angle );
  17043. ty = aY + aRadius * Math.sin( angle );
  17044. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17045. points.push( new THREE.Vector2( tx, ty ) );
  17046. }
  17047. //console.log(points);
  17048. break;
  17049. case THREE.PathActions.ELLIPSE:
  17050. var aX = args[ 0 ], aY = args[ 1 ],
  17051. xRadius = args[ 2 ],
  17052. yRadius = args[ 3 ],
  17053. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17054. aClockwise = !!args[ 6 ];
  17055. var deltaAngle = aEndAngle - aStartAngle;
  17056. var angle;
  17057. var tdivisions = divisions * 2;
  17058. for ( j = 1; j <= tdivisions; j ++ ) {
  17059. t = j / tdivisions;
  17060. if ( ! aClockwise ) {
  17061. t = 1 - t;
  17062. }
  17063. angle = aStartAngle + t * deltaAngle;
  17064. tx = aX + xRadius * Math.cos( angle );
  17065. ty = aY + yRadius * Math.sin( angle );
  17066. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17067. points.push( new THREE.Vector2( tx, ty ) );
  17068. }
  17069. //console.log(points);
  17070. break;
  17071. } // end switch
  17072. }
  17073. // Normalize to remove the closing point by default.
  17074. var lastPoint = points[ points.length - 1];
  17075. var EPSILON = 0.0000000001;
  17076. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17077. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17078. points.splice( points.length - 1, 1);
  17079. if ( closedPath ) {
  17080. points.push( points[ 0 ] );
  17081. }
  17082. return points;
  17083. };
  17084. // Breaks path into shapes
  17085. THREE.Path.prototype.toShapes = function() {
  17086. var i, il, item, action, args;
  17087. var subPaths = [], lastPath = new THREE.Path();
  17088. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17089. item = this.actions[ i ];
  17090. args = item.args;
  17091. action = item.action;
  17092. if ( action == THREE.PathActions.MOVE_TO ) {
  17093. if ( lastPath.actions.length != 0 ) {
  17094. subPaths.push( lastPath );
  17095. lastPath = new THREE.Path();
  17096. }
  17097. }
  17098. lastPath[ action ].apply( lastPath, args );
  17099. }
  17100. if ( lastPath.actions.length != 0 ) {
  17101. subPaths.push( lastPath );
  17102. }
  17103. // console.log(subPaths);
  17104. if ( subPaths.length == 0 ) return [];
  17105. var tmpPath, tmpShape, shapes = [];
  17106. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17107. // console.log("Holes first", holesFirst);
  17108. if ( subPaths.length == 1) {
  17109. tmpPath = subPaths[0];
  17110. tmpShape = new THREE.Shape();
  17111. tmpShape.actions = tmpPath.actions;
  17112. tmpShape.curves = tmpPath.curves;
  17113. shapes.push( tmpShape );
  17114. return shapes;
  17115. };
  17116. if ( holesFirst ) {
  17117. tmpShape = new THREE.Shape();
  17118. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17119. tmpPath = subPaths[ i ];
  17120. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17121. tmpShape.actions = tmpPath.actions;
  17122. tmpShape.curves = tmpPath.curves;
  17123. shapes.push( tmpShape );
  17124. tmpShape = new THREE.Shape();
  17125. //console.log('cw', i);
  17126. } else {
  17127. tmpShape.holes.push( tmpPath );
  17128. //console.log('ccw', i);
  17129. }
  17130. }
  17131. } else {
  17132. // Shapes first
  17133. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17134. tmpPath = subPaths[ i ];
  17135. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17136. if ( tmpShape ) shapes.push( tmpShape );
  17137. tmpShape = new THREE.Shape();
  17138. tmpShape.actions = tmpPath.actions;
  17139. tmpShape.curves = tmpPath.curves;
  17140. } else {
  17141. tmpShape.holes.push( tmpPath );
  17142. }
  17143. }
  17144. shapes.push( tmpShape );
  17145. }
  17146. //console.log("shape", shapes);
  17147. return shapes;
  17148. };
  17149. /**
  17150. * @author zz85 / http://www.lab4games.net/zz85/blog
  17151. * Defines a 2d shape plane using paths.
  17152. **/
  17153. // STEP 1 Create a path.
  17154. // STEP 2 Turn path into shape.
  17155. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17156. // STEP 3a - Extract points from each shape, turn to vertices
  17157. // STEP 3b - Triangulate each shape, add faces.
  17158. THREE.Shape = function () {
  17159. THREE.Path.apply( this, arguments );
  17160. this.holes = [];
  17161. };
  17162. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17163. // Convenience method to return ExtrudeGeometry
  17164. THREE.Shape.prototype.extrude = function ( options ) {
  17165. var extruded = new THREE.ExtrudeGeometry( this, options );
  17166. return extruded;
  17167. };
  17168. // Convenience method to return ShapeGeometry
  17169. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17170. var geometry = new THREE.ShapeGeometry( this, options );
  17171. return geometry;
  17172. };
  17173. // Get points of holes
  17174. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17175. var i, il = this.holes.length, holesPts = [];
  17176. for ( i = 0; i < il; i ++ ) {
  17177. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17178. }
  17179. return holesPts;
  17180. };
  17181. // Get points of holes (spaced by regular distance)
  17182. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17183. var i, il = this.holes.length, holesPts = [];
  17184. for ( i = 0; i < il; i ++ ) {
  17185. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17186. }
  17187. return holesPts;
  17188. };
  17189. // Get points of shape and holes (keypoints based on segments parameter)
  17190. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17191. return {
  17192. shape: this.getTransformedPoints( divisions ),
  17193. holes: this.getPointsHoles( divisions )
  17194. };
  17195. };
  17196. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17197. if (this.useSpacedPoints) {
  17198. return this.extractAllSpacedPoints(divisions);
  17199. }
  17200. return this.extractAllPoints(divisions);
  17201. };
  17202. //
  17203. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17204. //
  17205. // return {
  17206. //
  17207. // shape: this.transform( bend, divisions ),
  17208. // holes: this.getPointsHoles( divisions, bend )
  17209. //
  17210. // };
  17211. //
  17212. // };
  17213. // Get points of shape and holes (spaced by regular distance)
  17214. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17215. return {
  17216. shape: this.getTransformedSpacedPoints( divisions ),
  17217. holes: this.getSpacedPointsHoles( divisions )
  17218. };
  17219. };
  17220. /**************************************************************
  17221. * Utils
  17222. **************************************************************/
  17223. THREE.Shape.Utils = {
  17224. /*
  17225. contour - array of vector2 for contour
  17226. holes - array of array of vector2
  17227. */
  17228. removeHoles: function ( contour, holes ) {
  17229. var shape = contour.concat(); // work on this shape
  17230. var allpoints = shape.concat();
  17231. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17232. var prevShapeVert, nextShapeVert,
  17233. prevHoleVert, nextHoleVert,
  17234. holeIndex, shapeIndex,
  17235. shapeId, shapeGroup,
  17236. h, h2,
  17237. hole, shortest, d,
  17238. p, pts1, pts2,
  17239. tmpShape1, tmpShape2,
  17240. tmpHole1, tmpHole2,
  17241. verts = [];
  17242. for ( h = 0; h < holes.length; h ++ ) {
  17243. hole = holes[ h ];
  17244. /*
  17245. shapeholes[ h ].concat(); // preserves original
  17246. holes.push( hole );
  17247. */
  17248. Array.prototype.push.apply( allpoints, hole );
  17249. shortest = Number.POSITIVE_INFINITY;
  17250. // Find the shortest pair of pts between shape and hole
  17251. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17252. // Using distanceToSquared() intead of distanceTo() should speed a little
  17253. // since running square roots operations are reduced.
  17254. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17255. pts1 = hole[ h2 ];
  17256. var dist = [];
  17257. for ( p = 0; p < shape.length; p++ ) {
  17258. pts2 = shape[ p ];
  17259. d = pts1.distanceToSquared( pts2 );
  17260. dist.push( d );
  17261. if ( d < shortest ) {
  17262. shortest = d;
  17263. holeIndex = h2;
  17264. shapeIndex = p;
  17265. }
  17266. }
  17267. }
  17268. //console.log("shortest", shortest, dist);
  17269. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17270. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17271. var areaapts = [
  17272. hole[ holeIndex ],
  17273. shape[ shapeIndex ],
  17274. shape[ prevShapeVert ]
  17275. ];
  17276. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17277. var areabpts = [
  17278. hole[ holeIndex ],
  17279. hole[ prevHoleVert ],
  17280. shape[ shapeIndex ]
  17281. ];
  17282. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17283. var shapeOffset = 1;
  17284. var holeOffset = -1;
  17285. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17286. shapeIndex += shapeOffset;
  17287. holeIndex += holeOffset;
  17288. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17289. shapeIndex %= shape.length;
  17290. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17291. holeIndex %= hole.length;
  17292. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17293. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17294. areaapts = [
  17295. hole[ holeIndex ],
  17296. shape[ shapeIndex ],
  17297. shape[ prevShapeVert ]
  17298. ];
  17299. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17300. areabpts = [
  17301. hole[ holeIndex ],
  17302. hole[ prevHoleVert ],
  17303. shape[ shapeIndex ]
  17304. ];
  17305. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17306. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17307. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17308. // In case areas are not correct.
  17309. //console.log("USE THIS");
  17310. shapeIndex = oldShapeIndex;
  17311. holeIndex = oldHoleIndex ;
  17312. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17313. shapeIndex %= shape.length;
  17314. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17315. holeIndex %= hole.length;
  17316. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17317. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17318. } else {
  17319. //console.log("USE THAT ")
  17320. }
  17321. tmpShape1 = shape.slice( 0, shapeIndex );
  17322. tmpShape2 = shape.slice( shapeIndex );
  17323. tmpHole1 = hole.slice( holeIndex );
  17324. tmpHole2 = hole.slice( 0, holeIndex );
  17325. // Should check orders here again?
  17326. var trianglea = [
  17327. hole[ holeIndex ],
  17328. shape[ shapeIndex ],
  17329. shape[ prevShapeVert ]
  17330. ];
  17331. var triangleb = [
  17332. hole[ holeIndex ] ,
  17333. hole[ prevHoleVert ],
  17334. shape[ shapeIndex ]
  17335. ];
  17336. verts.push( trianglea );
  17337. verts.push( triangleb );
  17338. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17339. }
  17340. return {
  17341. shape:shape, /* shape with no holes */
  17342. isolatedPts: verts, /* isolated faces */
  17343. allpoints: allpoints
  17344. }
  17345. },
  17346. triangulateShape: function ( contour, holes ) {
  17347. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17348. var shape = shapeWithoutHoles.shape,
  17349. allpoints = shapeWithoutHoles.allpoints,
  17350. isolatedPts = shapeWithoutHoles.isolatedPts;
  17351. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17352. // 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.
  17353. //console.log( "triangles",triangles, triangles.length );
  17354. //console.log( "allpoints",allpoints, allpoints.length );
  17355. var i, il, f, face,
  17356. key, index,
  17357. allPointsMap = {},
  17358. isolatedPointsMap = {};
  17359. // prepare all points map
  17360. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17361. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17362. if ( allPointsMap[ key ] !== undefined ) {
  17363. console.log( "Duplicate point", key );
  17364. }
  17365. allPointsMap[ key ] = i;
  17366. }
  17367. // check all face vertices against all points map
  17368. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17369. face = triangles[ i ];
  17370. for ( f = 0; f < 3; f ++ ) {
  17371. key = face[ f ].x + ":" + face[ f ].y;
  17372. index = allPointsMap[ key ];
  17373. if ( index !== undefined ) {
  17374. face[ f ] = index;
  17375. }
  17376. }
  17377. }
  17378. // check isolated points vertices against all points map
  17379. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17380. face = isolatedPts[ i ];
  17381. for ( f = 0; f < 3; f ++ ) {
  17382. key = face[ f ].x + ":" + face[ f ].y;
  17383. index = allPointsMap[ key ];
  17384. if ( index !== undefined ) {
  17385. face[ f ] = index;
  17386. }
  17387. }
  17388. }
  17389. return triangles.concat( isolatedPts );
  17390. }, // end triangulate shapes
  17391. /*
  17392. triangulate2 : function( pts, holes ) {
  17393. // For use with Poly2Tri.js
  17394. var allpts = pts.concat();
  17395. var shape = [];
  17396. for (var p in pts) {
  17397. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17398. }
  17399. var swctx = new js.poly2tri.SweepContext(shape);
  17400. for (var h in holes) {
  17401. var aHole = holes[h];
  17402. var newHole = []
  17403. for (i in aHole) {
  17404. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17405. allpts.push(aHole[i]);
  17406. }
  17407. swctx.AddHole(newHole);
  17408. }
  17409. var find;
  17410. var findIndexForPt = function (pt) {
  17411. find = new THREE.Vector2(pt.x, pt.y);
  17412. var p;
  17413. for (p=0, pl = allpts.length; p<pl; p++) {
  17414. if (allpts[p].equals(find)) return p;
  17415. }
  17416. return -1;
  17417. };
  17418. // triangulate
  17419. js.poly2tri.sweep.Triangulate(swctx);
  17420. var triangles = swctx.GetTriangles();
  17421. var tr ;
  17422. var facesPts = [];
  17423. for (var t in triangles) {
  17424. tr = triangles[t];
  17425. facesPts.push([
  17426. findIndexForPt(tr.GetPoint(0)),
  17427. findIndexForPt(tr.GetPoint(1)),
  17428. findIndexForPt(tr.GetPoint(2))
  17429. ]);
  17430. }
  17431. // console.log(facesPts);
  17432. // console.log("triangles", triangles.length, triangles);
  17433. // Returns array of faces with 3 element each
  17434. return facesPts;
  17435. },
  17436. */
  17437. isClockWise: function ( pts ) {
  17438. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17439. },
  17440. // Bezier Curves formulas obtained from
  17441. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17442. // Quad Bezier Functions
  17443. b2p0: function ( t, p ) {
  17444. var k = 1 - t;
  17445. return k * k * p;
  17446. },
  17447. b2p1: function ( t, p ) {
  17448. return 2 * ( 1 - t ) * t * p;
  17449. },
  17450. b2p2: function ( t, p ) {
  17451. return t * t * p;
  17452. },
  17453. b2: function ( t, p0, p1, p2 ) {
  17454. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17455. },
  17456. // Cubic Bezier Functions
  17457. b3p0: function ( t, p ) {
  17458. var k = 1 - t;
  17459. return k * k * k * p;
  17460. },
  17461. b3p1: function ( t, p ) {
  17462. var k = 1 - t;
  17463. return 3 * k * k * t * p;
  17464. },
  17465. b3p2: function ( t, p ) {
  17466. var k = 1 - t;
  17467. return 3 * k * t * t * p;
  17468. },
  17469. b3p3: function ( t, p ) {
  17470. return t * t * t * p;
  17471. },
  17472. b3: function ( t, p0, p1, p2, p3 ) {
  17473. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17474. }
  17475. };
  17476. /**
  17477. * @author mikael emtinger / http://gomo.se/
  17478. */
  17479. THREE.AnimationHandler = (function() {
  17480. var playing = [];
  17481. var library = {};
  17482. var that = {};
  17483. //--- update ---
  17484. that.update = function( deltaTimeMS ) {
  17485. for( var i = 0; i < playing.length; i ++ )
  17486. playing[ i ].update( deltaTimeMS );
  17487. };
  17488. //--- add ---
  17489. that.addToUpdate = function( animation ) {
  17490. if ( playing.indexOf( animation ) === -1 )
  17491. playing.push( animation );
  17492. };
  17493. //--- remove ---
  17494. that.removeFromUpdate = function( animation ) {
  17495. var index = playing.indexOf( animation );
  17496. if( index !== -1 )
  17497. playing.splice( index, 1 );
  17498. };
  17499. //--- add ---
  17500. that.add = function( data ) {
  17501. if ( library[ data.name ] !== undefined )
  17502. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17503. library[ data.name ] = data;
  17504. initData( data );
  17505. };
  17506. //--- get ---
  17507. that.get = function( name ) {
  17508. if ( typeof name === "string" ) {
  17509. if ( library[ name ] ) {
  17510. return library[ name ];
  17511. } else {
  17512. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17513. return null;
  17514. }
  17515. } else {
  17516. // todo: add simple tween library
  17517. }
  17518. };
  17519. //--- parse ---
  17520. that.parse = function( root ) {
  17521. // setup hierarchy
  17522. var hierarchy = [];
  17523. if ( root instanceof THREE.SkinnedMesh ) {
  17524. for( var b = 0; b < root.bones.length; b++ ) {
  17525. hierarchy.push( root.bones[ b ] );
  17526. }
  17527. } else {
  17528. parseRecurseHierarchy( root, hierarchy );
  17529. }
  17530. return hierarchy;
  17531. };
  17532. var parseRecurseHierarchy = function( root, hierarchy ) {
  17533. hierarchy.push( root );
  17534. for( var c = 0; c < root.children.length; c++ )
  17535. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17536. }
  17537. //--- init data ---
  17538. var initData = function( data ) {
  17539. if( data.initialized === true )
  17540. return;
  17541. // loop through all keys
  17542. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17543. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17544. // remove minus times
  17545. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17546. data.hierarchy[ h ].keys[ k ].time = 0;
  17547. // create quaternions
  17548. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17549. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17550. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17551. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17552. }
  17553. }
  17554. // prepare morph target keys
  17555. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17556. // get all used
  17557. var usedMorphTargets = {};
  17558. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17559. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17560. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17561. usedMorphTargets[ morphTargetName ] = -1;
  17562. }
  17563. }
  17564. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17565. // set all used on all frames
  17566. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17567. var influences = {};
  17568. for ( var morphTargetName in usedMorphTargets ) {
  17569. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17570. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17571. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17572. break;
  17573. }
  17574. }
  17575. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17576. influences[ morphTargetName ] = 0;
  17577. }
  17578. }
  17579. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17580. }
  17581. }
  17582. // remove all keys that are on the same time
  17583. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17584. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17585. data.hierarchy[ h ].keys.splice( k, 1 );
  17586. k --;
  17587. }
  17588. }
  17589. // set index
  17590. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17591. data.hierarchy[ h ].keys[ k ].index = k;
  17592. }
  17593. }
  17594. // JIT
  17595. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17596. data.JIT = {};
  17597. data.JIT.hierarchy = [];
  17598. for( var h = 0; h < data.hierarchy.length; h ++ )
  17599. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17600. // done
  17601. data.initialized = true;
  17602. };
  17603. // interpolation types
  17604. that.LINEAR = 0;
  17605. that.CATMULLROM = 1;
  17606. that.CATMULLROM_FORWARD = 2;
  17607. return that;
  17608. }());
  17609. /**
  17610. * @author mikael emtinger / http://gomo.se/
  17611. * @author mrdoob / http://mrdoob.com/
  17612. * @author alteredq / http://alteredqualia.com/
  17613. */
  17614. THREE.Animation = function ( root, name, interpolationType ) {
  17615. this.root = root;
  17616. this.data = THREE.AnimationHandler.get( name );
  17617. this.hierarchy = THREE.AnimationHandler.parse( root );
  17618. this.currentTime = 0;
  17619. this.timeScale = 1;
  17620. this.isPlaying = false;
  17621. this.isPaused = true;
  17622. this.loop = true;
  17623. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17624. this.points = [];
  17625. this.target = new THREE.Vector3();
  17626. };
  17627. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17628. if ( this.isPlaying === false ) {
  17629. this.isPlaying = true;
  17630. this.loop = loop !== undefined ? loop : true;
  17631. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17632. // reset key cache
  17633. var h, hl = this.hierarchy.length,
  17634. object;
  17635. for ( h = 0; h < hl; h ++ ) {
  17636. object = this.hierarchy[ h ];
  17637. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17638. object.useQuaternion = true;
  17639. }
  17640. object.matrixAutoUpdate = true;
  17641. if ( object.animationCache === undefined ) {
  17642. object.animationCache = {};
  17643. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17644. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17645. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17646. }
  17647. var prevKey = object.animationCache.prevKey;
  17648. var nextKey = object.animationCache.nextKey;
  17649. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17650. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17651. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17652. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17653. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17654. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17655. }
  17656. this.update( 0 );
  17657. }
  17658. this.isPaused = false;
  17659. THREE.AnimationHandler.addToUpdate( this );
  17660. };
  17661. THREE.Animation.prototype.pause = function() {
  17662. if ( this.isPaused === true ) {
  17663. THREE.AnimationHandler.addToUpdate( this );
  17664. } else {
  17665. THREE.AnimationHandler.removeFromUpdate( this );
  17666. }
  17667. this.isPaused = !this.isPaused;
  17668. };
  17669. THREE.Animation.prototype.stop = function() {
  17670. this.isPlaying = false;
  17671. this.isPaused = false;
  17672. THREE.AnimationHandler.removeFromUpdate( this );
  17673. };
  17674. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17675. // early out
  17676. if ( this.isPlaying === false ) return;
  17677. // vars
  17678. var types = [ "pos", "rot", "scl" ];
  17679. var type;
  17680. var scale;
  17681. var vector;
  17682. var prevXYZ, nextXYZ;
  17683. var prevKey, nextKey;
  17684. var object;
  17685. var animationCache;
  17686. var frame;
  17687. var JIThierarchy = this.data.JIT.hierarchy;
  17688. var currentTime, unloopedCurrentTime;
  17689. var currentPoint, forwardPoint, angle;
  17690. this.currentTime += deltaTimeMS * this.timeScale;
  17691. unloopedCurrentTime = this.currentTime;
  17692. currentTime = this.currentTime = this.currentTime % this.data.length;
  17693. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17694. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17695. object = this.hierarchy[ h ];
  17696. animationCache = object.animationCache;
  17697. // loop through pos/rot/scl
  17698. for ( var t = 0; t < 3; t ++ ) {
  17699. // get keys
  17700. type = types[ t ];
  17701. prevKey = animationCache.prevKey[ type ];
  17702. nextKey = animationCache.nextKey[ type ];
  17703. // switch keys?
  17704. if ( nextKey.time <= unloopedCurrentTime ) {
  17705. // did we loop?
  17706. if ( currentTime < unloopedCurrentTime ) {
  17707. if ( this.loop ) {
  17708. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17709. nextKey = this.getNextKeyWith( type, h, 1 );
  17710. while( nextKey.time < currentTime ) {
  17711. prevKey = nextKey;
  17712. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17713. }
  17714. } else {
  17715. this.stop();
  17716. return;
  17717. }
  17718. } else {
  17719. do {
  17720. prevKey = nextKey;
  17721. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17722. } while( nextKey.time < currentTime )
  17723. }
  17724. animationCache.prevKey[ type ] = prevKey;
  17725. animationCache.nextKey[ type ] = nextKey;
  17726. }
  17727. object.matrixAutoUpdate = true;
  17728. object.matrixWorldNeedsUpdate = true;
  17729. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17730. prevXYZ = prevKey[ type ];
  17731. nextXYZ = nextKey[ type ];
  17732. // check scale error
  17733. if ( scale < 0 || scale > 1 ) {
  17734. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17735. scale = scale < 0 ? 0 : 1;
  17736. }
  17737. // interpolate
  17738. if ( type === "pos" ) {
  17739. vector = object.position;
  17740. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17741. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17742. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17743. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17744. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17745. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17746. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17747. this.points[ 1 ] = prevXYZ;
  17748. this.points[ 2 ] = nextXYZ;
  17749. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17750. scale = scale * 0.33 + 0.33;
  17751. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17752. vector.x = currentPoint[ 0 ];
  17753. vector.y = currentPoint[ 1 ];
  17754. vector.z = currentPoint[ 2 ];
  17755. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17756. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17757. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17758. this.target.sub( vector );
  17759. this.target.y = 0;
  17760. this.target.normalize();
  17761. angle = Math.atan2( this.target.x, this.target.z );
  17762. object.rotation.set( 0, angle, 0 );
  17763. }
  17764. }
  17765. } else if ( type === "rot" ) {
  17766. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17767. } else if ( type === "scl" ) {
  17768. vector = object.scale;
  17769. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17770. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17771. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17772. }
  17773. }
  17774. }
  17775. };
  17776. // Catmull-Rom spline
  17777. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17778. var c = [], v3 = [],
  17779. point, intPoint, weight, w2, w3,
  17780. pa, pb, pc, pd;
  17781. point = ( points.length - 1 ) * scale;
  17782. intPoint = Math.floor( point );
  17783. weight = point - intPoint;
  17784. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17785. c[ 1 ] = intPoint;
  17786. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17787. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17788. pa = points[ c[ 0 ] ];
  17789. pb = points[ c[ 1 ] ];
  17790. pc = points[ c[ 2 ] ];
  17791. pd = points[ c[ 3 ] ];
  17792. w2 = weight * weight;
  17793. w3 = weight * w2;
  17794. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17795. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17796. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17797. return v3;
  17798. };
  17799. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17800. var v0 = ( p2 - p0 ) * 0.5,
  17801. v1 = ( p3 - p1 ) * 0.5;
  17802. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17803. };
  17804. // Get next key with
  17805. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17806. var keys = this.data.hierarchy[ h ].keys;
  17807. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17808. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17809. key = key < keys.length - 1 ? key : keys.length - 1;
  17810. } else {
  17811. key = key % keys.length;
  17812. }
  17813. for ( ; key < keys.length; key++ ) {
  17814. if ( keys[ key ][ type ] !== undefined ) {
  17815. return keys[ key ];
  17816. }
  17817. }
  17818. return this.data.hierarchy[ h ].keys[ 0 ];
  17819. };
  17820. // Get previous key with
  17821. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17822. var keys = this.data.hierarchy[ h ].keys;
  17823. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17824. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17825. key = key > 0 ? key : 0;
  17826. } else {
  17827. key = key >= 0 ? key : key + keys.length;
  17828. }
  17829. for ( ; key >= 0; key -- ) {
  17830. if ( keys[ key ][ type ] !== undefined ) {
  17831. return keys[ key ];
  17832. }
  17833. }
  17834. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17835. };
  17836. /**
  17837. * @author mikael emtinger / http://gomo.se/
  17838. * @author mrdoob / http://mrdoob.com/
  17839. * @author alteredq / http://alteredqualia.com/
  17840. * @author khang duong
  17841. * @author erik kitson
  17842. */
  17843. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17844. this.root = root;
  17845. this.data = THREE.AnimationHandler.get( data );
  17846. this.hierarchy = THREE.AnimationHandler.parse( root );
  17847. this.currentTime = 0;
  17848. this.timeScale = 0.001;
  17849. this.isPlaying = false;
  17850. this.isPaused = true;
  17851. this.loop = true;
  17852. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17853. // initialize to first keyframes
  17854. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17855. var keys = this.data.hierarchy[h].keys,
  17856. sids = this.data.hierarchy[h].sids,
  17857. obj = this.hierarchy[h];
  17858. if ( keys.length && sids ) {
  17859. for ( var s = 0; s < sids.length; s++ ) {
  17860. var sid = sids[ s ],
  17861. next = this.getNextKeyWith( sid, h, 0 );
  17862. if ( next ) {
  17863. next.apply( sid );
  17864. }
  17865. }
  17866. obj.matrixAutoUpdate = false;
  17867. this.data.hierarchy[h].node.updateMatrix();
  17868. obj.matrixWorldNeedsUpdate = true;
  17869. }
  17870. }
  17871. };
  17872. // Play
  17873. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17874. if( !this.isPlaying ) {
  17875. this.isPlaying = true;
  17876. this.loop = loop !== undefined ? loop : true;
  17877. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17878. this.startTimeMs = startTimeMS;
  17879. this.startTime = 10000000;
  17880. this.endTime = -this.startTime;
  17881. // reset key cache
  17882. var h, hl = this.hierarchy.length,
  17883. object,
  17884. node;
  17885. for ( h = 0; h < hl; h++ ) {
  17886. object = this.hierarchy[ h ];
  17887. node = this.data.hierarchy[ h ];
  17888. object.useQuaternion = true;
  17889. if ( node.animationCache === undefined ) {
  17890. node.animationCache = {};
  17891. node.animationCache.prevKey = null;
  17892. node.animationCache.nextKey = null;
  17893. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17894. }
  17895. var keys = this.data.hierarchy[h].keys;
  17896. if (keys.length) {
  17897. node.animationCache.prevKey = keys[ 0 ];
  17898. node.animationCache.nextKey = keys[ 1 ];
  17899. this.startTime = Math.min( keys[0].time, this.startTime );
  17900. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17901. }
  17902. }
  17903. this.update( 0 );
  17904. }
  17905. this.isPaused = false;
  17906. THREE.AnimationHandler.addToUpdate( this );
  17907. };
  17908. // Pause
  17909. THREE.KeyFrameAnimation.prototype.pause = function() {
  17910. if( this.isPaused ) {
  17911. THREE.AnimationHandler.addToUpdate( this );
  17912. } else {
  17913. THREE.AnimationHandler.removeFromUpdate( this );
  17914. }
  17915. this.isPaused = !this.isPaused;
  17916. };
  17917. // Stop
  17918. THREE.KeyFrameAnimation.prototype.stop = function() {
  17919. this.isPlaying = false;
  17920. this.isPaused = false;
  17921. THREE.AnimationHandler.removeFromUpdate( this );
  17922. // reset JIT matrix and remove cache
  17923. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17924. var obj = this.hierarchy[ h ];
  17925. var node = this.data.hierarchy[ h ];
  17926. if ( node.animationCache !== undefined ) {
  17927. var original = node.animationCache.originalMatrix;
  17928. if( obj instanceof THREE.Bone ) {
  17929. original.copy( obj.skinMatrix );
  17930. obj.skinMatrix = original;
  17931. } else {
  17932. original.copy( obj.matrix );
  17933. obj.matrix = original;
  17934. }
  17935. delete node.animationCache;
  17936. }
  17937. }
  17938. };
  17939. // Update
  17940. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17941. // early out
  17942. if( !this.isPlaying ) return;
  17943. // vars
  17944. var prevKey, nextKey;
  17945. var object;
  17946. var node;
  17947. var frame;
  17948. var JIThierarchy = this.data.JIT.hierarchy;
  17949. var currentTime, unloopedCurrentTime;
  17950. var looped;
  17951. // update
  17952. this.currentTime += deltaTimeMS * this.timeScale;
  17953. unloopedCurrentTime = this.currentTime;
  17954. currentTime = this.currentTime = this.currentTime % this.data.length;
  17955. // if looped around, the current time should be based on the startTime
  17956. if ( currentTime < this.startTimeMs ) {
  17957. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17958. }
  17959. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17960. looped = currentTime < unloopedCurrentTime;
  17961. if ( looped && !this.loop ) {
  17962. // Set the animation to the last keyframes and stop
  17963. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17964. var keys = this.data.hierarchy[h].keys,
  17965. sids = this.data.hierarchy[h].sids,
  17966. end = keys.length-1,
  17967. obj = this.hierarchy[h];
  17968. if ( keys.length ) {
  17969. for ( var s = 0; s < sids.length; s++ ) {
  17970. var sid = sids[ s ],
  17971. prev = this.getPrevKeyWith( sid, h, end );
  17972. if ( prev ) {
  17973. prev.apply( sid );
  17974. }
  17975. }
  17976. this.data.hierarchy[h].node.updateMatrix();
  17977. obj.matrixWorldNeedsUpdate = true;
  17978. }
  17979. }
  17980. this.stop();
  17981. return;
  17982. }
  17983. // check pre-infinity
  17984. if ( currentTime < this.startTime ) {
  17985. return;
  17986. }
  17987. // update
  17988. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17989. object = this.hierarchy[ h ];
  17990. node = this.data.hierarchy[ h ];
  17991. var keys = node.keys,
  17992. animationCache = node.animationCache;
  17993. // use JIT?
  17994. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17995. if( object instanceof THREE.Bone ) {
  17996. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17997. object.matrixWorldNeedsUpdate = false;
  17998. } else {
  17999. object.matrix = JIThierarchy[ h ][ frame ];
  18000. object.matrixWorldNeedsUpdate = true;
  18001. }
  18002. // use interpolation
  18003. } else if ( keys.length ) {
  18004. // make sure so original matrix and not JIT matrix is set
  18005. if ( this.JITCompile && animationCache ) {
  18006. if( object instanceof THREE.Bone ) {
  18007. object.skinMatrix = animationCache.originalMatrix;
  18008. } else {
  18009. object.matrix = animationCache.originalMatrix;
  18010. }
  18011. }
  18012. prevKey = animationCache.prevKey;
  18013. nextKey = animationCache.nextKey;
  18014. if ( prevKey && nextKey ) {
  18015. // switch keys?
  18016. if ( nextKey.time <= unloopedCurrentTime ) {
  18017. // did we loop?
  18018. if ( looped && this.loop ) {
  18019. prevKey = keys[ 0 ];
  18020. nextKey = keys[ 1 ];
  18021. while ( nextKey.time < currentTime ) {
  18022. prevKey = nextKey;
  18023. nextKey = keys[ prevKey.index + 1 ];
  18024. }
  18025. } else if ( !looped ) {
  18026. var lastIndex = keys.length - 1;
  18027. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18028. prevKey = nextKey;
  18029. nextKey = keys[ prevKey.index + 1 ];
  18030. }
  18031. }
  18032. animationCache.prevKey = prevKey;
  18033. animationCache.nextKey = nextKey;
  18034. }
  18035. if(nextKey.time >= currentTime)
  18036. prevKey.interpolate( nextKey, currentTime );
  18037. else
  18038. prevKey.interpolate( nextKey, nextKey.time);
  18039. }
  18040. this.data.hierarchy[h].node.updateMatrix();
  18041. object.matrixWorldNeedsUpdate = true;
  18042. }
  18043. }
  18044. // update JIT?
  18045. if ( this.JITCompile ) {
  18046. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18047. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18048. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18049. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18050. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18051. } else {
  18052. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18053. }
  18054. }
  18055. }
  18056. }
  18057. };
  18058. // Get next key with
  18059. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18060. var keys = this.data.hierarchy[ h ].keys;
  18061. key = key % keys.length;
  18062. for ( ; key < keys.length; key++ ) {
  18063. if ( keys[ key ].hasTarget( sid ) ) {
  18064. return keys[ key ];
  18065. }
  18066. }
  18067. return keys[ 0 ];
  18068. };
  18069. // Get previous key with
  18070. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18071. var keys = this.data.hierarchy[ h ].keys;
  18072. key = key >= 0 ? key : key + keys.length;
  18073. for ( ; key >= 0; key-- ) {
  18074. if ( keys[ key ].hasTarget( sid ) ) {
  18075. return keys[ key ];
  18076. }
  18077. }
  18078. return keys[ keys.length - 1 ];
  18079. };
  18080. /**
  18081. * Camera for rendering cube maps
  18082. * - renders scene into axis-aligned cube
  18083. *
  18084. * @author alteredq / http://alteredqualia.com/
  18085. */
  18086. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18087. THREE.Object3D.call( this );
  18088. var fov = 90, aspect = 1;
  18089. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18090. cameraPX.up.set( 0, -1, 0 );
  18091. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18092. this.add( cameraPX );
  18093. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18094. cameraNX.up.set( 0, -1, 0 );
  18095. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18096. this.add( cameraNX );
  18097. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18098. cameraPY.up.set( 0, 0, 1 );
  18099. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18100. this.add( cameraPY );
  18101. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18102. cameraNY.up.set( 0, 0, -1 );
  18103. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18104. this.add( cameraNY );
  18105. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18106. cameraPZ.up.set( 0, -1, 0 );
  18107. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18108. this.add( cameraPZ );
  18109. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18110. cameraNZ.up.set( 0, -1, 0 );
  18111. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18112. this.add( cameraNZ );
  18113. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18114. this.updateCubeMap = function ( renderer, scene ) {
  18115. var renderTarget = this.renderTarget;
  18116. var generateMipmaps = renderTarget.generateMipmaps;
  18117. renderTarget.generateMipmaps = false;
  18118. renderTarget.activeCubeFace = 0;
  18119. renderer.render( scene, cameraPX, renderTarget );
  18120. renderTarget.activeCubeFace = 1;
  18121. renderer.render( scene, cameraNX, renderTarget );
  18122. renderTarget.activeCubeFace = 2;
  18123. renderer.render( scene, cameraPY, renderTarget );
  18124. renderTarget.activeCubeFace = 3;
  18125. renderer.render( scene, cameraNY, renderTarget );
  18126. renderTarget.activeCubeFace = 4;
  18127. renderer.render( scene, cameraPZ, renderTarget );
  18128. renderTarget.generateMipmaps = generateMipmaps;
  18129. renderTarget.activeCubeFace = 5;
  18130. renderer.render( scene, cameraNZ, renderTarget );
  18131. };
  18132. };
  18133. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18134. /*
  18135. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18136. *
  18137. * A general perpose camera, for setting FOV, Lens Focal Length,
  18138. * and switching between perspective and orthographic views easily.
  18139. * Use this only if you do not wish to manage
  18140. * both a Orthographic and Perspective Camera
  18141. *
  18142. */
  18143. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18144. THREE.Camera.call( this );
  18145. this.fov = fov;
  18146. this.left = -width / 2;
  18147. this.right = width / 2
  18148. this.top = height / 2;
  18149. this.bottom = -height / 2;
  18150. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18151. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18152. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18153. this.zoom = 1;
  18154. this.toPerspective();
  18155. var aspect = width/height;
  18156. };
  18157. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18158. THREE.CombinedCamera.prototype.toPerspective = function () {
  18159. // Switches to the Perspective Camera
  18160. this.near = this.cameraP.near;
  18161. this.far = this.cameraP.far;
  18162. this.cameraP.fov = this.fov / this.zoom ;
  18163. this.cameraP.updateProjectionMatrix();
  18164. this.projectionMatrix = this.cameraP.projectionMatrix;
  18165. this.inPerspectiveMode = true;
  18166. this.inOrthographicMode = false;
  18167. };
  18168. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18169. // Switches to the Orthographic camera estimating viewport from Perspective
  18170. var fov = this.fov;
  18171. var aspect = this.cameraP.aspect;
  18172. var near = this.cameraP.near;
  18173. var far = this.cameraP.far;
  18174. // The size that we set is the mid plane of the viewing frustum
  18175. var hyperfocus = ( near + far ) / 2;
  18176. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18177. var planeHeight = 2 * halfHeight;
  18178. var planeWidth = planeHeight * aspect;
  18179. var halfWidth = planeWidth / 2;
  18180. halfHeight /= this.zoom;
  18181. halfWidth /= this.zoom;
  18182. this.cameraO.left = -halfWidth;
  18183. this.cameraO.right = halfWidth;
  18184. this.cameraO.top = halfHeight;
  18185. this.cameraO.bottom = -halfHeight;
  18186. // this.cameraO.left = -farHalfWidth;
  18187. // this.cameraO.right = farHalfWidth;
  18188. // this.cameraO.top = farHalfHeight;
  18189. // this.cameraO.bottom = -farHalfHeight;
  18190. // this.cameraO.left = this.left / this.zoom;
  18191. // this.cameraO.right = this.right / this.zoom;
  18192. // this.cameraO.top = this.top / this.zoom;
  18193. // this.cameraO.bottom = this.bottom / this.zoom;
  18194. this.cameraO.updateProjectionMatrix();
  18195. this.near = this.cameraO.near;
  18196. this.far = this.cameraO.far;
  18197. this.projectionMatrix = this.cameraO.projectionMatrix;
  18198. this.inPerspectiveMode = false;
  18199. this.inOrthographicMode = true;
  18200. };
  18201. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18202. this.cameraP.aspect = width / height;
  18203. this.left = -width / 2;
  18204. this.right = width / 2
  18205. this.top = height / 2;
  18206. this.bottom = -height / 2;
  18207. };
  18208. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18209. this.fov = fov;
  18210. if ( this.inPerspectiveMode ) {
  18211. this.toPerspective();
  18212. } else {
  18213. this.toOrthographic();
  18214. }
  18215. };
  18216. // For mantaining similar API with PerspectiveCamera
  18217. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18218. if ( this.inPerspectiveMode ) {
  18219. this.toPerspective();
  18220. } else {
  18221. this.toPerspective();
  18222. this.toOrthographic();
  18223. }
  18224. };
  18225. /*
  18226. * Uses Focal Length (in mm) to estimate and set FOV
  18227. * 35mm (fullframe) camera is used if frame size is not specified;
  18228. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18229. */
  18230. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18231. if ( frameHeight === undefined ) frameHeight = 24;
  18232. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18233. this.setFov( fov );
  18234. return fov;
  18235. };
  18236. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18237. this.zoom = zoom;
  18238. if ( this.inPerspectiveMode ) {
  18239. this.toPerspective();
  18240. } else {
  18241. this.toOrthographic();
  18242. }
  18243. };
  18244. THREE.CombinedCamera.prototype.toFrontView = function() {
  18245. this.rotation.x = 0;
  18246. this.rotation.y = 0;
  18247. this.rotation.z = 0;
  18248. // should we be modifing the matrix instead?
  18249. this.rotationAutoUpdate = false;
  18250. };
  18251. THREE.CombinedCamera.prototype.toBackView = function() {
  18252. this.rotation.x = 0;
  18253. this.rotation.y = Math.PI;
  18254. this.rotation.z = 0;
  18255. this.rotationAutoUpdate = false;
  18256. };
  18257. THREE.CombinedCamera.prototype.toLeftView = function() {
  18258. this.rotation.x = 0;
  18259. this.rotation.y = - Math.PI / 2;
  18260. this.rotation.z = 0;
  18261. this.rotationAutoUpdate = false;
  18262. };
  18263. THREE.CombinedCamera.prototype.toRightView = function() {
  18264. this.rotation.x = 0;
  18265. this.rotation.y = Math.PI / 2;
  18266. this.rotation.z = 0;
  18267. this.rotationAutoUpdate = false;
  18268. };
  18269. THREE.CombinedCamera.prototype.toTopView = function() {
  18270. this.rotation.x = - Math.PI / 2;
  18271. this.rotation.y = 0;
  18272. this.rotation.z = 0;
  18273. this.rotationAutoUpdate = false;
  18274. };
  18275. THREE.CombinedCamera.prototype.toBottomView = function() {
  18276. this.rotation.x = Math.PI / 2;
  18277. this.rotation.y = 0;
  18278. this.rotation.z = 0;
  18279. this.rotationAutoUpdate = false;
  18280. };
  18281. /**
  18282. * @author alteredq / http://alteredqualia.com/
  18283. *
  18284. * - 3d asterisk shape (for line pieces THREE.Line)
  18285. */
  18286. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18287. THREE.Geometry.call( this );
  18288. var sd = innerRadius;
  18289. var ed = outerRadius;
  18290. var sd2 = 0.707 * sd;
  18291. var ed2 = 0.707 * ed;
  18292. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18293. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18294. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18295. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18296. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18297. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18298. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18299. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18300. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18301. ];
  18302. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18303. var x = rays[ i ][ 0 ];
  18304. var y = rays[ i ][ 1 ];
  18305. var z = rays[ i ][ 2 ];
  18306. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18307. }
  18308. };
  18309. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18310. * @author hughes
  18311. */
  18312. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18313. THREE.Geometry.call( this );
  18314. radius = radius || 50;
  18315. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18316. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18317. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18318. var i, uvs = [],
  18319. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18320. this.vertices.push(center);
  18321. uvs.push( centerUV );
  18322. for ( i = 0; i <= segments; i ++ ) {
  18323. var vertex = new THREE.Vector3();
  18324. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18325. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18326. this.vertices.push( vertex );
  18327. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18328. }
  18329. var n = new THREE.Vector3( 0, 0, -1 );
  18330. for ( i = 1; i <= segments; i ++ ) {
  18331. var v1 = i;
  18332. var v2 = i + 1 ;
  18333. var v3 = 0;
  18334. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18335. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18336. }
  18337. this.computeCentroids();
  18338. this.computeFaceNormals();
  18339. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18340. };
  18341. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18342. /**
  18343. * @author mrdoob / http://mrdoob.com/
  18344. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18345. */
  18346. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18347. THREE.Geometry.call( this );
  18348. var scope = this;
  18349. this.width = width;
  18350. this.height = height;
  18351. this.depth = depth;
  18352. this.widthSegments = widthSegments || 1;
  18353. this.heightSegments = heightSegments || 1;
  18354. this.depthSegments = depthSegments || 1;
  18355. var width_half = this.width / 2;
  18356. var height_half = this.height / 2;
  18357. var depth_half = this.depth / 2;
  18358. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18359. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18360. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18361. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18362. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18363. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18364. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18365. var w, ix, iy,
  18366. gridX = scope.widthSegments,
  18367. gridY = scope.heightSegments,
  18368. width_half = width / 2,
  18369. height_half = height / 2,
  18370. offset = scope.vertices.length;
  18371. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18372. w = 'z';
  18373. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18374. w = 'y';
  18375. gridY = scope.depthSegments;
  18376. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18377. w = 'x';
  18378. gridX = scope.depthSegments;
  18379. }
  18380. var gridX1 = gridX + 1,
  18381. gridY1 = gridY + 1,
  18382. segment_width = width / gridX,
  18383. segment_height = height / gridY,
  18384. normal = new THREE.Vector3();
  18385. normal[ w ] = depth > 0 ? 1 : - 1;
  18386. for ( iy = 0; iy < gridY1; iy ++ ) {
  18387. for ( ix = 0; ix < gridX1; ix ++ ) {
  18388. var vector = new THREE.Vector3();
  18389. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18390. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18391. vector[ w ] = depth;
  18392. scope.vertices.push( vector );
  18393. }
  18394. }
  18395. for ( iy = 0; iy < gridY; iy++ ) {
  18396. for ( ix = 0; ix < gridX; ix++ ) {
  18397. var a = ix + gridX1 * iy;
  18398. var b = ix + gridX1 * ( iy + 1 );
  18399. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18400. var d = ( ix + 1 ) + gridX1 * iy;
  18401. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18402. face.normal.copy( normal );
  18403. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18404. face.materialIndex = materialIndex;
  18405. scope.faces.push( face );
  18406. scope.faceVertexUvs[ 0 ].push( [
  18407. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18408. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18409. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18410. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18411. ] );
  18412. }
  18413. }
  18414. }
  18415. this.computeCentroids();
  18416. this.mergeVertices();
  18417. };
  18418. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18419. /**
  18420. * @author mrdoob / http://mrdoob.com/
  18421. */
  18422. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18423. THREE.Geometry.call( this );
  18424. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18425. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18426. height = height !== undefined ? height : 100;
  18427. var heightHalf = height / 2;
  18428. var segmentsX = radiusSegments || 8;
  18429. var segmentsY = heightSegments || 1;
  18430. var x, y, vertices = [], uvs = [];
  18431. for ( y = 0; y <= segmentsY; y ++ ) {
  18432. var verticesRow = [];
  18433. var uvsRow = [];
  18434. var v = y / segmentsY;
  18435. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18436. for ( x = 0; x <= segmentsX; x ++ ) {
  18437. var u = x / segmentsX;
  18438. var vertex = new THREE.Vector3();
  18439. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18440. vertex.y = - v * height + heightHalf;
  18441. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18442. this.vertices.push( vertex );
  18443. verticesRow.push( this.vertices.length - 1 );
  18444. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18445. }
  18446. vertices.push( verticesRow );
  18447. uvs.push( uvsRow );
  18448. }
  18449. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18450. var na, nb;
  18451. for ( x = 0; x < segmentsX; x ++ ) {
  18452. if ( radiusTop !== 0 ) {
  18453. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18454. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18455. } else {
  18456. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18457. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18458. }
  18459. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18460. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18461. for ( y = 0; y < segmentsY; y ++ ) {
  18462. var v1 = vertices[ y ][ x ];
  18463. var v2 = vertices[ y + 1 ][ x ];
  18464. var v3 = vertices[ y + 1 ][ x + 1 ];
  18465. var v4 = vertices[ y ][ x + 1 ];
  18466. var n1 = na.clone();
  18467. var n2 = na.clone();
  18468. var n3 = nb.clone();
  18469. var n4 = nb.clone();
  18470. var uv1 = uvs[ y ][ x ].clone();
  18471. var uv2 = uvs[ y + 1 ][ x ].clone();
  18472. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18473. var uv4 = uvs[ y ][ x + 1 ].clone();
  18474. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18475. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18476. }
  18477. }
  18478. // top cap
  18479. if ( !openEnded && radiusTop > 0 ) {
  18480. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18481. for ( x = 0; x < segmentsX; x ++ ) {
  18482. var v1 = vertices[ 0 ][ x ];
  18483. var v2 = vertices[ 0 ][ x + 1 ];
  18484. var v3 = this.vertices.length - 1;
  18485. var n1 = new THREE.Vector3( 0, 1, 0 );
  18486. var n2 = new THREE.Vector3( 0, 1, 0 );
  18487. var n3 = new THREE.Vector3( 0, 1, 0 );
  18488. var uv1 = uvs[ 0 ][ x ].clone();
  18489. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18490. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18491. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18492. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18493. }
  18494. }
  18495. // bottom cap
  18496. if ( !openEnded && radiusBottom > 0 ) {
  18497. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18498. for ( x = 0; x < segmentsX; x ++ ) {
  18499. var v1 = vertices[ y ][ x + 1 ];
  18500. var v2 = vertices[ y ][ x ];
  18501. var v3 = this.vertices.length - 1;
  18502. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18503. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18504. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18505. var uv1 = uvs[ y ][ x + 1 ].clone();
  18506. var uv2 = uvs[ y ][ x ].clone();
  18507. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18508. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18509. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18510. }
  18511. }
  18512. this.computeCentroids();
  18513. this.computeFaceNormals();
  18514. }
  18515. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18516. /**
  18517. * @author zz85 / http://www.lab4games.net/zz85/blog
  18518. *
  18519. * Creates extruded geometry from a path shape.
  18520. *
  18521. * parameters = {
  18522. *
  18523. * size: <float>, // size of the text
  18524. * height: <float>, // thickness to extrude text
  18525. * curveSegments: <int>, // number of points on the curves
  18526. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18527. * amount: <int>, // Amount
  18528. *
  18529. * bevelEnabled: <bool>, // turn on bevel
  18530. * bevelThickness: <float>, // how deep into text bevel goes
  18531. * bevelSize: <float>, // how far from text outline is bevel
  18532. * bevelSegments: <int>, // number of bevel layers
  18533. *
  18534. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18535. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18536. *
  18537. * material: <int> // material index for front and back faces
  18538. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18539. * uvGenerator: <Object> // object that provides UV generator functions
  18540. *
  18541. * }
  18542. **/
  18543. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18544. if ( typeof( shapes ) === "undefined" ) {
  18545. shapes = [];
  18546. return;
  18547. }
  18548. THREE.Geometry.call( this );
  18549. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18550. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18551. this.addShapeList( shapes, options );
  18552. this.computeCentroids();
  18553. this.computeFaceNormals();
  18554. // can't really use automatic vertex normals
  18555. // as then front and back sides get smoothed too
  18556. // should do separate smoothing just for sides
  18557. //this.computeVertexNormals();
  18558. //console.log( "took", ( Date.now() - startTime ) );
  18559. };
  18560. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18561. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18562. var sl = shapes.length;
  18563. for ( var s = 0; s < sl; s ++ ) {
  18564. var shape = shapes[ s ];
  18565. this.addShape( shape, options );
  18566. }
  18567. };
  18568. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18569. var amount = options.amount !== undefined ? options.amount : 100;
  18570. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18571. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18572. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18573. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18574. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18575. var steps = options.steps !== undefined ? options.steps : 1;
  18576. var extrudePath = options.extrudePath;
  18577. var extrudePts, extrudeByPath = false;
  18578. var material = options.material;
  18579. var extrudeMaterial = options.extrudeMaterial;
  18580. // Use default WorldUVGenerator if no UV generators are specified.
  18581. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18582. var shapebb = this.shapebb;
  18583. //shapebb = shape.getBoundingBox();
  18584. var splineTube, binormal, normal, position2;
  18585. if ( extrudePath ) {
  18586. extrudePts = extrudePath.getSpacedPoints( steps );
  18587. extrudeByPath = true;
  18588. bevelEnabled = false; // bevels not supported for path extrusion
  18589. // SETUP TNB variables
  18590. // Reuse TNB from TubeGeomtry for now.
  18591. // TODO1 - have a .isClosed in spline?
  18592. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18593. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18594. binormal = new THREE.Vector3();
  18595. normal = new THREE.Vector3();
  18596. position2 = new THREE.Vector3();
  18597. }
  18598. // Safeguards if bevels are not enabled
  18599. if ( ! bevelEnabled ) {
  18600. bevelSegments = 0;
  18601. bevelThickness = 0;
  18602. bevelSize = 0;
  18603. }
  18604. // Variables initalization
  18605. var ahole, h, hl; // looping of holes
  18606. var scope = this;
  18607. var bevelPoints = [];
  18608. var shapesOffset = this.vertices.length;
  18609. var shapePoints = shape.extractPoints( curveSegments );
  18610. var vertices = shapePoints.shape;
  18611. var holes = shapePoints.holes;
  18612. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18613. if ( reverse ) {
  18614. vertices = vertices.reverse();
  18615. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18616. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18617. ahole = holes[ h ];
  18618. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18619. holes[ h ] = ahole.reverse();
  18620. }
  18621. }
  18622. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18623. }
  18624. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18625. /* Vertices */
  18626. var contour = vertices; // vertices has all points but contour has only points of circumference
  18627. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18628. ahole = holes[ h ];
  18629. vertices = vertices.concat( ahole );
  18630. }
  18631. function scalePt2 ( pt, vec, size ) {
  18632. if ( !vec ) console.log( "die" );
  18633. return vec.clone().multiplyScalar( size ).add( pt );
  18634. }
  18635. var b, bs, t, z,
  18636. vert, vlen = vertices.length,
  18637. face, flen = faces.length,
  18638. cont, clen = contour.length;
  18639. // Find directions for point movement
  18640. var RAD_TO_DEGREES = 180 / Math.PI;
  18641. function getBevelVec( pt_i, pt_j, pt_k ) {
  18642. // Algorithm 2
  18643. return getBevelVec2( pt_i, pt_j, pt_k );
  18644. }
  18645. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18646. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18647. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18648. if ( anglea > angleb ) {
  18649. angleb += Math.PI * 2;
  18650. }
  18651. var anglec = ( anglea + angleb ) / 2;
  18652. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18653. var x = - Math.cos( anglec );
  18654. var y = - Math.sin( anglec );
  18655. var vec = new THREE.Vector2( x, y ); //.normalize();
  18656. return vec;
  18657. }
  18658. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18659. var a = THREE.ExtrudeGeometry.__v1,
  18660. b = THREE.ExtrudeGeometry.__v2,
  18661. v_hat = THREE.ExtrudeGeometry.__v3,
  18662. w_hat = THREE.ExtrudeGeometry.__v4,
  18663. p = THREE.ExtrudeGeometry.__v5,
  18664. q = THREE.ExtrudeGeometry.__v6,
  18665. v, w,
  18666. v_dot_w_hat, q_sub_p_dot_w_hat,
  18667. s, intersection;
  18668. // good reading for line-line intersection
  18669. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18670. // define a as vector j->i
  18671. // define b as vectot k->i
  18672. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18673. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18674. // get unit vectors
  18675. v = a.normalize();
  18676. w = b.normalize();
  18677. // normals from pt i
  18678. v_hat.set( -v.y, v.x );
  18679. w_hat.set( w.y, -w.x );
  18680. // pts from i
  18681. p.copy( pt_i ).add( v_hat );
  18682. q.copy( pt_i ).add( w_hat );
  18683. if ( p.equals( q ) ) {
  18684. //console.log("Warning: lines are straight");
  18685. return w_hat.clone();
  18686. }
  18687. // Points from j, k. helps prevents points cross overover most of the time
  18688. p.copy( pt_j ).add( v_hat );
  18689. q.copy( pt_k ).add( w_hat );
  18690. v_dot_w_hat = v.dot( w_hat );
  18691. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18692. // We should not reach these conditions
  18693. if ( v_dot_w_hat === 0 ) {
  18694. console.log( "Either infinite or no solutions!" );
  18695. if ( q_sub_p_dot_w_hat === 0 ) {
  18696. console.log( "Its finite solutions." );
  18697. } else {
  18698. console.log( "Too bad, no solutions." );
  18699. }
  18700. }
  18701. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18702. if ( s < 0 ) {
  18703. // in case of emergecy, revert to algorithm 1.
  18704. return getBevelVec1( pt_i, pt_j, pt_k );
  18705. }
  18706. intersection = v.multiplyScalar( s ).add( p );
  18707. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18708. }
  18709. var contourMovements = [];
  18710. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18711. if ( j === il ) j = 0;
  18712. if ( k === il ) k = 0;
  18713. // (j)---(i)---(k)
  18714. // console.log('i,j,k', i, j , k)
  18715. var pt_i = contour[ i ];
  18716. var pt_j = contour[ j ];
  18717. var pt_k = contour[ k ];
  18718. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18719. }
  18720. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18721. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18722. ahole = holes[ h ];
  18723. oneHoleMovements = [];
  18724. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18725. if ( j === il ) j = 0;
  18726. if ( k === il ) k = 0;
  18727. // (j)---(i)---(k)
  18728. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18729. }
  18730. holesMovements.push( oneHoleMovements );
  18731. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18732. }
  18733. // Loop bevelSegments, 1 for the front, 1 for the back
  18734. for ( b = 0; b < bevelSegments; b ++ ) {
  18735. //for ( b = bevelSegments; b > 0; b -- ) {
  18736. t = b / bevelSegments;
  18737. z = bevelThickness * ( 1 - t );
  18738. //z = bevelThickness * t;
  18739. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18740. //bs = bevelSize * t ; // linear
  18741. // contract shape
  18742. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18743. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18744. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18745. v( vert.x, vert.y, - z );
  18746. }
  18747. // expand holes
  18748. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18749. ahole = holes[ h ];
  18750. oneHoleMovements = holesMovements[ h ];
  18751. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18752. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18753. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18754. v( vert.x, vert.y, -z );
  18755. }
  18756. }
  18757. }
  18758. bs = bevelSize;
  18759. // Back facing vertices
  18760. for ( i = 0; i < vlen; i ++ ) {
  18761. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18762. if ( !extrudeByPath ) {
  18763. v( vert.x, vert.y, 0 );
  18764. } else {
  18765. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18766. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18767. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18768. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18769. v( position2.x, position2.y, position2.z );
  18770. }
  18771. }
  18772. // Add stepped vertices...
  18773. // Including front facing vertices
  18774. var s;
  18775. for ( s = 1; s <= steps; s ++ ) {
  18776. for ( i = 0; i < vlen; i ++ ) {
  18777. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18778. if ( !extrudeByPath ) {
  18779. v( vert.x, vert.y, amount / steps * s );
  18780. } else {
  18781. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18782. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18783. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18784. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18785. v( position2.x, position2.y, position2.z );
  18786. }
  18787. }
  18788. }
  18789. // Add bevel segments planes
  18790. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18791. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18792. t = b / bevelSegments;
  18793. z = bevelThickness * ( 1 - t );
  18794. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18795. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18796. // contract shape
  18797. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18798. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18799. v( vert.x, vert.y, amount + z );
  18800. }
  18801. // expand holes
  18802. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18803. ahole = holes[ h ];
  18804. oneHoleMovements = holesMovements[ h ];
  18805. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18806. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18807. if ( !extrudeByPath ) {
  18808. v( vert.x, vert.y, amount + z );
  18809. } else {
  18810. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18811. }
  18812. }
  18813. }
  18814. }
  18815. /* Faces */
  18816. // Top and bottom faces
  18817. buildLidFaces();
  18818. // Sides faces
  18819. buildSideFaces();
  18820. ///// Internal functions
  18821. function buildLidFaces() {
  18822. if ( bevelEnabled ) {
  18823. var layer = 0 ; // steps + 1
  18824. var offset = vlen * layer;
  18825. // Bottom faces
  18826. for ( i = 0; i < flen; i ++ ) {
  18827. face = faces[ i ];
  18828. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18829. }
  18830. layer = steps + bevelSegments * 2;
  18831. offset = vlen * layer;
  18832. // Top faces
  18833. for ( i = 0; i < flen; i ++ ) {
  18834. face = faces[ i ];
  18835. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18836. }
  18837. } else {
  18838. // Bottom faces
  18839. for ( i = 0; i < flen; i++ ) {
  18840. face = faces[ i ];
  18841. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18842. }
  18843. // Top faces
  18844. for ( i = 0; i < flen; i ++ ) {
  18845. face = faces[ i ];
  18846. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18847. }
  18848. }
  18849. }
  18850. // Create faces for the z-sides of the shape
  18851. function buildSideFaces() {
  18852. var layeroffset = 0;
  18853. sidewalls( contour, layeroffset );
  18854. layeroffset += contour.length;
  18855. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18856. ahole = holes[ h ];
  18857. sidewalls( ahole, layeroffset );
  18858. //, true
  18859. layeroffset += ahole.length;
  18860. }
  18861. }
  18862. function sidewalls( contour, layeroffset ) {
  18863. var j, k;
  18864. i = contour.length;
  18865. while ( --i >= 0 ) {
  18866. j = i;
  18867. k = i - 1;
  18868. if ( k < 0 ) k = contour.length - 1;
  18869. //console.log('b', i,j, i-1, k,vertices.length);
  18870. var s = 0, sl = steps + bevelSegments * 2;
  18871. for ( s = 0; s < sl; s ++ ) {
  18872. var slen1 = vlen * s;
  18873. var slen2 = vlen * ( s + 1 );
  18874. var a = layeroffset + j + slen1,
  18875. b = layeroffset + k + slen1,
  18876. c = layeroffset + k + slen2,
  18877. d = layeroffset + j + slen2;
  18878. f4( a, b, c, d, contour, s, sl, j, k );
  18879. }
  18880. }
  18881. }
  18882. function v( x, y, z ) {
  18883. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18884. }
  18885. function f3( a, b, c, isBottom ) {
  18886. a += shapesOffset;
  18887. b += shapesOffset;
  18888. c += shapesOffset;
  18889. // normal, color, material
  18890. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18891. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18892. scope.faceVertexUvs[ 0 ].push( uvs );
  18893. }
  18894. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18895. a += shapesOffset;
  18896. b += shapesOffset;
  18897. c += shapesOffset;
  18898. d += shapesOffset;
  18899. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18900. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18901. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18902. scope.faceVertexUvs[ 0 ].push( uvs );
  18903. }
  18904. };
  18905. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18906. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18907. var ax = geometry.vertices[ indexA ].x,
  18908. ay = geometry.vertices[ indexA ].y,
  18909. bx = geometry.vertices[ indexB ].x,
  18910. by = geometry.vertices[ indexB ].y,
  18911. cx = geometry.vertices[ indexC ].x,
  18912. cy = geometry.vertices[ indexC ].y;
  18913. return [
  18914. new THREE.Vector2( ax, ay ),
  18915. new THREE.Vector2( bx, by ),
  18916. new THREE.Vector2( cx, cy )
  18917. ];
  18918. },
  18919. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18920. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18921. },
  18922. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18923. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18924. contourIndex1, contourIndex2 ) {
  18925. var ax = geometry.vertices[ indexA ].x,
  18926. ay = geometry.vertices[ indexA ].y,
  18927. az = geometry.vertices[ indexA ].z,
  18928. bx = geometry.vertices[ indexB ].x,
  18929. by = geometry.vertices[ indexB ].y,
  18930. bz = geometry.vertices[ indexB ].z,
  18931. cx = geometry.vertices[ indexC ].x,
  18932. cy = geometry.vertices[ indexC ].y,
  18933. cz = geometry.vertices[ indexC ].z,
  18934. dx = geometry.vertices[ indexD ].x,
  18935. dy = geometry.vertices[ indexD ].y,
  18936. dz = geometry.vertices[ indexD ].z;
  18937. if ( Math.abs( ay - by ) < 0.01 ) {
  18938. return [
  18939. new THREE.Vector2( ax, 1 - az ),
  18940. new THREE.Vector2( bx, 1 - bz ),
  18941. new THREE.Vector2( cx, 1 - cz ),
  18942. new THREE.Vector2( dx, 1 - dz )
  18943. ];
  18944. } else {
  18945. return [
  18946. new THREE.Vector2( ay, 1 - az ),
  18947. new THREE.Vector2( by, 1 - bz ),
  18948. new THREE.Vector2( cy, 1 - cz ),
  18949. new THREE.Vector2( dy, 1 - dz )
  18950. ];
  18951. }
  18952. }
  18953. };
  18954. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18955. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18956. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18957. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18958. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18959. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18960. /**
  18961. * @author jonobr1 / http://jonobr1.com
  18962. *
  18963. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18964. * ExtrudeGeometry.
  18965. *
  18966. * parameters = {
  18967. *
  18968. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18969. *
  18970. * material: <int> // material index for front and back faces
  18971. * uvGenerator: <Object> // object that provides UV generator functions
  18972. *
  18973. * }
  18974. **/
  18975. THREE.ShapeGeometry = function ( shapes, options ) {
  18976. THREE.Geometry.call( this );
  18977. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18978. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18979. this.addShapeList( shapes, options );
  18980. this.computeCentroids();
  18981. this.computeFaceNormals();
  18982. };
  18983. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18984. /**
  18985. * Add an array of shapes to THREE.ShapeGeometry.
  18986. */
  18987. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18988. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18989. this.addShape( shapes[ i ], options );
  18990. }
  18991. return this;
  18992. };
  18993. /**
  18994. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18995. */
  18996. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18997. if ( options === undefined ) options = {};
  18998. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18999. var material = options.material;
  19000. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19001. var shapebb = this.shapebb;
  19002. //
  19003. var i, l, hole, s;
  19004. var shapesOffset = this.vertices.length;
  19005. var shapePoints = shape.extractPoints( curveSegments );
  19006. var vertices = shapePoints.shape;
  19007. var holes = shapePoints.holes;
  19008. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19009. if ( reverse ) {
  19010. vertices = vertices.reverse();
  19011. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19012. for ( i = 0, l = holes.length; i < l; i++ ) {
  19013. hole = holes[ i ];
  19014. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19015. holes[ i ] = hole.reverse();
  19016. }
  19017. }
  19018. reverse = false;
  19019. }
  19020. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19021. // Vertices
  19022. var contour = vertices;
  19023. for ( i = 0, l = holes.length; i < l; i++ ) {
  19024. hole = holes[ i ];
  19025. vertices = vertices.concat( hole );
  19026. }
  19027. //
  19028. var vert, vlen = vertices.length;
  19029. var face, flen = faces.length;
  19030. var cont, clen = contour.length;
  19031. for ( i = 0; i < vlen; i++ ) {
  19032. vert = vertices[ i ];
  19033. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19034. }
  19035. for ( i = 0; i < flen; i++ ) {
  19036. face = faces[ i ];
  19037. var a = face[ 0 ] + shapesOffset;
  19038. var b = face[ 1 ] + shapesOffset;
  19039. var c = face[ 2 ] + shapesOffset;
  19040. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19041. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19042. }
  19043. };
  19044. /**
  19045. * @author astrodud / http://astrodud.isgreat.org/
  19046. * @author zz85 / https://github.com/zz85
  19047. * @author bhouston / http://exocortex.com
  19048. */
  19049. // points - to create a closed torus, one must use a set of points
  19050. // like so: [ a, b, c, d, a ], see first is the same as last.
  19051. // segments - the number of circumference segments to create
  19052. // phiStart - the starting radian
  19053. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19054. // 2*pi is a closed lathe, less than 2PI is a portion.
  19055. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19056. THREE.Geometry.call( this );
  19057. segments = segments || 12;
  19058. phiStart = phiStart || 0;
  19059. phiLength = phiLength || 2 * Math.PI;
  19060. var inversePointLength = 1.0 / ( points.length - 1 );
  19061. var inverseSegments = 1.0 / segments;
  19062. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19063. var phi = phiStart + i * inverseSegments * phiLength;
  19064. var c = Math.cos( phi ),
  19065. s = Math.sin( phi );
  19066. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19067. var pt = points[ j ];
  19068. var vertex = new THREE.Vector3();
  19069. vertex.x = c * pt.x - s * pt.y;
  19070. vertex.y = s * pt.x + c * pt.y;
  19071. vertex.z = pt.z;
  19072. this.vertices.push( vertex );
  19073. }
  19074. }
  19075. var np = points.length;
  19076. for ( var i = 0, il = segments; i < il; i ++ ) {
  19077. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19078. var base = j + np * i;
  19079. var a = base;
  19080. var b = base + np;
  19081. var c = base + 1 + np;
  19082. var d = base + 1;
  19083. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19084. var u0 = i * inverseSegments;
  19085. var v0 = j * inversePointLength;
  19086. var u1 = u0 + inverseSegments;
  19087. var v1 = v0 + inversePointLength;
  19088. this.faceVertexUvs[ 0 ].push( [
  19089. new THREE.Vector2( u0, v0 ),
  19090. new THREE.Vector2( u1, v0 ),
  19091. new THREE.Vector2( u1, v1 ),
  19092. new THREE.Vector2( u0, v1 )
  19093. ] );
  19094. }
  19095. }
  19096. this.mergeVertices();
  19097. this.computeCentroids();
  19098. this.computeFaceNormals();
  19099. this.computeVertexNormals();
  19100. };
  19101. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19102. /**
  19103. * @author mrdoob / http://mrdoob.com/
  19104. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19105. */
  19106. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19107. THREE.Geometry.call( this );
  19108. this.width = width;
  19109. this.height = height;
  19110. this.widthSegments = widthSegments || 1;
  19111. this.heightSegments = heightSegments || 1;
  19112. var ix, iz;
  19113. var width_half = width / 2;
  19114. var height_half = height / 2;
  19115. var gridX = this.widthSegments;
  19116. var gridZ = this.heightSegments;
  19117. var gridX1 = gridX + 1;
  19118. var gridZ1 = gridZ + 1;
  19119. var segment_width = this.width / gridX;
  19120. var segment_height = this.height / gridZ;
  19121. var normal = new THREE.Vector3( 0, 0, 1 );
  19122. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19123. for ( ix = 0; ix < gridX1; ix ++ ) {
  19124. var x = ix * segment_width - width_half;
  19125. var y = iz * segment_height - height_half;
  19126. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19127. }
  19128. }
  19129. for ( iz = 0; iz < gridZ; iz ++ ) {
  19130. for ( ix = 0; ix < gridX; ix ++ ) {
  19131. var a = ix + gridX1 * iz;
  19132. var b = ix + gridX1 * ( iz + 1 );
  19133. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19134. var d = ( ix + 1 ) + gridX1 * iz;
  19135. var face = new THREE.Face4( a, b, c, d );
  19136. face.normal.copy( normal );
  19137. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19138. this.faces.push( face );
  19139. this.faceVertexUvs[ 0 ].push( [
  19140. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19141. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19142. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19143. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19144. ] );
  19145. }
  19146. }
  19147. this.computeCentroids();
  19148. };
  19149. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19150. /**
  19151. * @author mrdoob / http://mrdoob.com/
  19152. */
  19153. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19154. THREE.Geometry.call( this );
  19155. this.radius = radius || 50;
  19156. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19157. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19158. phiStart = phiStart !== undefined ? phiStart : 0;
  19159. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19160. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19161. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19162. var x, y, vertices = [], uvs = [];
  19163. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19164. var verticesRow = [];
  19165. var uvsRow = [];
  19166. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19167. var u = x / this.widthSegments;
  19168. var v = y / this.heightSegments;
  19169. var vertex = new THREE.Vector3();
  19170. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19171. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19172. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19173. this.vertices.push( vertex );
  19174. verticesRow.push( this.vertices.length - 1 );
  19175. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19176. }
  19177. vertices.push( verticesRow );
  19178. uvs.push( uvsRow );
  19179. }
  19180. for ( y = 0; y < this.heightSegments; y ++ ) {
  19181. for ( x = 0; x < this.widthSegments; x ++ ) {
  19182. var v1 = vertices[ y ][ x + 1 ];
  19183. var v2 = vertices[ y ][ x ];
  19184. var v3 = vertices[ y + 1 ][ x ];
  19185. var v4 = vertices[ y + 1 ][ x + 1 ];
  19186. var n1 = this.vertices[ v1 ].clone().normalize();
  19187. var n2 = this.vertices[ v2 ].clone().normalize();
  19188. var n3 = this.vertices[ v3 ].clone().normalize();
  19189. var n4 = this.vertices[ v4 ].clone().normalize();
  19190. var uv1 = uvs[ y ][ x + 1 ].clone();
  19191. var uv2 = uvs[ y ][ x ].clone();
  19192. var uv3 = uvs[ y + 1 ][ x ].clone();
  19193. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19194. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19195. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19196. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19197. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19198. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19199. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19200. } else {
  19201. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19202. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19203. }
  19204. }
  19205. }
  19206. this.computeCentroids();
  19207. this.computeFaceNormals();
  19208. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19209. };
  19210. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19211. /**
  19212. * @author zz85 / http://www.lab4games.net/zz85/blog
  19213. * @author alteredq / http://alteredqualia.com/
  19214. *
  19215. * For creating 3D text geometry in three.js
  19216. *
  19217. * Text = 3D Text
  19218. *
  19219. * parameters = {
  19220. * size: <float>, // size of the text
  19221. * height: <float>, // thickness to extrude text
  19222. * curveSegments: <int>, // number of points on the curves
  19223. *
  19224. * font: <string>, // font name
  19225. * weight: <string>, // font weight (normal, bold)
  19226. * style: <string>, // font style (normal, italics)
  19227. *
  19228. * bevelEnabled: <bool>, // turn on bevel
  19229. * bevelThickness: <float>, // how deep into text bevel goes
  19230. * bevelSize: <float>, // how far from text outline is bevel
  19231. * }
  19232. *
  19233. */
  19234. /* Usage Examples
  19235. // TextGeometry wrapper
  19236. var text3d = new TextGeometry( text, options );
  19237. // Complete manner
  19238. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19239. var text3d = new ExtrudeGeometry( textShapes, options );
  19240. */
  19241. THREE.TextGeometry = function ( text, parameters ) {
  19242. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19243. // translate parameters to ExtrudeGeometry API
  19244. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19245. // defaults
  19246. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19247. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19248. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19249. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19250. };
  19251. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19252. /**
  19253. * @author oosmoxiecode
  19254. * @author mrdoob / http://mrdoob.com/
  19255. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19256. */
  19257. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19258. THREE.Geometry.call( this );
  19259. var scope = this;
  19260. this.radius = radius || 100;
  19261. this.tube = tube || 40;
  19262. this.radialSegments = radialSegments || 8;
  19263. this.tubularSegments = tubularSegments || 6;
  19264. this.arc = arc || Math.PI * 2;
  19265. var center = new THREE.Vector3(), uvs = [], normals = [];
  19266. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19267. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19268. var u = i / this.tubularSegments * this.arc;
  19269. var v = j / this.radialSegments * Math.PI * 2;
  19270. center.x = this.radius * Math.cos( u );
  19271. center.y = this.radius * Math.sin( u );
  19272. var vertex = new THREE.Vector3();
  19273. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19274. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19275. vertex.z = this.tube * Math.sin( v );
  19276. this.vertices.push( vertex );
  19277. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19278. normals.push( vertex.clone().sub( center ).normalize() );
  19279. }
  19280. }
  19281. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19282. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19283. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19284. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19285. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19286. var d = ( this.tubularSegments + 1 ) * j + i;
  19287. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19288. face.normal.add( normals[ a ] );
  19289. face.normal.add( normals[ b ] );
  19290. face.normal.add( normals[ c ] );
  19291. face.normal.add( normals[ d ] );
  19292. face.normal.normalize();
  19293. this.faces.push( face );
  19294. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19295. }
  19296. }
  19297. this.computeCentroids();
  19298. };
  19299. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19300. /**
  19301. * @author oosmoxiecode
  19302. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19303. */
  19304. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19305. THREE.Geometry.call( this );
  19306. var scope = this;
  19307. this.radius = radius || 100;
  19308. this.tube = tube || 40;
  19309. this.radialSegments = radialSegments || 64;
  19310. this.tubularSegments = tubularSegments || 8;
  19311. this.p = p || 2;
  19312. this.q = q || 3;
  19313. this.heightScale = heightScale || 1;
  19314. this.grid = new Array( this.radialSegments );
  19315. var tang = new THREE.Vector3();
  19316. var n = new THREE.Vector3();
  19317. var bitan = new THREE.Vector3();
  19318. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19319. this.grid[ i ] = new Array( this.tubularSegments );
  19320. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19321. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19322. var v = j / this.tubularSegments * 2 * Math.PI;
  19323. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19324. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19325. var cx, cy;
  19326. tang.subVectors( p2, p1 );
  19327. n.addVectors( p2, p1 );
  19328. bitan.crossVectors( tang, n );
  19329. n.crossVectors( bitan, tang );
  19330. bitan.normalize();
  19331. n.normalize();
  19332. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19333. cy = this.tube * Math.sin( v );
  19334. p1.x += cx * n.x + cy * bitan.x;
  19335. p1.y += cx * n.y + cy * bitan.y;
  19336. p1.z += cx * n.z + cy * bitan.z;
  19337. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19338. }
  19339. }
  19340. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19341. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19342. var ip = ( i + 1 ) % this.radialSegments;
  19343. var jp = ( j + 1 ) % this.tubularSegments;
  19344. var a = this.grid[ i ][ j ];
  19345. var b = this.grid[ ip ][ j ];
  19346. var c = this.grid[ ip ][ jp ];
  19347. var d = this.grid[ i ][ jp ];
  19348. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19349. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19350. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19351. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19352. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19353. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19354. }
  19355. }
  19356. this.computeCentroids();
  19357. this.computeFaceNormals();
  19358. this.computeVertexNormals();
  19359. function vert( x, y, z ) {
  19360. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19361. }
  19362. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19363. var cu = Math.cos( u );
  19364. var cv = Math.cos( v );
  19365. var su = Math.sin( u );
  19366. var quOverP = in_q / in_p * u;
  19367. var cs = Math.cos( quOverP );
  19368. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19369. var ty = radius * ( 2 + cs ) * su * 0.5;
  19370. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19371. return new THREE.Vector3( tx, ty, tz );
  19372. }
  19373. };
  19374. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19375. /**
  19376. * @author WestLangley / https://github.com/WestLangley
  19377. * @author zz85 / https://github.com/zz85
  19378. * @author miningold / https://github.com/miningold
  19379. *
  19380. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19381. *
  19382. * Creates a tube which extrudes along a 3d spline
  19383. *
  19384. * Uses parallel transport frames as described in
  19385. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19386. */
  19387. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19388. THREE.Geometry.call( this );
  19389. this.path = path;
  19390. this.segments = segments || 64;
  19391. this.radius = radius || 1;
  19392. this.radiusSegments = radiusSegments || 8;
  19393. this.closed = closed || false;
  19394. if ( debug ) this.debug = new THREE.Object3D();
  19395. this.grid = [];
  19396. var scope = this,
  19397. tangent,
  19398. normal,
  19399. binormal,
  19400. numpoints = this.segments + 1,
  19401. x, y, z,
  19402. tx, ty, tz,
  19403. u, v,
  19404. cx, cy,
  19405. pos, pos2 = new THREE.Vector3(),
  19406. i, j,
  19407. ip, jp,
  19408. a, b, c, d,
  19409. uva, uvb, uvc, uvd;
  19410. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19411. tangents = frames.tangents,
  19412. normals = frames.normals,
  19413. binormals = frames.binormals;
  19414. // proxy internals
  19415. this.tangents = tangents;
  19416. this.normals = normals;
  19417. this.binormals = binormals;
  19418. function vert( x, y, z ) {
  19419. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19420. }
  19421. // consruct the grid
  19422. for ( i = 0; i < numpoints; i++ ) {
  19423. this.grid[ i ] = [];
  19424. u = i / ( numpoints - 1 );
  19425. pos = path.getPointAt( u );
  19426. tangent = tangents[ i ];
  19427. normal = normals[ i ];
  19428. binormal = binormals[ i ];
  19429. if ( this.debug ) {
  19430. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19431. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19432. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19433. }
  19434. for ( j = 0; j < this.radiusSegments; j++ ) {
  19435. v = j / this.radiusSegments * 2 * Math.PI;
  19436. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19437. cy = this.radius * Math.sin( v );
  19438. pos2.copy( pos );
  19439. pos2.x += cx * normal.x + cy * binormal.x;
  19440. pos2.y += cx * normal.y + cy * binormal.y;
  19441. pos2.z += cx * normal.z + cy * binormal.z;
  19442. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19443. }
  19444. }
  19445. // construct the mesh
  19446. for ( i = 0; i < this.segments; i++ ) {
  19447. for ( j = 0; j < this.radiusSegments; j++ ) {
  19448. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19449. jp = (j + 1) % this.radiusSegments;
  19450. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19451. b = this.grid[ ip ][ j ];
  19452. c = this.grid[ ip ][ jp ];
  19453. d = this.grid[ i ][ jp ];
  19454. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19455. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19456. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19457. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19458. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19459. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19460. }
  19461. }
  19462. this.computeCentroids();
  19463. this.computeFaceNormals();
  19464. this.computeVertexNormals();
  19465. };
  19466. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19467. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19468. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19469. var tangent = new THREE.Vector3(),
  19470. normal = new THREE.Vector3(),
  19471. binormal = new THREE.Vector3(),
  19472. tangents = [],
  19473. normals = [],
  19474. binormals = [],
  19475. vec = new THREE.Vector3(),
  19476. mat = new THREE.Matrix4(),
  19477. numpoints = segments + 1,
  19478. theta,
  19479. epsilon = 0.0001,
  19480. smallest,
  19481. tx, ty, tz,
  19482. i, u, v;
  19483. // expose internals
  19484. this.tangents = tangents;
  19485. this.normals = normals;
  19486. this.binormals = binormals;
  19487. // compute the tangent vectors for each segment on the path
  19488. for ( i = 0; i < numpoints; i++ ) {
  19489. u = i / ( numpoints - 1 );
  19490. tangents[ i ] = path.getTangentAt( u );
  19491. tangents[ i ].normalize();
  19492. }
  19493. initialNormal3();
  19494. function initialNormal1(lastBinormal) {
  19495. // fixed start binormal. Has dangers of 0 vectors
  19496. normals[ 0 ] = new THREE.Vector3();
  19497. binormals[ 0 ] = new THREE.Vector3();
  19498. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19499. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19500. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19501. }
  19502. function initialNormal2() {
  19503. // This uses the Frenet-Serret formula for deriving binormal
  19504. var t2 = path.getTangentAt( epsilon );
  19505. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19506. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19507. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19508. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19509. }
  19510. function initialNormal3() {
  19511. // select an initial normal vector perpenicular to the first tangent vector,
  19512. // and in the direction of the smallest tangent xyz component
  19513. normals[ 0 ] = new THREE.Vector3();
  19514. binormals[ 0 ] = new THREE.Vector3();
  19515. smallest = Number.MAX_VALUE;
  19516. tx = Math.abs( tangents[ 0 ].x );
  19517. ty = Math.abs( tangents[ 0 ].y );
  19518. tz = Math.abs( tangents[ 0 ].z );
  19519. if ( tx <= smallest ) {
  19520. smallest = tx;
  19521. normal.set( 1, 0, 0 );
  19522. }
  19523. if ( ty <= smallest ) {
  19524. smallest = ty;
  19525. normal.set( 0, 1, 0 );
  19526. }
  19527. if ( tz <= smallest ) {
  19528. normal.set( 0, 0, 1 );
  19529. }
  19530. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19531. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19532. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19533. }
  19534. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19535. for ( i = 1; i < numpoints; i++ ) {
  19536. normals[ i ] = normals[ i-1 ].clone();
  19537. binormals[ i ] = binormals[ i-1 ].clone();
  19538. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19539. if ( vec.length() > epsilon ) {
  19540. vec.normalize();
  19541. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19542. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19543. }
  19544. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19545. }
  19546. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19547. if ( closed ) {
  19548. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19549. theta /= ( numpoints - 1 );
  19550. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19551. theta = -theta;
  19552. }
  19553. for ( i = 1; i < numpoints; i++ ) {
  19554. // twist a little...
  19555. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19556. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19557. }
  19558. }
  19559. };
  19560. /**
  19561. * @author clockworkgeek / https://github.com/clockworkgeek
  19562. * @author timothypratley / https://github.com/timothypratley
  19563. */
  19564. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19565. THREE.Geometry.call( this );
  19566. radius = radius || 1;
  19567. detail = detail || 0;
  19568. var that = this;
  19569. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19570. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19571. }
  19572. var midpoints = [], p = this.vertices;
  19573. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19574. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19575. }
  19576. this.mergeVertices();
  19577. // Apply radius
  19578. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19579. this.vertices[ i ].multiplyScalar( radius );
  19580. }
  19581. // Project vector onto sphere's surface
  19582. function prepare( vector ) {
  19583. var vertex = vector.normalize().clone();
  19584. vertex.index = that.vertices.push( vertex ) - 1;
  19585. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19586. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19587. var v = inclination( vector ) / Math.PI + 0.5;
  19588. vertex.uv = new THREE.Vector2( u, 1 - v );
  19589. return vertex;
  19590. }
  19591. // Approximate a curved face with recursively sub-divided triangles.
  19592. function make( v1, v2, v3, detail ) {
  19593. if ( detail < 1 ) {
  19594. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19595. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19596. face.normal = face.centroid.clone().normalize();
  19597. that.faces.push( face );
  19598. var azi = azimuth( face.centroid );
  19599. that.faceVertexUvs[ 0 ].push( [
  19600. correctUV( v1.uv, v1, azi ),
  19601. correctUV( v2.uv, v2, azi ),
  19602. correctUV( v3.uv, v3, azi )
  19603. ] );
  19604. } else {
  19605. detail -= 1;
  19606. // split triangle into 4 smaller triangles
  19607. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19608. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19609. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19610. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19611. }
  19612. }
  19613. function midpoint( v1, v2 ) {
  19614. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19615. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19616. var mid = midpoints[ v1.index ][ v2.index ];
  19617. if ( mid === undefined ) {
  19618. // generate mean point and project to surface with prepare()
  19619. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19620. new THREE.Vector3().addVectors( v1, v2 ).divideScalar( 2 )
  19621. );
  19622. }
  19623. return mid;
  19624. }
  19625. // Angle around the Y axis, counter-clockwise when looking from above.
  19626. function azimuth( vector ) {
  19627. return Math.atan2( vector.z, -vector.x );
  19628. }
  19629. // Angle above the XZ plane.
  19630. function inclination( vector ) {
  19631. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19632. }
  19633. // Texture fixing helper. Spheres have some odd behaviours.
  19634. function correctUV( uv, vector, azimuth ) {
  19635. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19636. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19637. return uv;
  19638. }
  19639. this.computeCentroids();
  19640. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19641. };
  19642. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19643. /**
  19644. * @author timothypratley / https://github.com/timothypratley
  19645. */
  19646. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19647. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19648. var vertices = [
  19649. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19650. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19651. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19652. ];
  19653. var faces = [
  19654. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19655. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19656. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19657. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19658. ];
  19659. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19660. };
  19661. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19662. /**
  19663. * @author timothypratley / https://github.com/timothypratley
  19664. */
  19665. THREE.OctahedronGeometry = function ( radius, detail ) {
  19666. var vertices = [
  19667. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19668. ];
  19669. var faces = [
  19670. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19671. ];
  19672. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19673. };
  19674. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19675. /**
  19676. * @author timothypratley / https://github.com/timothypratley
  19677. */
  19678. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19679. var vertices = [
  19680. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19681. ];
  19682. var faces = [
  19683. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19684. ];
  19685. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19686. };
  19687. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19688. /**
  19689. * @author zz85 / https://github.com/zz85
  19690. * Parametric Surfaces Geometry
  19691. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19692. *
  19693. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19694. *
  19695. */
  19696. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19697. THREE.Geometry.call( this );
  19698. var verts = this.vertices;
  19699. var faces = this.faces;
  19700. var uvs = this.faceVertexUvs[ 0 ];
  19701. useTris = (useTris === undefined) ? false : useTris;
  19702. var i, il, j, p;
  19703. var u, v;
  19704. var stackCount = stacks + 1;
  19705. var sliceCount = slices + 1;
  19706. for ( i = 0; i <= stacks; i ++ ) {
  19707. v = i / stacks;
  19708. for ( j = 0; j <= slices; j ++ ) {
  19709. u = j / slices;
  19710. p = func( u, v );
  19711. verts.push( p );
  19712. }
  19713. }
  19714. var a, b, c, d;
  19715. var uva, uvb, uvc, uvd;
  19716. for ( i = 0; i < stacks; i ++ ) {
  19717. for ( j = 0; j < slices; j ++ ) {
  19718. a = i * sliceCount + j;
  19719. b = i * sliceCount + j + 1;
  19720. c = (i + 1) * sliceCount + j;
  19721. d = (i + 1) * sliceCount + j + 1;
  19722. uva = new THREE.Vector2( j / slices, i / stacks );
  19723. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19724. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19725. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19726. if ( useTris ) {
  19727. faces.push( new THREE.Face3( a, b, c ) );
  19728. faces.push( new THREE.Face3( b, d, c ) );
  19729. uvs.push( [ uva, uvb, uvc ] );
  19730. uvs.push( [ uvb, uvd, uvc ] );
  19731. } else {
  19732. faces.push( new THREE.Face4( a, b, d, c ) );
  19733. uvs.push( [ uva, uvb, uvd, uvc ] );
  19734. }
  19735. }
  19736. }
  19737. // console.log(this);
  19738. // magic bullet
  19739. // var diff = this.mergeVertices();
  19740. // console.log('removed ', diff, ' vertices by merging');
  19741. this.computeCentroids();
  19742. this.computeFaceNormals();
  19743. this.computeVertexNormals();
  19744. };
  19745. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19746. /**
  19747. * @author qiao / https://github.com/qiao
  19748. * @fileoverview This is a convex hull generator using the incremental method.
  19749. * The complexity is O(n^2) where n is the number of vertices.
  19750. * O(nlogn) algorithms do exist, but they are much more complicated.
  19751. *
  19752. * Benchmark:
  19753. *
  19754. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19755. *
  19756. * Num Vertices Time(ms)
  19757. *
  19758. * 10 1
  19759. * 20 3
  19760. * 30 19
  19761. * 40 48
  19762. * 50 107
  19763. */
  19764. THREE.ConvexGeometry = function( vertices ) {
  19765. THREE.Geometry.call( this );
  19766. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19767. for ( var i = 3; i < vertices.length; i++ ) {
  19768. addPoint( i );
  19769. }
  19770. function addPoint( vertexId ) {
  19771. var vertex = vertices[ vertexId ].clone();
  19772. var mag = vertex.length();
  19773. vertex.x += mag * randomOffset();
  19774. vertex.y += mag * randomOffset();
  19775. vertex.z += mag * randomOffset();
  19776. var hole = [];
  19777. for ( var f = 0; f < faces.length; ) {
  19778. var face = faces[ f ];
  19779. // for each face, if the vertex can see it,
  19780. // then we try to add the face's edges into the hole.
  19781. if ( visible( face, vertex ) ) {
  19782. for ( var e = 0; e < 3; e++ ) {
  19783. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19784. var boundary = true;
  19785. // remove duplicated edges.
  19786. for ( var h = 0; h < hole.length; h++ ) {
  19787. if ( equalEdge( hole[ h ], edge ) ) {
  19788. hole[ h ] = hole[ hole.length - 1 ];
  19789. hole.pop();
  19790. boundary = false;
  19791. break;
  19792. }
  19793. }
  19794. if ( boundary ) {
  19795. hole.push( edge );
  19796. }
  19797. }
  19798. // remove faces[ f ]
  19799. faces[ f ] = faces[ faces.length - 1 ];
  19800. faces.pop();
  19801. } else { // not visible
  19802. f++;
  19803. }
  19804. }
  19805. // construct the new faces formed by the edges of the hole and the vertex
  19806. for ( var h = 0; h < hole.length; h++ ) {
  19807. faces.push( [
  19808. hole[ h ][ 0 ],
  19809. hole[ h ][ 1 ],
  19810. vertexId
  19811. ] );
  19812. }
  19813. }
  19814. /**
  19815. * Whether the face is visible from the vertex
  19816. */
  19817. function visible( face, vertex ) {
  19818. var va = vertices[ face[ 0 ] ];
  19819. var vb = vertices[ face[ 1 ] ];
  19820. var vc = vertices[ face[ 2 ] ];
  19821. var n = normal( va, vb, vc );
  19822. // distance from face to origin
  19823. var dist = n.dot( va );
  19824. return n.dot( vertex ) >= dist;
  19825. }
  19826. /**
  19827. * Face normal
  19828. */
  19829. function normal( va, vb, vc ) {
  19830. var cb = new THREE.Vector3();
  19831. var ab = new THREE.Vector3();
  19832. cb.subVectors( vc, vb );
  19833. ab.subVectors( va, vb );
  19834. cb.cross( ab );
  19835. cb.normalize();
  19836. return cb;
  19837. }
  19838. /**
  19839. * Detect whether two edges are equal.
  19840. * Note that when constructing the convex hull, two same edges can only
  19841. * be of the negative direction.
  19842. */
  19843. function equalEdge( ea, eb ) {
  19844. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19845. }
  19846. /**
  19847. * Create a random offset between -1e-6 and 1e-6.
  19848. */
  19849. function randomOffset() {
  19850. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19851. }
  19852. /**
  19853. * XXX: Not sure if this is the correct approach. Need someone to review.
  19854. */
  19855. function vertexUv( vertex ) {
  19856. var mag = vertex.length();
  19857. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  19858. }
  19859. // Push vertices into `this.vertices`, skipping those inside the hull
  19860. var id = 0;
  19861. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19862. for ( var i = 0; i < faces.length; i++ ) {
  19863. var face = faces[ i ];
  19864. for ( var j = 0; j < 3; j++ ) {
  19865. if ( newId[ face[ j ] ] === undefined ) {
  19866. newId[ face[ j ] ] = id++;
  19867. this.vertices.push( vertices[ face[ j ] ] );
  19868. }
  19869. face[ j ] = newId[ face[ j ] ];
  19870. }
  19871. }
  19872. // Convert faces into instances of THREE.Face3
  19873. for ( var i = 0; i < faces.length; i++ ) {
  19874. this.faces.push( new THREE.Face3(
  19875. faces[ i ][ 0 ],
  19876. faces[ i ][ 1 ],
  19877. faces[ i ][ 2 ]
  19878. ) );
  19879. }
  19880. // Compute UVs
  19881. for ( var i = 0; i < this.faces.length; i++ ) {
  19882. var face = this.faces[ i ];
  19883. this.faceVertexUvs[ 0 ].push( [
  19884. vertexUv( this.vertices[ face.a ] ),
  19885. vertexUv( this.vertices[ face.b ] ),
  19886. vertexUv( this.vertices[ face.c ])
  19887. ] );
  19888. }
  19889. this.computeCentroids();
  19890. this.computeFaceNormals();
  19891. this.computeVertexNormals();
  19892. };
  19893. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19894. /**
  19895. * @author sroucheray / http://sroucheray.org/
  19896. * @author mrdoob / http://mrdoob.com/
  19897. */
  19898. THREE.AxisHelper = function ( size ) {
  19899. var geometry = new THREE.Geometry();
  19900. geometry.vertices.push(
  19901. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19902. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19903. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19904. );
  19905. geometry.colors.push(
  19906. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19907. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19908. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19909. );
  19910. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19911. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19912. };
  19913. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19914. /**
  19915. * @author WestLangley / http://github.com/WestLangley
  19916. * @author zz85 / https://github.com/zz85
  19917. * @author bhouston / https://exocortex.com
  19918. *
  19919. * Creates an arrow for visualizing directions
  19920. *
  19921. * Parameters:
  19922. * dir - Vector3
  19923. * origin - Vector3
  19924. * length - Number
  19925. * hex - color in hex value
  19926. */
  19927. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19928. THREE.Object3D.call( this );
  19929. if ( length === undefined ) length = 20;
  19930. if ( hex === undefined ) hex = 0xffff00;
  19931. var lineGeometry = new THREE.Geometry();
  19932. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19933. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19934. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19935. this.add( this.line );
  19936. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19937. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19938. this.cone.position.set( 0, 1, 0 );
  19939. this.add( this.cone );
  19940. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19941. this.setDirection( dir );
  19942. this.setLength( length );
  19943. };
  19944. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19945. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19946. var d = THREE.ArrowHelper.__v1.copy( dir ).normalize();
  19947. if ( d.y > 0.999 ) {
  19948. this.rotation.set( 0, 0, 0 );
  19949. } else if ( d.y < - 0.999 ) {
  19950. this.rotation.set( Math.PI, 0, 0 );
  19951. } else {
  19952. var axis = THREE.ArrowHelper.__v2.set( d.z, 0, - d.x ).normalize();
  19953. var radians = Math.acos( d.y );
  19954. var quaternion = THREE.ArrowHelper.__q1.setFromAxisAngle( axis, radians );
  19955. this.rotation.setEulerFromQuaternion( quaternion, this.eulerOrder );
  19956. }
  19957. };
  19958. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19959. this.scale.set( length, length, length );
  19960. };
  19961. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19962. this.line.material.color.setHex( hex );
  19963. this.cone.material.color.setHex( hex );
  19964. };
  19965. THREE.ArrowHelper.__v1 = new THREE.Vector3();
  19966. THREE.ArrowHelper.__v2 = new THREE.Vector3();
  19967. THREE.ArrowHelper.__q1 = new THREE.Quaternion();
  19968. /**
  19969. * @author alteredq / http://alteredqualia.com/
  19970. *
  19971. * - shows frustum, line of sight and up of the camera
  19972. * - suitable for fast updates
  19973. * - based on frustum visualization in lightgl.js shadowmap example
  19974. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19975. */
  19976. THREE.CameraHelper = function ( camera ) {
  19977. THREE.Line.call( this );
  19978. var scope = this;
  19979. this.geometry = new THREE.Geometry();
  19980. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19981. this.type = THREE.LinePieces;
  19982. this.matrixWorld = camera.matrixWorld;
  19983. this.matrixAutoUpdate = false;
  19984. this.pointMap = {};
  19985. // colors
  19986. var hexFrustum = 0xffaa00;
  19987. var hexCone = 0xff0000;
  19988. var hexUp = 0x00aaff;
  19989. var hexTarget = 0xffffff;
  19990. var hexCross = 0x333333;
  19991. // near
  19992. addLine( "n1", "n2", hexFrustum );
  19993. addLine( "n2", "n4", hexFrustum );
  19994. addLine( "n4", "n3", hexFrustum );
  19995. addLine( "n3", "n1", hexFrustum );
  19996. // far
  19997. addLine( "f1", "f2", hexFrustum );
  19998. addLine( "f2", "f4", hexFrustum );
  19999. addLine( "f4", "f3", hexFrustum );
  20000. addLine( "f3", "f1", hexFrustum );
  20001. // sides
  20002. addLine( "n1", "f1", hexFrustum );
  20003. addLine( "n2", "f2", hexFrustum );
  20004. addLine( "n3", "f3", hexFrustum );
  20005. addLine( "n4", "f4", hexFrustum );
  20006. // cone
  20007. addLine( "p", "n1", hexCone );
  20008. addLine( "p", "n2", hexCone );
  20009. addLine( "p", "n3", hexCone );
  20010. addLine( "p", "n4", hexCone );
  20011. // up
  20012. addLine( "u1", "u2", hexUp );
  20013. addLine( "u2", "u3", hexUp );
  20014. addLine( "u3", "u1", hexUp );
  20015. // target
  20016. addLine( "c", "t", hexTarget );
  20017. addLine( "p", "c", hexCross );
  20018. // cross
  20019. addLine( "cn1", "cn2", hexCross );
  20020. addLine( "cn3", "cn4", hexCross );
  20021. addLine( "cf1", "cf2", hexCross );
  20022. addLine( "cf3", "cf4", hexCross );
  20023. this.camera = camera;
  20024. function addLine( a, b, hex ) {
  20025. addPoint( a, hex );
  20026. addPoint( b, hex );
  20027. }
  20028. function addPoint( id, hex ) {
  20029. scope.geometry.vertices.push( new THREE.Vector3() );
  20030. scope.geometry.colors.push( new THREE.Color( hex ) );
  20031. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20032. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20033. }
  20034. this.update( camera );
  20035. };
  20036. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20037. THREE.CameraHelper.prototype.update = function () {
  20038. var scope = this;
  20039. var w = 1, h = 1;
  20040. // we need just camera projection matrix
  20041. // world matrix must be identity
  20042. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20043. // center / target
  20044. setPoint( "c", 0, 0, -1 );
  20045. setPoint( "t", 0, 0, 1 );
  20046. // near
  20047. setPoint( "n1", -w, -h, -1 );
  20048. setPoint( "n2", w, -h, -1 );
  20049. setPoint( "n3", -w, h, -1 );
  20050. setPoint( "n4", w, h, -1 );
  20051. // far
  20052. setPoint( "f1", -w, -h, 1 );
  20053. setPoint( "f2", w, -h, 1 );
  20054. setPoint( "f3", -w, h, 1 );
  20055. setPoint( "f4", w, h, 1 );
  20056. // up
  20057. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20058. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20059. setPoint( "u3", 0, h * 2, -1 );
  20060. // cross
  20061. setPoint( "cf1", -w, 0, 1 );
  20062. setPoint( "cf2", w, 0, 1 );
  20063. setPoint( "cf3", 0, -h, 1 );
  20064. setPoint( "cf4", 0, h, 1 );
  20065. setPoint( "cn1", -w, 0, -1 );
  20066. setPoint( "cn2", w, 0, -1 );
  20067. setPoint( "cn3", 0, -h, -1 );
  20068. setPoint( "cn4", 0, h, -1 );
  20069. function setPoint( point, x, y, z ) {
  20070. THREE.CameraHelper.__v.set( x, y, z );
  20071. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20072. var points = scope.pointMap[ point ];
  20073. if ( points !== undefined ) {
  20074. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20075. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20076. }
  20077. }
  20078. }
  20079. this.geometry.verticesNeedUpdate = true;
  20080. };
  20081. THREE.CameraHelper.__projector = new THREE.Projector();
  20082. THREE.CameraHelper.__v = new THREE.Vector3();
  20083. THREE.CameraHelper.__c = new THREE.Camera();
  20084. /**
  20085. * @author alteredq / http://alteredqualia.com/
  20086. *
  20087. * - shows directional light color, intensity, position, orientation and target
  20088. */
  20089. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20090. THREE.Object3D.call( this );
  20091. this.light = light;
  20092. // position
  20093. this.position = light.position;
  20094. // direction
  20095. this.direction = new THREE.Vector3();
  20096. this.direction.subVectors( light.target.position, light.position );
  20097. // color
  20098. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20099. this.color = light.color.clone();
  20100. this.color.multiplyScalar( intensity );
  20101. var hexColor = this.color.getHex();
  20102. // light helper
  20103. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20104. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20105. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20106. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20107. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20108. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20109. this.add( this.lightSphere );
  20110. this.add( this.lightRays );
  20111. this.lightSphere.properties.isGizmo = true;
  20112. this.lightSphere.properties.gizmoSubject = light;
  20113. this.lightSphere.properties.gizmoRoot = this;
  20114. // light target helper
  20115. this.targetSphere = null;
  20116. if ( light.target.properties.targetInverse !== undefined ) {
  20117. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20118. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20119. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20120. this.targetSphere.position = light.target.position;
  20121. this.targetSphere.properties.isGizmo = true;
  20122. this.targetSphere.properties.gizmoSubject = light.target;
  20123. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20124. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20125. var lineGeometry = new THREE.Geometry();
  20126. lineGeometry.vertices.push( this.position.clone() );
  20127. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20128. lineGeometry.computeLineDistances();
  20129. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20130. this.targetLine.properties.isGizmo = true;
  20131. }
  20132. //
  20133. this.properties.isGizmo = true;
  20134. }
  20135. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20136. THREE.DirectionalLightHelper.prototype.update = function () {
  20137. // update arrow orientation
  20138. // pointing from light to target
  20139. this.direction.subVectors( this.light.target.position, this.light.position );
  20140. // update arrow, spheres, rays and line colors to light color * light intensity
  20141. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20142. this.color.copy( this.light.color );
  20143. this.color.multiplyScalar( intensity );
  20144. this.lightSphere.material.color.copy( this.color );
  20145. this.lightRays.material.color.copy( this.color );
  20146. // Only update targetSphere and targetLine if available
  20147. if ( this.targetSphere !== null ) {
  20148. this.targetSphere.material.color.copy( this.color );
  20149. this.targetLine.material.color.copy( this.color );
  20150. // update target line vertices
  20151. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20152. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20153. this.targetLine.geometry.computeLineDistances();
  20154. this.targetLine.geometry.verticesNeedUpdate = true;
  20155. }
  20156. }
  20157. /**
  20158. * @author alteredq / http://alteredqualia.com/
  20159. *
  20160. * - shows hemisphere light intensity, sky and ground colors and directions
  20161. */
  20162. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20163. THREE.Object3D.call( this );
  20164. this.light = light;
  20165. // position
  20166. this.position = light.position;
  20167. //
  20168. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20169. // sky color
  20170. this.color = light.color.clone();
  20171. this.color.multiplyScalar( intensity );
  20172. var hexColor = this.color.getHex();
  20173. // ground color
  20174. this.groundColor = light.groundColor.clone();
  20175. this.groundColor.multiplyScalar( intensity );
  20176. var hexColorGround = this.groundColor.getHex();
  20177. // double colored light bulb
  20178. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20179. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20180. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20181. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20182. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20183. bulbGeometry.faces[ i ].materialIndex = 0;
  20184. }
  20185. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20186. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20187. }
  20188. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20189. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20190. // arrows for sky and ground light directions
  20191. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20192. this.lightArrow.rotation.x = Math.PI;
  20193. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20194. var joint = new THREE.Object3D();
  20195. joint.rotation.x = -Math.PI * 0.5;
  20196. joint.add( this.lightSphere );
  20197. joint.add( this.lightArrow );
  20198. joint.add( this.lightArrowGround );
  20199. this.add( joint );
  20200. //
  20201. this.lightSphere.properties.isGizmo = true;
  20202. this.lightSphere.properties.gizmoSubject = light;
  20203. this.lightSphere.properties.gizmoRoot = this;
  20204. //
  20205. this.properties.isGizmo = true;
  20206. //
  20207. this.target = new THREE.Vector3();
  20208. this.lookAt( this.target );
  20209. }
  20210. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20211. THREE.HemisphereLightHelper.prototype.update = function () {
  20212. // update sphere sky and ground colors to light color * light intensity
  20213. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20214. this.color.copy( this.light.color );
  20215. this.color.multiplyScalar( intensity );
  20216. this.groundColor.copy( this.light.groundColor );
  20217. this.groundColor.multiplyScalar( intensity );
  20218. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20219. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20220. this.lightArrow.setColor( this.color.getHex() );
  20221. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20222. this.lookAt( this.target );
  20223. }
  20224. /**
  20225. * @author alteredq / http://alteredqualia.com/
  20226. *
  20227. * - shows point light color, intensity, position and distance
  20228. */
  20229. THREE.PointLightHelper = function ( light, sphereSize ) {
  20230. THREE.Object3D.call( this );
  20231. this.light = light;
  20232. // position
  20233. this.position = light.position;
  20234. // color
  20235. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20236. this.color = light.color.clone();
  20237. this.color.multiplyScalar( intensity );
  20238. var hexColor = this.color.getHex();
  20239. // light helper
  20240. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20241. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20242. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20243. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20244. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20245. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20246. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20247. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20248. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20249. var d = light.distance;
  20250. if ( d === 0.0 ) {
  20251. this.lightDistance.visible = false;
  20252. } else {
  20253. this.lightDistance.scale.set( d, d, d );
  20254. }
  20255. this.add( this.lightSphere );
  20256. this.add( this.lightRays );
  20257. this.add( this.lightDistance );
  20258. //
  20259. this.lightSphere.properties.isGizmo = true;
  20260. this.lightSphere.properties.gizmoSubject = light;
  20261. this.lightSphere.properties.gizmoRoot = this;
  20262. //
  20263. this.properties.isGizmo = true;
  20264. }
  20265. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20266. THREE.PointLightHelper.prototype.update = function () {
  20267. // update sphere and rays colors to light color * light intensity
  20268. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20269. this.color.copy( this.light.color );
  20270. this.color.multiplyScalar( intensity );
  20271. this.lightSphere.material.color.copy( this.color );
  20272. this.lightRays.material.color.copy( this.color );
  20273. this.lightDistance.material.color.copy( this.color );
  20274. //
  20275. var d = this.light.distance;
  20276. if ( d === 0.0 ) {
  20277. this.lightDistance.visible = false;
  20278. } else {
  20279. this.lightDistance.visible = true;
  20280. this.lightDistance.scale.set( d, d, d );
  20281. }
  20282. }
  20283. /**
  20284. * @author alteredq / http://alteredqualia.com/
  20285. *
  20286. * - shows spot light color, intensity, position, orientation, light cone and target
  20287. */
  20288. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20289. THREE.Object3D.call( this );
  20290. this.light = light;
  20291. // position
  20292. this.position = light.position;
  20293. // direction
  20294. this.direction = new THREE.Vector3();
  20295. this.direction.subVectors( light.target.position, light.position );
  20296. // color
  20297. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20298. this.color = light.color.clone();
  20299. this.color.multiplyScalar( intensity );
  20300. var hexColor = this.color.getHex();
  20301. // light helper
  20302. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20303. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20304. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20305. var coneMatrix = new THREE.Matrix4();
  20306. coneMatrix.rotateX( -Math.PI/2 );
  20307. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20308. coneGeometry.applyMatrix( coneMatrix );
  20309. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20310. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20311. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20312. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20313. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20314. var coneLength = light.distance ? light.distance : 10000;
  20315. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20316. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20317. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20318. this.gyroscope = new THREE.Gyroscope();
  20319. this.gyroscope.add( this.lightSphere );
  20320. this.gyroscope.add( this.lightRays );
  20321. this.add( this.gyroscope );
  20322. this.add( this.lightCone );
  20323. this.lookAt( light.target.position );
  20324. this.lightSphere.properties.isGizmo = true;
  20325. this.lightSphere.properties.gizmoSubject = light;
  20326. this.lightSphere.properties.gizmoRoot = this;
  20327. // light target helper
  20328. this.targetSphere = null;
  20329. if ( light.target.properties.targetInverse !== undefined ) {
  20330. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20331. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20332. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20333. this.targetSphere.position = light.target.position;
  20334. this.targetSphere.properties.isGizmo = true;
  20335. this.targetSphere.properties.gizmoSubject = light.target;
  20336. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20337. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20338. var lineGeometry = new THREE.Geometry();
  20339. lineGeometry.vertices.push( this.position.clone() );
  20340. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20341. lineGeometry.computeLineDistances();
  20342. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20343. this.targetLine.properties.isGizmo = true;
  20344. }
  20345. //
  20346. this.properties.isGizmo = true;
  20347. }
  20348. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20349. THREE.SpotLightHelper.prototype.update = function () {
  20350. // update arrow orientation
  20351. // pointing from light to target
  20352. this.direction.subVectors( this.light.target.position, this.light.position );
  20353. // update light cone orientation and size
  20354. this.lookAt( this.light.target.position );
  20355. var coneLength = this.light.distance ? this.light.distance : 10000;
  20356. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20357. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20358. // update arrow, spheres, rays and line colors to light color * light intensity
  20359. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20360. this.color.copy( this.light.color );
  20361. this.color.multiplyScalar( intensity );
  20362. this.lightSphere.material.color.copy( this.color );
  20363. this.lightRays.material.color.copy( this.color );
  20364. this.lightCone.material.color.copy( this.color );
  20365. // Only update targetSphere and targetLine if available
  20366. if ( this.targetSphere !== null ) {
  20367. this.targetSphere.material.color.copy( this.color );
  20368. this.targetLine.material.color.copy( this.color );
  20369. // update target line vertices
  20370. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20371. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20372. this.targetLine.geometry.computeLineDistances();
  20373. this.targetLine.geometry.verticesNeedUpdate = true;
  20374. }
  20375. };
  20376. /**
  20377. * @author alteredq / http://alteredqualia.com/
  20378. */
  20379. THREE.ImmediateRenderObject = function () {
  20380. THREE.Object3D.call( this );
  20381. this.render = function ( renderCallback ) { };
  20382. };
  20383. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20384. /**
  20385. * @author mikael emtinger / http://gomo.se/
  20386. * @author alteredq / http://alteredqualia.com/
  20387. */
  20388. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20389. THREE.Object3D.call( this );
  20390. this.lensFlares = [];
  20391. this.positionScreen = new THREE.Vector3();
  20392. this.customUpdateCallback = undefined;
  20393. if( texture !== undefined ) {
  20394. this.add( texture, size, distance, blending, color );
  20395. }
  20396. };
  20397. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20398. /*
  20399. * Add: adds another flare
  20400. */
  20401. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20402. if( size === undefined ) size = -1;
  20403. if( distance === undefined ) distance = 0;
  20404. if( opacity === undefined ) opacity = 1;
  20405. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20406. if( blending === undefined ) blending = THREE.NormalBlending;
  20407. distance = Math.min( distance, Math.max( 0, distance ) );
  20408. this.lensFlares.push( { texture: texture, // THREE.Texture
  20409. size: size, // size in pixels (-1 = use texture.width)
  20410. distance: distance, // distance (0-1) from light source (0=at light source)
  20411. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20412. scale: 1, // scale
  20413. rotation: 1, // rotation
  20414. opacity: opacity, // opacity
  20415. color: color, // color
  20416. blending: blending } ); // blending
  20417. };
  20418. /*
  20419. * Update lens flares update positions on all flares based on the screen position
  20420. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20421. */
  20422. THREE.LensFlare.prototype.updateLensFlares = function () {
  20423. var f, fl = this.lensFlares.length;
  20424. var flare;
  20425. var vecX = -this.positionScreen.x * 2;
  20426. var vecY = -this.positionScreen.y * 2;
  20427. for( f = 0; f < fl; f ++ ) {
  20428. flare = this.lensFlares[ f ];
  20429. flare.x = this.positionScreen.x + vecX * flare.distance;
  20430. flare.y = this.positionScreen.y + vecY * flare.distance;
  20431. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20432. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20433. }
  20434. };
  20435. /**
  20436. * @author alteredq / http://alteredqualia.com/
  20437. */
  20438. THREE.MorphBlendMesh = function( geometry, material ) {
  20439. THREE.Mesh.call( this, geometry, material );
  20440. this.animationsMap = {};
  20441. this.animationsList = [];
  20442. // prepare default animation
  20443. // (all frames played together in 1 second)
  20444. var numFrames = this.geometry.morphTargets.length;
  20445. var name = "__default";
  20446. var startFrame = 0;
  20447. var endFrame = numFrames - 1;
  20448. var fps = numFrames / 1;
  20449. this.createAnimation( name, startFrame, endFrame, fps );
  20450. this.setAnimationWeight( name, 1 );
  20451. };
  20452. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20453. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20454. var animation = {
  20455. startFrame: start,
  20456. endFrame: end,
  20457. length: end - start + 1,
  20458. fps: fps,
  20459. duration: ( end - start ) / fps,
  20460. lastFrame: 0,
  20461. currentFrame: 0,
  20462. active: false,
  20463. time: 0,
  20464. direction: 1,
  20465. weight: 1,
  20466. directionBackwards: false,
  20467. mirroredLoop: false
  20468. };
  20469. this.animationsMap[ name ] = animation;
  20470. this.animationsList.push( animation );
  20471. };
  20472. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20473. var pattern = /([a-z]+)(\d+)/;
  20474. var firstAnimation, frameRanges = {};
  20475. var geometry = this.geometry;
  20476. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20477. var morph = geometry.morphTargets[ i ];
  20478. var chunks = morph.name.match( pattern );
  20479. if ( chunks && chunks.length > 1 ) {
  20480. var name = chunks[ 1 ];
  20481. var num = chunks[ 2 ];
  20482. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20483. var range = frameRanges[ name ];
  20484. if ( i < range.start ) range.start = i;
  20485. if ( i > range.end ) range.end = i;
  20486. if ( ! firstAnimation ) firstAnimation = name;
  20487. }
  20488. }
  20489. for ( var name in frameRanges ) {
  20490. var range = frameRanges[ name ];
  20491. this.createAnimation( name, range.start, range.end, fps );
  20492. }
  20493. this.firstAnimation = firstAnimation;
  20494. };
  20495. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20496. var animation = this.animationsMap[ name ];
  20497. if ( animation ) {
  20498. animation.direction = 1;
  20499. animation.directionBackwards = false;
  20500. }
  20501. };
  20502. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20503. var animation = this.animationsMap[ name ];
  20504. if ( animation ) {
  20505. animation.direction = -1;
  20506. animation.directionBackwards = true;
  20507. }
  20508. };
  20509. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20510. var animation = this.animationsMap[ name ];
  20511. if ( animation ) {
  20512. animation.fps = fps;
  20513. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20514. }
  20515. };
  20516. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20517. var animation = this.animationsMap[ name ];
  20518. if ( animation ) {
  20519. animation.duration = duration;
  20520. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20521. }
  20522. };
  20523. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20524. var animation = this.animationsMap[ name ];
  20525. if ( animation ) {
  20526. animation.weight = weight;
  20527. }
  20528. };
  20529. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20530. var animation = this.animationsMap[ name ];
  20531. if ( animation ) {
  20532. animation.time = time;
  20533. }
  20534. };
  20535. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20536. var time = 0;
  20537. var animation = this.animationsMap[ name ];
  20538. if ( animation ) {
  20539. time = animation.time;
  20540. }
  20541. return time;
  20542. };
  20543. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20544. var duration = -1;
  20545. var animation = this.animationsMap[ name ];
  20546. if ( animation ) {
  20547. duration = animation.duration;
  20548. }
  20549. return duration;
  20550. };
  20551. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20552. var animation = this.animationsMap[ name ];
  20553. if ( animation ) {
  20554. animation.time = 0;
  20555. animation.active = true;
  20556. } else {
  20557. console.warn( "animation[" + name + "] undefined" );
  20558. }
  20559. };
  20560. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20561. var animation = this.animationsMap[ name ];
  20562. if ( animation ) {
  20563. animation.active = false;
  20564. }
  20565. };
  20566. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20567. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20568. var animation = this.animationsList[ i ];
  20569. if ( ! animation.active ) continue;
  20570. var frameTime = animation.duration / animation.length;
  20571. animation.time += animation.direction * delta;
  20572. if ( animation.mirroredLoop ) {
  20573. if ( animation.time > animation.duration || animation.time < 0 ) {
  20574. animation.direction *= -1;
  20575. if ( animation.time > animation.duration ) {
  20576. animation.time = animation.duration;
  20577. animation.directionBackwards = true;
  20578. }
  20579. if ( animation.time < 0 ) {
  20580. animation.time = 0;
  20581. animation.directionBackwards = false;
  20582. }
  20583. }
  20584. } else {
  20585. animation.time = animation.time % animation.duration;
  20586. if ( animation.time < 0 ) animation.time += animation.duration;
  20587. }
  20588. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20589. var weight = animation.weight;
  20590. if ( keyframe !== animation.currentFrame ) {
  20591. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20592. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20593. this.morphTargetInfluences[ keyframe ] = 0;
  20594. animation.lastFrame = animation.currentFrame;
  20595. animation.currentFrame = keyframe;
  20596. }
  20597. var mix = ( animation.time % frameTime ) / frameTime;
  20598. if ( animation.directionBackwards ) mix = 1 - mix;
  20599. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20600. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20601. }
  20602. };
  20603. /**
  20604. * @author mikael emtinger / http://gomo.se/
  20605. * @author alteredq / http://alteredqualia.com/
  20606. */
  20607. THREE.LensFlarePlugin = function () {
  20608. var _gl, _renderer, _precision, _lensFlare = {};
  20609. this.init = function ( renderer ) {
  20610. _gl = renderer.context;
  20611. _renderer = renderer;
  20612. _precision = renderer.getPrecision();
  20613. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20614. _lensFlare.faces = new Uint16Array( 6 );
  20615. var i = 0;
  20616. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20617. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20618. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20619. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20620. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20621. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20622. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20623. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20624. i = 0;
  20625. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20626. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20627. // buffers
  20628. _lensFlare.vertexBuffer = _gl.createBuffer();
  20629. _lensFlare.elementBuffer = _gl.createBuffer();
  20630. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20631. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20632. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20633. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20634. // textures
  20635. _lensFlare.tempTexture = _gl.createTexture();
  20636. _lensFlare.occlusionTexture = _gl.createTexture();
  20637. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20638. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20639. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20640. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20641. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20642. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20643. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20644. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20645. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20646. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20647. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20648. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20649. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20650. _lensFlare.hasVertexTexture = false;
  20651. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20652. } else {
  20653. _lensFlare.hasVertexTexture = true;
  20654. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20655. }
  20656. _lensFlare.attributes = {};
  20657. _lensFlare.uniforms = {};
  20658. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20659. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20660. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20661. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20662. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20663. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20664. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20665. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20666. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20667. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20668. };
  20669. /*
  20670. * Render lens flares
  20671. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20672. * reads these back and calculates occlusion.
  20673. * Then _lensFlare.update_lensFlares() is called to re-position and
  20674. * update transparency of flares. Then they are rendered.
  20675. *
  20676. */
  20677. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20678. var flares = scene.__webglFlares,
  20679. nFlares = flares.length;
  20680. if ( ! nFlares ) return;
  20681. var tempPosition = new THREE.Vector3();
  20682. var invAspect = viewportHeight / viewportWidth,
  20683. halfViewportWidth = viewportWidth * 0.5,
  20684. halfViewportHeight = viewportHeight * 0.5;
  20685. var size = 16 / viewportHeight,
  20686. scale = new THREE.Vector2( size * invAspect, size );
  20687. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20688. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20689. var uniforms = _lensFlare.uniforms,
  20690. attributes = _lensFlare.attributes;
  20691. // set _lensFlare program and reset blending
  20692. _gl.useProgram( _lensFlare.program );
  20693. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20694. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20695. // loop through all lens flares to update their occlusion and positions
  20696. // setup gl and common used attribs/unforms
  20697. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20698. _gl.uniform1i( uniforms.map, 1 );
  20699. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20700. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20701. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20702. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20703. _gl.disable( _gl.CULL_FACE );
  20704. _gl.depthMask( false );
  20705. var i, j, jl, flare, sprite;
  20706. for ( i = 0; i < nFlares; i ++ ) {
  20707. size = 16 / viewportHeight;
  20708. scale.set( size * invAspect, size );
  20709. // calc object screen position
  20710. flare = flares[ i ];
  20711. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20712. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20713. tempPosition.applyProjection( camera.projectionMatrix );
  20714. // setup arrays for gl programs
  20715. screenPosition.copy( tempPosition )
  20716. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20717. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20718. // screen cull
  20719. if ( _lensFlare.hasVertexTexture || (
  20720. screenPositionPixels.x > 0 &&
  20721. screenPositionPixels.x < viewportWidth &&
  20722. screenPositionPixels.y > 0 &&
  20723. screenPositionPixels.y < viewportHeight ) ) {
  20724. // save current RGB to temp texture
  20725. _gl.activeTexture( _gl.TEXTURE1 );
  20726. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20727. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20728. // render pink quad
  20729. _gl.uniform1i( uniforms.renderType, 0 );
  20730. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20731. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20732. _gl.disable( _gl.BLEND );
  20733. _gl.enable( _gl.DEPTH_TEST );
  20734. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20735. // copy result to occlusionMap
  20736. _gl.activeTexture( _gl.TEXTURE0 );
  20737. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20738. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20739. // restore graphics
  20740. _gl.uniform1i( uniforms.renderType, 1 );
  20741. _gl.disable( _gl.DEPTH_TEST );
  20742. _gl.activeTexture( _gl.TEXTURE1 );
  20743. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20744. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20745. // update object positions
  20746. flare.positionScreen.copy( screenPosition )
  20747. if ( flare.customUpdateCallback ) {
  20748. flare.customUpdateCallback( flare );
  20749. } else {
  20750. flare.updateLensFlares();
  20751. }
  20752. // render flares
  20753. _gl.uniform1i( uniforms.renderType, 2 );
  20754. _gl.enable( _gl.BLEND );
  20755. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20756. sprite = flare.lensFlares[ j ];
  20757. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20758. screenPosition.x = sprite.x;
  20759. screenPosition.y = sprite.y;
  20760. screenPosition.z = sprite.z;
  20761. size = sprite.size * sprite.scale / viewportHeight;
  20762. scale.x = size * invAspect;
  20763. scale.y = size;
  20764. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20765. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20766. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20767. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20768. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20769. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20770. _renderer.setTexture( sprite.texture, 1 );
  20771. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20772. }
  20773. }
  20774. }
  20775. }
  20776. // restore gl
  20777. _gl.enable( _gl.CULL_FACE );
  20778. _gl.enable( _gl.DEPTH_TEST );
  20779. _gl.depthMask( true );
  20780. };
  20781. function createProgram ( shader, precision ) {
  20782. var program = _gl.createProgram();
  20783. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20784. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20785. var prefix = "precision " + precision + " float;\n";
  20786. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  20787. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  20788. _gl.compileShader( fragmentShader );
  20789. _gl.compileShader( vertexShader );
  20790. _gl.attachShader( program, fragmentShader );
  20791. _gl.attachShader( program, vertexShader );
  20792. _gl.linkProgram( program );
  20793. return program;
  20794. };
  20795. };
  20796. /**
  20797. * @author alteredq / http://alteredqualia.com/
  20798. */
  20799. THREE.ShadowMapPlugin = function () {
  20800. var _gl,
  20801. _renderer,
  20802. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20803. _frustum = new THREE.Frustum(),
  20804. _projScreenMatrix = new THREE.Matrix4(),
  20805. _min = new THREE.Vector3(),
  20806. _max = new THREE.Vector3();
  20807. this.init = function ( renderer ) {
  20808. _gl = renderer.context;
  20809. _renderer = renderer;
  20810. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20811. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20812. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20813. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20814. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20815. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20816. _depthMaterial._shadowPass = true;
  20817. _depthMaterialMorph._shadowPass = true;
  20818. _depthMaterialSkin._shadowPass = true;
  20819. _depthMaterialMorphSkin._shadowPass = true;
  20820. };
  20821. this.render = function ( scene, camera ) {
  20822. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20823. this.update( scene, camera );
  20824. };
  20825. this.update = function ( scene, camera ) {
  20826. var i, il, j, jl, n,
  20827. shadowMap, shadowMatrix, shadowCamera,
  20828. program, buffer, material,
  20829. webglObject, object, light,
  20830. renderList,
  20831. lights = [],
  20832. k = 0,
  20833. fog = null;
  20834. // set GL state for depth map
  20835. _gl.clearColor( 1, 1, 1, 1 );
  20836. _gl.disable( _gl.BLEND );
  20837. _gl.enable( _gl.CULL_FACE );
  20838. _gl.frontFace( _gl.CCW );
  20839. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20840. _gl.cullFace( _gl.FRONT );
  20841. } else {
  20842. _gl.cullFace( _gl.BACK );
  20843. }
  20844. _renderer.setDepthTest( true );
  20845. // preprocess lights
  20846. // - skip lights that are not casting shadows
  20847. // - create virtual lights for cascaded shadow maps
  20848. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20849. light = scene.__lights[ i ];
  20850. if ( ! light.castShadow ) continue;
  20851. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20852. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20853. var virtualLight;
  20854. if ( ! light.shadowCascadeArray[ n ] ) {
  20855. virtualLight = createVirtualLight( light, n );
  20856. virtualLight.originalCamera = camera;
  20857. var gyro = new THREE.Gyroscope();
  20858. gyro.position = light.shadowCascadeOffset;
  20859. gyro.add( virtualLight );
  20860. gyro.add( virtualLight.target );
  20861. camera.add( gyro );
  20862. light.shadowCascadeArray[ n ] = virtualLight;
  20863. console.log( "Created virtualLight", virtualLight );
  20864. } else {
  20865. virtualLight = light.shadowCascadeArray[ n ];
  20866. }
  20867. updateVirtualLight( light, n );
  20868. lights[ k ] = virtualLight;
  20869. k ++;
  20870. }
  20871. } else {
  20872. lights[ k ] = light;
  20873. k ++;
  20874. }
  20875. }
  20876. // render depth map
  20877. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20878. light = lights[ i ];
  20879. if ( ! light.shadowMap ) {
  20880. var shadowFilter = THREE.LinearFilter;
  20881. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  20882. shadowFilter = THREE.NearestFilter;
  20883. }
  20884. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  20885. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20886. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20887. light.shadowMatrix = new THREE.Matrix4();
  20888. }
  20889. if ( ! light.shadowCamera ) {
  20890. if ( light instanceof THREE.SpotLight ) {
  20891. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20892. } else if ( light instanceof THREE.DirectionalLight ) {
  20893. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20894. } else {
  20895. console.error( "Unsupported light type for shadow" );
  20896. continue;
  20897. }
  20898. scene.add( light.shadowCamera );
  20899. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20900. }
  20901. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20902. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20903. light.shadowCamera.add( light.cameraHelper );
  20904. }
  20905. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20906. updateShadowCamera( camera, light );
  20907. }
  20908. shadowMap = light.shadowMap;
  20909. shadowMatrix = light.shadowMatrix;
  20910. shadowCamera = light.shadowCamera;
  20911. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20912. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20913. shadowCamera.updateMatrixWorld();
  20914. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20915. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20916. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20917. // compute shadow matrix
  20918. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20919. 0.0, 0.5, 0.0, 0.5,
  20920. 0.0, 0.0, 0.5, 0.5,
  20921. 0.0, 0.0, 0.0, 1.0 );
  20922. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  20923. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  20924. // update camera matrices and frustum
  20925. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20926. _frustum.setFromMatrix( _projScreenMatrix );
  20927. // render shadow map
  20928. _renderer.setRenderTarget( shadowMap );
  20929. _renderer.clear();
  20930. // set object matrices & frustum culling
  20931. renderList = scene.__webglObjects;
  20932. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20933. webglObject = renderList[ j ];
  20934. object = webglObject.object;
  20935. webglObject.render = false;
  20936. if ( object.visible && object.castShadow ) {
  20937. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  20938. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20939. webglObject.render = true;
  20940. }
  20941. }
  20942. }
  20943. // render regular objects
  20944. var objectMaterial, useMorphing, useSkinning;
  20945. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20946. webglObject = renderList[ j ];
  20947. if ( webglObject.render ) {
  20948. object = webglObject.object;
  20949. buffer = webglObject.buffer;
  20950. // culling is overriden globally for all objects
  20951. // while rendering depth map
  20952. // need to deal with MeshFaceMaterial somehow
  20953. // in that case just use the first of material.materials for now
  20954. // (proper solution would require to break objects by materials
  20955. // similarly to regular rendering and then set corresponding
  20956. // depth materials per each chunk instead of just once per object)
  20957. objectMaterial = getObjectMaterial( object );
  20958. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20959. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20960. if ( object.customDepthMaterial ) {
  20961. material = object.customDepthMaterial;
  20962. } else if ( useSkinning ) {
  20963. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20964. } else if ( useMorphing ) {
  20965. material = _depthMaterialMorph;
  20966. } else {
  20967. material = _depthMaterial;
  20968. }
  20969. if ( buffer instanceof THREE.BufferGeometry ) {
  20970. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20971. } else {
  20972. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20973. }
  20974. }
  20975. }
  20976. // set matrices and render immediate objects
  20977. renderList = scene.__webglObjectsImmediate;
  20978. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20979. webglObject = renderList[ j ];
  20980. object = webglObject.object;
  20981. if ( object.visible && object.castShadow ) {
  20982. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20983. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20984. }
  20985. }
  20986. }
  20987. // restore GL state
  20988. var clearColor = _renderer.getClearColor(),
  20989. clearAlpha = _renderer.getClearAlpha();
  20990. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20991. _gl.enable( _gl.BLEND );
  20992. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20993. _gl.cullFace( _gl.BACK );
  20994. }
  20995. };
  20996. function createVirtualLight( light, cascade ) {
  20997. var virtualLight = new THREE.DirectionalLight();
  20998. virtualLight.isVirtual = true;
  20999. virtualLight.onlyShadow = true;
  21000. virtualLight.castShadow = true;
  21001. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21002. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21003. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21004. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21005. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21006. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21007. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21008. virtualLight.shadowDarkness = light.shadowDarkness;
  21009. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21010. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21011. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21012. virtualLight.pointsWorld = [];
  21013. virtualLight.pointsFrustum = [];
  21014. var pointsWorld = virtualLight.pointsWorld,
  21015. pointsFrustum = virtualLight.pointsFrustum;
  21016. for ( var i = 0; i < 8; i ++ ) {
  21017. pointsWorld[ i ] = new THREE.Vector3();
  21018. pointsFrustum[ i ] = new THREE.Vector3();
  21019. }
  21020. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21021. var farZ = light.shadowCascadeFarZ[ cascade ];
  21022. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21023. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21024. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21025. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21026. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21027. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21028. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21029. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21030. return virtualLight;
  21031. }
  21032. // Synchronize virtual light with the original light
  21033. function updateVirtualLight( light, cascade ) {
  21034. var virtualLight = light.shadowCascadeArray[ cascade ];
  21035. virtualLight.position.copy( light.position );
  21036. virtualLight.target.position.copy( light.target.position );
  21037. virtualLight.lookAt( virtualLight.target );
  21038. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21039. virtualLight.shadowDarkness = light.shadowDarkness;
  21040. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21041. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21042. var farZ = light.shadowCascadeFarZ[ cascade ];
  21043. var pointsFrustum = virtualLight.pointsFrustum;
  21044. pointsFrustum[ 0 ].z = nearZ;
  21045. pointsFrustum[ 1 ].z = nearZ;
  21046. pointsFrustum[ 2 ].z = nearZ;
  21047. pointsFrustum[ 3 ].z = nearZ;
  21048. pointsFrustum[ 4 ].z = farZ;
  21049. pointsFrustum[ 5 ].z = farZ;
  21050. pointsFrustum[ 6 ].z = farZ;
  21051. pointsFrustum[ 7 ].z = farZ;
  21052. }
  21053. // Fit shadow camera's ortho frustum to camera frustum
  21054. function updateShadowCamera( camera, light ) {
  21055. var shadowCamera = light.shadowCamera,
  21056. pointsFrustum = light.pointsFrustum,
  21057. pointsWorld = light.pointsWorld;
  21058. _min.set( Infinity, Infinity, Infinity );
  21059. _max.set( -Infinity, -Infinity, -Infinity );
  21060. for ( var i = 0; i < 8; i ++ ) {
  21061. var p = pointsWorld[ i ];
  21062. p.copy( pointsFrustum[ i ] );
  21063. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21064. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21065. if ( p.x < _min.x ) _min.x = p.x;
  21066. if ( p.x > _max.x ) _max.x = p.x;
  21067. if ( p.y < _min.y ) _min.y = p.y;
  21068. if ( p.y > _max.y ) _max.y = p.y;
  21069. if ( p.z < _min.z ) _min.z = p.z;
  21070. if ( p.z > _max.z ) _max.z = p.z;
  21071. }
  21072. shadowCamera.left = _min.x;
  21073. shadowCamera.right = _max.x;
  21074. shadowCamera.top = _max.y;
  21075. shadowCamera.bottom = _min.y;
  21076. // can't really fit near/far
  21077. //shadowCamera.near = _min.z;
  21078. //shadowCamera.far = _max.z;
  21079. shadowCamera.updateProjectionMatrix();
  21080. }
  21081. // For the moment just ignore objects that have multiple materials with different animation methods
  21082. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21083. function getObjectMaterial( object ) {
  21084. return object.material instanceof THREE.MeshFaceMaterial
  21085. ? object.material.materials[ 0 ]
  21086. : object.material;
  21087. };
  21088. };
  21089. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21090. /**
  21091. * @author mikael emtinger / http://gomo.se/
  21092. * @author alteredq / http://alteredqualia.com/
  21093. */
  21094. THREE.SpritePlugin = function () {
  21095. var _gl, _renderer, _precision, _sprite = {};
  21096. this.init = function ( renderer ) {
  21097. _gl = renderer.context;
  21098. _renderer = renderer;
  21099. _precision = renderer.getPrecision();
  21100. _sprite.vertices = new Float32Array( 8 + 8 );
  21101. _sprite.faces = new Uint16Array( 6 );
  21102. var i = 0;
  21103. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21104. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21105. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21106. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21107. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21108. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21109. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21110. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21111. i = 0;
  21112. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21113. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21114. _sprite.vertexBuffer = _gl.createBuffer();
  21115. _sprite.elementBuffer = _gl.createBuffer();
  21116. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21117. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21118. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21119. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21120. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21121. _sprite.attributes = {};
  21122. _sprite.uniforms = {};
  21123. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21124. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21125. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21126. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21127. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21128. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21129. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21130. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21131. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21132. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21133. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21134. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21135. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21136. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21137. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21138. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21139. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21140. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21141. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21142. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21143. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21144. };
  21145. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21146. var sprites = scene.__webglSprites,
  21147. nSprites = sprites.length;
  21148. if ( ! nSprites ) return;
  21149. var attributes = _sprite.attributes,
  21150. uniforms = _sprite.uniforms;
  21151. var invAspect = viewportHeight / viewportWidth;
  21152. var halfViewportWidth = viewportWidth * 0.5,
  21153. halfViewportHeight = viewportHeight * 0.5;
  21154. // setup gl
  21155. _gl.useProgram( _sprite.program );
  21156. _gl.enableVertexAttribArray( attributes.position );
  21157. _gl.enableVertexAttribArray( attributes.uv );
  21158. _gl.disable( _gl.CULL_FACE );
  21159. _gl.enable( _gl.BLEND );
  21160. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21161. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21162. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21163. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21164. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21165. _gl.activeTexture( _gl.TEXTURE0 );
  21166. _gl.uniform1i( uniforms.map, 0 );
  21167. var oldFogType = 0;
  21168. var sceneFogType = 0;
  21169. var fog = scene.fog;
  21170. if ( fog ) {
  21171. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21172. if ( fog instanceof THREE.Fog ) {
  21173. _gl.uniform1f( uniforms.fogNear, fog.near );
  21174. _gl.uniform1f( uniforms.fogFar, fog.far );
  21175. _gl.uniform1i( uniforms.fogType, 1 );
  21176. oldFogType = 1;
  21177. sceneFogType = 1;
  21178. } else if ( fog instanceof THREE.FogExp2 ) {
  21179. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21180. _gl.uniform1i( uniforms.fogType, 2 );
  21181. oldFogType = 2;
  21182. sceneFogType = 2;
  21183. }
  21184. } else {
  21185. _gl.uniform1i( uniforms.fogType, 0 );
  21186. oldFogType = 0;
  21187. sceneFogType = 0;
  21188. }
  21189. // update positions and sort
  21190. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21191. for( i = 0; i < nSprites; i ++ ) {
  21192. sprite = sprites[ i ];
  21193. material = sprite.material;
  21194. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21195. if ( ! material.useScreenCoordinates ) {
  21196. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21197. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21198. } else {
  21199. sprite.z = - sprite.position.z;
  21200. }
  21201. }
  21202. sprites.sort( painterSortStable );
  21203. // render all sprites
  21204. for( i = 0; i < nSprites; i ++ ) {
  21205. sprite = sprites[ i ];
  21206. material = sprite.material;
  21207. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21208. if ( material.map && material.map.image && material.map.image.width ) {
  21209. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21210. if ( material.useScreenCoordinates === true ) {
  21211. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21212. _gl.uniform3f(
  21213. uniforms.screenPosition,
  21214. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21215. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21216. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21217. );
  21218. scale[ 0 ] = _renderer.devicePixelRatio;
  21219. scale[ 1 ] = _renderer.devicePixelRatio;
  21220. } else {
  21221. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21222. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21223. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21224. scale[ 0 ] = 1;
  21225. scale[ 1 ] = 1;
  21226. }
  21227. if ( scene.fog && material.fog ) {
  21228. fogType = sceneFogType;
  21229. } else {
  21230. fogType = 0;
  21231. }
  21232. if ( oldFogType !== fogType ) {
  21233. _gl.uniform1i( uniforms.fogType, fogType );
  21234. oldFogType = fogType;
  21235. }
  21236. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21237. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21238. scale[ 1 ] *= size * sprite.scale.y;
  21239. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21240. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21241. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21242. _gl.uniform1f( uniforms.opacity, material.opacity );
  21243. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21244. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21245. _gl.uniform2fv( uniforms.scale, scale );
  21246. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21247. _renderer.setDepthTest( material.depthTest );
  21248. _renderer.setDepthWrite( material.depthWrite );
  21249. _renderer.setTexture( material.map, 0 );
  21250. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21251. }
  21252. }
  21253. // restore gl
  21254. _gl.enable( _gl.CULL_FACE );
  21255. };
  21256. function createProgram ( shader, precision ) {
  21257. var program = _gl.createProgram();
  21258. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21259. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21260. var prefix = "precision " + precision + " float;\n";
  21261. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21262. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21263. _gl.compileShader( fragmentShader );
  21264. _gl.compileShader( vertexShader );
  21265. _gl.attachShader( program, fragmentShader );
  21266. _gl.attachShader( program, vertexShader );
  21267. _gl.linkProgram( program );
  21268. return program;
  21269. };
  21270. function painterSortStable ( a, b ) {
  21271. if ( a.z !== b.z ) {
  21272. return b.z - a.z;
  21273. } else {
  21274. return b.id - a.id;
  21275. }
  21276. };
  21277. };
  21278. /**
  21279. * @author alteredq / http://alteredqualia.com/
  21280. */
  21281. THREE.DepthPassPlugin = function () {
  21282. this.enabled = false;
  21283. this.renderTarget = null;
  21284. var _gl,
  21285. _renderer,
  21286. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21287. _frustum = new THREE.Frustum(),
  21288. _projScreenMatrix = new THREE.Matrix4();
  21289. this.init = function ( renderer ) {
  21290. _gl = renderer.context;
  21291. _renderer = renderer;
  21292. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21293. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21294. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21295. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21296. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21297. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21298. _depthMaterial._shadowPass = true;
  21299. _depthMaterialMorph._shadowPass = true;
  21300. _depthMaterialSkin._shadowPass = true;
  21301. _depthMaterialMorphSkin._shadowPass = true;
  21302. };
  21303. this.render = function ( scene, camera ) {
  21304. if ( ! this.enabled ) return;
  21305. this.update( scene, camera );
  21306. };
  21307. this.update = function ( scene, camera ) {
  21308. var i, il, j, jl, n,
  21309. program, buffer, material,
  21310. webglObject, object, light,
  21311. renderList,
  21312. fog = null;
  21313. // set GL state for depth map
  21314. _gl.clearColor( 1, 1, 1, 1 );
  21315. _gl.disable( _gl.BLEND );
  21316. _renderer.setDepthTest( true );
  21317. // update scene
  21318. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21319. // update camera matrices and frustum
  21320. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21321. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21322. _frustum.setFromMatrix( _projScreenMatrix );
  21323. // render depth map
  21324. _renderer.setRenderTarget( this.renderTarget );
  21325. _renderer.clear();
  21326. // set object matrices & frustum culling
  21327. renderList = scene.__webglObjects;
  21328. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21329. webglObject = renderList[ j ];
  21330. object = webglObject.object;
  21331. webglObject.render = false;
  21332. if ( object.visible ) {
  21333. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21334. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21335. webglObject.render = true;
  21336. }
  21337. }
  21338. }
  21339. // render regular objects
  21340. var objectMaterial, useMorphing, useSkinning;
  21341. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21342. webglObject = renderList[ j ];
  21343. if ( webglObject.render ) {
  21344. object = webglObject.object;
  21345. buffer = webglObject.buffer;
  21346. // todo: create proper depth material for particles
  21347. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21348. objectMaterial = getObjectMaterial( object );
  21349. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21350. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21351. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21352. if ( object.customDepthMaterial ) {
  21353. material = object.customDepthMaterial;
  21354. } else if ( useSkinning ) {
  21355. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21356. } else if ( useMorphing ) {
  21357. material = _depthMaterialMorph;
  21358. } else {
  21359. material = _depthMaterial;
  21360. }
  21361. if ( buffer instanceof THREE.BufferGeometry ) {
  21362. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21363. } else {
  21364. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21365. }
  21366. }
  21367. }
  21368. // set matrices and render immediate objects
  21369. renderList = scene.__webglObjectsImmediate;
  21370. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21371. webglObject = renderList[ j ];
  21372. object = webglObject.object;
  21373. if ( object.visible ) {
  21374. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21375. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21376. }
  21377. }
  21378. // restore GL state
  21379. var clearColor = _renderer.getClearColor(),
  21380. clearAlpha = _renderer.getClearAlpha();
  21381. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21382. _gl.enable( _gl.BLEND );
  21383. };
  21384. // For the moment just ignore objects that have multiple materials with different animation methods
  21385. // Only the first material will be taken into account for deciding which depth material to use
  21386. function getObjectMaterial( object ) {
  21387. return object.material instanceof THREE.MeshFaceMaterial
  21388. ? object.material.materials[ 0 ]
  21389. : object.material;
  21390. };
  21391. };
  21392. /**
  21393. * @author mikael emtinger / http://gomo.se/
  21394. *
  21395. */
  21396. THREE.ShaderFlares = {
  21397. 'lensFlareVertexTexture': {
  21398. vertexShader: [
  21399. "uniform lowp int renderType;",
  21400. "uniform vec3 screenPosition;",
  21401. "uniform vec2 scale;",
  21402. "uniform float rotation;",
  21403. "uniform sampler2D occlusionMap;",
  21404. "attribute vec2 position;",
  21405. "attribute vec2 uv;",
  21406. "varying vec2 vUV;",
  21407. "varying float vVisibility;",
  21408. "void main() {",
  21409. "vUV = uv;",
  21410. "vec2 pos = position;",
  21411. "if( renderType == 2 ) {",
  21412. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21413. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21414. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21415. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21416. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21417. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21418. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21419. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21420. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21421. "vVisibility = ( visibility.r / 9.0 ) *",
  21422. "( 1.0 - visibility.g / 9.0 ) *",
  21423. "( visibility.b / 9.0 ) *",
  21424. "( 1.0 - visibility.a / 9.0 );",
  21425. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21426. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21427. "}",
  21428. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21429. "}"
  21430. ].join( "\n" ),
  21431. fragmentShader: [
  21432. "uniform lowp int renderType;",
  21433. "uniform sampler2D map;",
  21434. "uniform float opacity;",
  21435. "uniform vec3 color;",
  21436. "varying vec2 vUV;",
  21437. "varying float vVisibility;",
  21438. "void main() {",
  21439. // pink square
  21440. "if( renderType == 0 ) {",
  21441. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21442. // restore
  21443. "} else if( renderType == 1 ) {",
  21444. "gl_FragColor = texture2D( map, vUV );",
  21445. // flare
  21446. "} else {",
  21447. "vec4 texture = texture2D( map, vUV );",
  21448. "texture.a *= opacity * vVisibility;",
  21449. "gl_FragColor = texture;",
  21450. "gl_FragColor.rgb *= color;",
  21451. "}",
  21452. "}"
  21453. ].join( "\n" )
  21454. },
  21455. 'lensFlare': {
  21456. vertexShader: [
  21457. "uniform lowp int renderType;",
  21458. "uniform vec3 screenPosition;",
  21459. "uniform vec2 scale;",
  21460. "uniform float rotation;",
  21461. "attribute vec2 position;",
  21462. "attribute vec2 uv;",
  21463. "varying vec2 vUV;",
  21464. "void main() {",
  21465. "vUV = uv;",
  21466. "vec2 pos = position;",
  21467. "if( renderType == 2 ) {",
  21468. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21469. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21470. "}",
  21471. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21472. "}"
  21473. ].join( "\n" ),
  21474. fragmentShader: [
  21475. "precision mediump float;",
  21476. "uniform lowp int renderType;",
  21477. "uniform sampler2D map;",
  21478. "uniform sampler2D occlusionMap;",
  21479. "uniform float opacity;",
  21480. "uniform vec3 color;",
  21481. "varying vec2 vUV;",
  21482. "void main() {",
  21483. // pink square
  21484. "if( renderType == 0 ) {",
  21485. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21486. // restore
  21487. "} else if( renderType == 1 ) {",
  21488. "gl_FragColor = texture2D( map, vUV );",
  21489. // flare
  21490. "} else {",
  21491. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21492. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21493. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21494. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21495. "visibility = ( 1.0 - visibility / 4.0 );",
  21496. "vec4 texture = texture2D( map, vUV );",
  21497. "texture.a *= opacity * visibility;",
  21498. "gl_FragColor = texture;",
  21499. "gl_FragColor.rgb *= color;",
  21500. "}",
  21501. "}"
  21502. ].join( "\n" )
  21503. }
  21504. };
  21505. /**
  21506. * @author mikael emtinger / http://gomo.se/
  21507. * @author alteredq / http://alteredqualia.com/
  21508. *
  21509. */
  21510. THREE.ShaderSprite = {
  21511. 'sprite': {
  21512. vertexShader: [
  21513. "uniform int useScreenCoordinates;",
  21514. "uniform int sizeAttenuation;",
  21515. "uniform vec3 screenPosition;",
  21516. "uniform mat4 modelViewMatrix;",
  21517. "uniform mat4 projectionMatrix;",
  21518. "uniform float rotation;",
  21519. "uniform vec2 scale;",
  21520. "uniform vec2 alignment;",
  21521. "uniform vec2 uvOffset;",
  21522. "uniform vec2 uvScale;",
  21523. "attribute vec2 position;",
  21524. "attribute vec2 uv;",
  21525. "varying vec2 vUV;",
  21526. "void main() {",
  21527. "vUV = uvOffset + uv * uvScale;",
  21528. "vec2 alignedPosition = position + alignment;",
  21529. "vec2 rotatedPosition;",
  21530. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21531. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21532. "vec4 finalPosition;",
  21533. "if( useScreenCoordinates != 0 ) {",
  21534. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21535. "} else {",
  21536. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21537. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21538. "}",
  21539. "gl_Position = finalPosition;",
  21540. "}"
  21541. ].join( "\n" ),
  21542. fragmentShader: [
  21543. "uniform vec3 color;",
  21544. "uniform sampler2D map;",
  21545. "uniform float opacity;",
  21546. "uniform int fogType;",
  21547. "uniform vec3 fogColor;",
  21548. "uniform float fogDensity;",
  21549. "uniform float fogNear;",
  21550. "uniform float fogFar;",
  21551. "uniform float alphaTest;",
  21552. "varying vec2 vUV;",
  21553. "void main() {",
  21554. "vec4 texture = texture2D( map, vUV );",
  21555. "if ( texture.a < alphaTest ) discard;",
  21556. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21557. "if ( fogType > 0 ) {",
  21558. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21559. "float fogFactor = 0.0;",
  21560. "if ( fogType == 1 ) {",
  21561. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21562. "} else {",
  21563. "const float LOG2 = 1.442695;",
  21564. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21565. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21566. "}",
  21567. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21568. "}",
  21569. "}"
  21570. ].join( "\n" )
  21571. }
  21572. };